//创建公钥和私钥 $res=openssl_pkey_new(array(‘private_key_bits‘ => 512)); #此处512必须不能包含引号。 //提取私钥 openssl_pkey_export($res, $private_key); //生成公钥 $public_key=openssl_pkey_get_details($res); $public_key=$public_key["key"]; //显示数据 var_dump($private_key); var_dump($public_key); //要加密的数据 $data = "Web site:http://www.xnbzg.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";
运行结果
[[email protected] ~]# php -f makersa.php string(522) "-----BEGIN PRIVATE KEY----- MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEA2tIoxjY4S02v7HVn g9b20Q8Cjbq6dnAAbC1naNwGZzEEqmR4GKNvTFEdp+O8e945lKa79goCYjdVoyxL S3SKjQIDAQABAkEAhpxaMPUR1GFKI/BlaZlH5HuTWpTQOCPWXrXfs4YG+lrtwd8P vEKSJeRNCWWpY0zwOoDQQBB9JBO6wlnsI1JcAQIhAPeDqBlLX1Q2F//h1OdPYUIR 1r0VbqiAOMTmCzmzSRTBAiEA4lKr5r5RC0+VraZxq1W/UBuBuQYKcLAUQ4l2a40N 7M0CIC56389YMx+qRNl9fDCv3HC+zteVNcGYypBXLtZ4D4pBAiAUa3MZEYjMZXTS wxa0Z7soJiMxJ2tfuXNKmKd3krVz7QIgDWHPu3yTDhYbK2nV41iDuJ/oSZnZb7S8 9uGYFrj+ZyE= -----END PRIVATE KEY----- " string(182) "-----BEGIN PUBLIC KEY----- MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANrSKMY2OEtNr+x1Z4PW9tEPAo26unZw AGwtZ2jcBmcxBKpkeBijb0xRHafjvHveOZSmu/YKAmI3VaMsS0t0io0CAwEAAQ== -----END PUBLIC KEY----- " 加密的数据:Web site:http://www.xnbzg.cn 私钥加密后的数据:PKbSJnCiWqNB58fXG9aBXyDTudd/GnEYQtG7mK80/+Z3IaGu5wORL5Cwq7l9b00Xtao6w2tnboEz+D+O/c4m+w== 公钥解密后的数据:Web site:http://www.xnbzg.cn ------------------------------- 公钥加密后的数据:Pq0Sm4pWSrF7wtckqbdjAaU7H002zdfw5ZmL4wMyTdzqxwS9bNyw5k4DFnZZKCKN26gu3bhikd5G7zXl22y1rQ== 私钥解密后的数据:Web site:http://www.xnbzg.cn
时间: 2024-10-25 16:53:24