php openssl 生成公私钥,根据网上文章整理的
linux下没有问题,win下有报错
<?php $configargs = array( "config" => "/usr/local/php/ext/openssl/tests/openssl.cnf", "digest_alg" => "md5", "private_key_bits" => 4096, "private_key_type" => OPENSSL_KEYTYPE_RSA, // 'digest_alg' => 'md5', // 'x509_extensions' => 'v3_ca', // 'req_extensions' => 'v3_req', // 'private_key_bits' => 666, // 'private_key_type' => OPENSSL_KEYTYPE_RSA, // 'encrypt_key' => false, ); //$res = openssl_pkey_new(); $res = openssl_pkey_new($configargs); // Get private key openssl_pkey_export($res, $privkey, '', $configargs); echo $privkey; echo "<br>"; echo "<br>"; // Get public key $pubkey = openssl_pkey_get_details($res); $pubkey = $pubkey["key"]; echo $pubkey; echo "<br>"; echo "<br>"; // $res = openssl_pkey_get_private($privkey); // if (openssl_sign('hello', $out, $res)) // echo base64_encode($out); $pi_key = openssl_pkey_get_private($privkey);//这个函数可用来判断私钥是否是可用的,可用返回资源id Resource id $pu_key = openssl_pkey_get_public($pubkey);//这个函数可用来判断公钥是否是可用的 $data = "test data";//原始数据 $encrypted = ""; $decrypted = ""; echo "source data:",$data,"\n"; echo "private key encrypt:\n"; openssl_private_encrypt($data,$encrypted,$pi_key);//私钥加密 $encrypted = base64_encode($encrypted);//加密后的内容通常含有特殊字符,需要编码转换下,在网络间通过url传输时要注意base64编码是否是url安全的 echo $encrypted,"\n"; echo "public key decrypt:\n"; openssl_public_decrypt(base64_decode($encrypted),$decrypted,$pu_key);//私钥加密的内容通过公钥可用解密出来 echo $decrypted,"\n"; echo "---------------------------------------\n"; echo "public key encrypt:\n"; openssl_public_encrypt($data,$encrypted,$pu_key);//公钥加密 $encrypted = base64_encode($encrypted); echo $encrypted,"\n"; echo "private key decrypt:\n"; openssl_private_decrypt(base64_decode($encrypted),$decrypted,$pi_key);//私钥解密 echo $decrypted,"\n"; ?>