//http://www.lampol-blog.com/detail/aid/ZDk5MmFNZ2pJL1pROW5QZU9KZ2FWdVlFTDVHRnRmZm4rNDMzSFlHNg%3D%3D 各种秘钥生成的教程
//生成密钥
$opensslConfigPath = "D:\phpstudy\PHPTutorial\Apache\conf\openssl.cnf";
$config = array(
"digest_alg" => "sha512",
"private_key_bits" =>2048,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
'config'=> $opensslConfigPath
);
//创建密钥对 一定要同步生成 秘钥存储格式也应该正确
例如:/***"-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAplkILBn2LiwpjLvNUqPO
pgNPWDE0xcFBuJKASUND9kPoQ19i5zyue9rSRsvxO9weTkrKi5CEaJxfftSj4YFG
2BXvDmYKCua34Zz2zmjRwTZzX+2gzXicttwxzxNKs8ImNipSstnfot6401Ccp/Vk
ib4eVmhyAV/jMCaauGLsM5dr+Pn+IeHYsykJyaI9Hz4rUed/6LHzUlTKIZcitAyG
1k+Lxl2J1DxY9nZE7PF9wWt9dzX44pCOOKOadLyz9r980RhFF7OsYggoByNu1d8D
VzAqKqHlsNm/iT8623MdgjPKp76dpgPGe947ggLfXC/KIkn880izqEU+pkOMd8sO
UQIDAQAB
-----END PUBLIC KEY-----"***/
$res = openssl_pkey_new($config);
//生成私钥
openssl_pkey_export($res, $privkey, null, $config);
//生成公钥
$pubKey = openssl_pkey_get_details($res)['key'];
print_r($privkey);
echo '
print_r($pubKey);
file_put_contents('private.key',$privkey);
file_put_contents('public.key',$pubKey);
//要加密的数据$data = "Web site:http://www.04007.cn";
echo '加密的数据:'.$data."\n";//私钥加密后的数据
openssl_private_encrypt($data,$encrypted,$private_key);//加密后的内容通常含有特殊字符,需要base64编码转换下
$encrypted = base64_encode($encrypted);
echo "私钥加密后的数据:".$encrypted."\n";
//公钥解密 openssl_public_decrypt(base64_decode($encrypted), $decrypted, $public_key);
echo "公钥解密后的数据:".$decrypted,"\n-------------------------------\n";
//----相反操作。公钥加密 openssl_public_encrypt($data, $encrypted, $public_key);
$encrypted = base64_encode($encrypted);
echo "公钥加密后的数据:".$encrypted."\n";
openssl_private_decrypt(base64_decode($encrypted), $decrypted, $private_key);//私钥解密
echo "私钥解密后的数据:".$decrypted."\n";
?>