需要用到:
2、php扩展php_openssl
openssl_private_decrypt — 使用私钥解密数据
openssl_private_encrypt — 使用私钥加密数据
openssl_public_decrypt — 使用公钥解密数据
openssl_public_encrypt — 使用公钥加密数据
通过生成获取了私钥与公钥
私钥:
-----BEGIN PUBLIC KEY-----
MIIBITANBgkqhkiG9w0BAQEFAAOCAQ4AMIIBCQKCAQBnTj4S97mYkJePENDd1SR6
sFjFFCdPQ1KTa+fPsv1VRP4+9FtDwj4Oz5MQeaw0I0hOFIjEy2wVNds5dXbY3njK
KVSw13CcQ7AtsoEy5i/gGhwEiaZewC8Of2FsHGBc5Agw99Pbbbgj+nXlPGfax4x1
+3uB3xIWc9ivnWKvTC3eV2bjvXj46d7Cz0Vn9Y0xAFY8hiY2F+jV2iJO9cNuyPWP
icIEHCfDv3WnXNU3WvwdaxVXTrGsOMIVjL4w9yhdoSFLigmUKvY0pQOaakSQaR4a
GvkznndEzVyjaQqmIAZHeoaUeGAdKyyk4GTFJyHz+QeW2S4vdatSwHoQX/yunLDV
AgMBAAE=
-----END PUBLIC KEY-----
公钥:
-----BEGIN RSA PRIVATE KEY-----
MIIEoQIBAAKCAQBnTj4S97mYkJePENDd1SR6sFjFFCdPQ1KTa+fPsv1VRP4+9FtD
wj4Oz5MQeaw0I0hOFIjEy2wVNds5dXbY3njKKVSw13CcQ7AtsoEy5i/gGhwEiaZe
wC8Of2FsHGBc5Agw99Pbbbgj+nXlPGfax4x1+3uB3xIWc9ivnWKvTC3eV2bjvXj4
6d7Cz0Vn9Y0xAFY8hiY2F+jV2iJO9cNuyPWPicIEHCfDv3WnXNU3WvwdaxVXTrGs
OMIVjL4w9yhdoSFLigmUKvY0pQOaakSQaR4aGvkznndEzVyjaQqmIAZHeoaUeGAd
Kyyk4GTFJyHz+QeW2S4vdatSwHoQX/yunLDVAgMBAAECggEAQ9pqfz7jUsg2JCwh
ZHNpIITP6bKRF0ja5iXL/upL50QH0wXhJCJjbIr+x6WDbEN4bICkTM5oUY4sThNP
WqbVo8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02WuMIGwNSR4FjY/ZtK3ei/Dd4x3a/Iv/Mb1eo
z50zvSHGS1icNS0ESJlG0UdDNefohsex8Ylfd9pPr+4fwPxcJQ==
-----END RSA PRIVATE KEY-----
一般使用会将私钥的保存在服务器,公钥保存在客户端
代码演示:
//RAS加密
$private = '-----BEGIN RSA PRIVATE KEY-----
MIIEoQIBAAKCAQBnTj4S97mYkJePENDd1SR6sFjFFCdPQ1KTa+fPsv1VRP4+9FtD
wj4Oz5MQeaw0I0hOFIjEy2wVNds5dXbY3njKKVSw13CcQ7AtsoEy5i/gGhwEiaZe
wC8Of2FsHGBc5Agw99Pbbbgj+nXlPGfax4x1+3uB3xIWc9ivnWKvTC3eV2bjvXj4
6d7Cz0Vn9Y0xAFY8hiY2F+jV2iJO9cNuyPWPicIEHCfDv3WnXNU3WvwdaxVXTrGs
OMIVjL4w9yhdoSFLigmUKvY0pQOaakSQaR4aGvkznndEzVyjaQqmIAZHeoaUeGAd
Kyyk4GTFJyHz+QeW2S4vdatSwHoQX/yunLDVAgMBAAECggEAQ9pqfz7jUsg2JCwh
ZHNpIITP6bKRF0ja5iXL/upL50QH0wXhJCJjbIr+x6WDbEN4bICkTM5oUY4sThNP
WqbVo8N98yGuv5TeFUXYArya2ZGMsZZQBpAo2FbmgIIq8Rh+INvG9auddVQ/N7Bz
bon/QkdKGkWQtdqlisPPW+CniA/+rSYpmXB4ygeGq/gp8n1BBQy8b4PlftVyQ2Gt
texbuBNr4a8PQ5DztkUdNArV4jzkeOkvk6lZmq8RWCwSWzo2QLuYS4ZfRvhcCwV4
x7E5mNBNLPGhY+ZK0U8i0L3zyBBnBhKLS6vCOpdJrXEUUrc2eGxZBIPemxGB3Okd
bPbTyQKBgQCoR5+oaeAd4bAFEF7kOJhisgky9a2lzJAfgEX7lX06lzulWnnlLUs5
qf1tG61e56NoF8SFweLqXJ50V/ZqTEtJgrTgPsnjesJefEfqbHQ+Pcxr9ZOhpTC3
w7+NDavQ3oK+qBYX7hLgofIo/T8n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XNU3WvwdaxVXTrGsOMIVjL4w9yhdoSFLigmUKvY0pQOaakSQaR4a
GvkznndEzVyjaQqmIAZHeoaUeGAdKyyk4GTFJyHz+QeW2S4vdatSwHoQX/yunLDV
AgMBAAE=
-----END PUBLIC KEY-----';
//私钥加密
$data = 'mysql Darren hhhhhh'; //要加密的内容
$centent = ''; // 加密后的值,会传递到这里,引用传值
//第一个形参为 要加密的数据 ,第二个是引用传值,加密后的数据会被保存在$centent变量,第三个是加密的私钥
$res = openssl_private_encrypt($data,$centent,$private); //成功返回true ,失败返回false
var_dump($centent,$res);
echo '
';
//公钥解密
$value = '';// 加密后的值,会传递到这里,引用传值
//第一个形参为 要解密的数据 ,第二个是引用传值,解密后的数据会被保存在$value变量,第三个是解密的公钥
$res = openssl_public_decrypt($centent,$value,$public); //成功返回true ,失败返回false
var_dump($value,$res);
结果: