php服务端与客户端交互、提供开放api时,通常需要对敏感的部分api数据传输进行数据加密,这时候rsa非对称加密就能派上用处了,下面通过一个例子来说明如何用php来实现数据的加密解密
生成公钥、私钥
1 2 3
| 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
|
PHP进行加密解密
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| <?php
$privateKeyFilePath = 'rsa_private_key.pem';
$publicKeyFilePath = 'rsa_public_key.pem'; extension_loaded('openssl') or die('php需要openssl扩展支持'); (file_exists($privateKeyFilePath) && file_exists($publicKeyFilePath)) or die('密钥或者公钥的文件路径不正确');
$privateKey = openssl_pkey_get_private(file_get_contents($privateKeyFilePath));
$publicKey = openssl_pkey_get_public(file_get_contents($publicKeyFilePath)); ($privateKey && $publicKey) or die('密钥或者公钥不可用');
$originalData = '我的帐号是:shiki,密码是:matata';
$encryptData = ''; echo '原数据为:', $originalData, PHP_EOL;
if (openssl_private_encrypt($originalData, $encryptData, $privateKey)) {
echo '加密成功,加密后数据(base64_encode后)为:', base64_encode($encryptData), PHP_EOL; } else { die('加密失败'); }
$decryptData =''; if (openssl_public_decrypt($encryptData, $decryptData, $publicKey)) { echo '解密成功,解密后数据为:', $decryptData, PHP_EOL; } else { die('解密成功'); }
|