标签:
rsa加密解密:
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;
标签:
原文地址:http://www.cnblogs.com/simpman/p/4911763.html