##新建openssl.php
[root@iz2vcf47jzvf8dxrapolf7z test]# cat openssl.php
/**
* 私钥加密/公钥解密
*
* @param $str string 待加解密字符串
* @param $isEncrypt boolean
* return string|null
*/
function opensslPrivateEncrypt($str, $isEncrypt = true)
{
if($isEncrypt){
$privateKey = file_get_contents('./rsa_private_key.pem');
$privateKey = openssl_pkey_get_private($privateKey);
return openssl_private_encrypt($str, $encryptedStr, $privateKey)
? base64_encode($encryptedStr) : null;
}else{
$publicKey = file_get_contents('./rsa_public_key.pem');
$publicKey = openssl_pkey_get_public($publicKey);
return (openssl_public_decrypt(base64_decode($str), $decryptedStr, $publicKey))
? $decryptedStr : null;
}
}
/**
* 公钥加密/私钥解密
*
* @param $str string 待加解密字符串
* @param $isEncrypt boolean
* return string|null
*/
function opensslPublicEncrypt($str , $isEncrypt = true)
{
if($isEncrypt){
$publicKey = file_get_contents('./rsa_public_key.pem');
$publicKey = openssl_pkey_get_public($publicKey);
return openssl_public_encrypt($str, $encryptedStr, $publicKey)
? base64_encode($encryptedStr) : null;
}else{
$privateKey = file_get_contents('./rsa_private_key.pem');
$privateKey = openssl_pkey_get_private($privateKey);
return (openssl_private_decrypt(base64_decode($str), $decryptedStr, $privateKey))
? $decryptedStr : null;
}
}
$config = array();
$config['title'] = 'PHP is the best program language.';
$config['comment'] = 'PHPERS are great people.';
$privateEncrypt = opensslPrivateEncrypt(json_encode($config));
echo("##privateEncrypt is:" . PHP_EOL);
echo($privateEncrypt . PHP_EOL);
$privateDecrypt = opensslPrivateEncrypt($privateEncrypt, false);
echo("##privateDecrypt is:" . PHP_EOL);
echo($privateDecrypt . PHP_EOL);
$publicEncrypt = opensslPublicEncrypt(json_encode($config));
echo("##publicEncrypt is:" . PHP_EOL);
echo($publicEncrypt . PHP_EOL);
$publicDecrypt = opensslPublicEncrypt($publicEncrypt, false);
echo("##publicDecrypt is:" . PHP_EOL);
echo($publicDecrypt . PHP_EOL);
##执行脚本
[root@iz2vcf47jzvf8dxrapolf7z test]# php openssl.php
##privateEncrypt is:
mLrLIAwbwlE69Yj5/lnNw1t8qSjhnFa+96s/kSMYweAn/HEsV7jfVAJ6mn/FY2DRRWkKeOnguUYsRcFTBcS1ieG7UtqbUAASXA5dwVgtTrFoDcDhHMl7p90+dIO8n+vMoBx1kkUegpvtH03y3MgUVSj/BLkLE8jrFXyjGufIcv0=
##privateDecrypt is:
{"title":"PHP is the best program language.","comment":"PHPERS are great people."}
##publicEncrypt is:
NW2k5m2pKrZmEMSHXiK7mfyC+yDjH1+b6TrEMPv+ywBfsUlo2P8eWwcXOQxvsV4UG87a1S4Xa2QySntdEwhpYoim97457ODVVCb6jx+cqqdWJ1wlLS+gx7FJxw7Z0kMPmCm5iMcQwWPK+UzF+dpc/gJFa9uGAAmYczUumOauAx0=
##publicDecrypt is:
{"title":"PHP is the best program language.","comment":"PHPERS are great people."}