RSA加密解密

rsa加密解密:

安装openssl:

切换到php安装目录的etx/openssl目录
cd /home/tao/soft/php-5.2.13/ext/openssl
openssl目录下有个config.w32和config0.m4,把config0.m4改名为config.m4(原因不解释)
mv config0.m4 config.m4
$PHP_PREFIX/bin/phpize或直接/usr/local/bin/phpize
./configure --with-openssl --with-php-config=/usr/local/php/bin/php-config
make
make test
make install

在php.ini内加入以下内容:
extension_dir = "/usr/local/php/lib/php/extensions/no-debug-non-zts-20060613/"
extension = "openssl.so"

重启php、nginx后生效

 

openssl_pkey_get_private 系列函数,windows下需要加载 extension=php_openssl.dll;linux下extension=openssl.so。

 

下载开源RSA密钥生成工具openssl(通常Linux系统都自带该程序),解压缩至独立的文件夹,进入其中的bin目录,执行以下命令:

openssl genrsa -out rsa_private_key.pem 1024
openssl pkcs8 -topk8 -inform PEM -in rsa_private_key.pem -outform PEM -nocrypt -out private_key.pem
openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem

第一条命令生成原始 RSA私钥文件 rsa_private_key.pem,第二条命令将原始 RSA私钥转换为 pkcs8格式,第三条生成RSA公钥 rsa_public_key.pem
从上面看出通过私钥能生成对应的公钥,因此我们将私钥private_key.pem用在服务器端,公钥发放给android跟ios等前端

 

openssl_pkey_get_private

openssl_pkey_get_public

 

openssl_private_encrypt

openssl_public_decrypt

openssl_public_encrypt

openssl_private_decrypt

 

<?php

//私钥加密,公钥解密
$privateFile = "rsa_private_key.pem";
$privateKey = file_get_contents($privateFile);

$pi_key =  openssl_pkey_get_private($privateKey);
//print_r($pi_key);echo "\n"; 
$data = "aassssasssddd";//原始数据  
echo "source:".$data."\n";
$encrypted = "";   
$decrypted = "";   


openssl_private_encrypt($data,$encrypted,$pi_key);//私钥加密  
echo $encrypted."||||\n";
$encrypted = base64_encode($encrypted);
echo $encrypted,"\n"; 

$publicFile = "rsa_public_key.pem";
$publicKey = file_get_contents($publicFile);
$pu_key = openssl_pkey_get_public($publicKey);

openssl_public_decrypt(base64_decode($encrypted),$decrypted,$pu_key);//私钥加密的内容通过公钥可用解密出来  
echo $decrypted,"\n";

//公钥加密,私钥解密 
$data = "abcdefg";
openssl_public_encrypt($data,$encrypted,$pu_key);

openssl_private_decrypt($encrypted,$decrypted,$pi_key);
echo $decrypted;

 

posted @ 2015-10-26 17:08  simpman  阅读(694)  评论(0编辑  收藏  举报