rsa加密解密:php
安裝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後生效linux
openssl_pkey_get_private 系列函數,windows下須要加載 extension=php_openssl.dll;linux下extension=openssl.so。android
下載開源RSA密鑰生成工具openssl(一般Linux系統都自帶該程序),解壓縮至獨立的文件夾,進入其中的bin目錄,執行如下命令:
ios
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
nginx
第一條命令生成原始 RSA私鑰文件 rsa_private_key.pem,第二條命令將原始 RSA私鑰轉換爲 pkcs8格式,第三條生成RSA公鑰 rsa_public_key.pem
從上面看出經過私鑰能生成對應的公鑰,所以咱們將私鑰private_key.pem用在服務器端,公鑰發放給android跟ios等前端windows
openssl_pkey_get_privatesass
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;