The example in this article describes PHP's rsa encryption and decryption based on openssl. Share it with everyone for your reference, the details are as follows:
"D:/phpserver/Lighttpd/openssl.cnf", //'config' =>'D:/phpStudy/Lighttpd/OpenSSL.cnf', 'private_key_bits' => 1024, // Size of Key. 'private_key_type' => OPENSSL_KEYTYPE_RSA ); //$res = openssl_pkey_new(); $res = openssl_pkey_new($config); // Get private key // openssl_pkey_export($res, $privkey, "PassPhrase number 1" ); openssl_pkey_export($res, $privkey); var_dump($privkey); // Get public key $pubkey=openssl_pkey_get_details($res); // echo "------------>
"; // print_r($pubkey["rsa"]); // $bin_str=$pubkey["rsa"]["n"]; // print_r($bin_str); // echo "
"; // //echo $bin_hex_str = pack("H*" , bin2hex($bin_str)); // echo $bin_hex_str = bin2hex($bin_str); // echo "
------------<
"; $pubkey=$pubkey["key"]; // var_dump($privkey); // var_dump($pubkey); echo $privkey."
"; echo $pubkey."
"; ?>
----------------------
"; $data = "woshizhu";//原始数据 $encrypted = ""; $decrypted = ""; echo "source data:",$data,"
"; echo "private key encrypt:\n"; openssl_private_encrypt($data,$encrypted,$pi_key);//私钥加密 $encrypted = base64_encode($encrypted);//加密后的内容通常含有特殊字符,需要编码转换下,在网络间通过url传输时要注意base64编码是否是url安全的 echo "
----------私钥加密------------
"; echo $encrypted,"
"; echo "
----------私钥加密------------
"; echo "public key decrypt:\n"; $decrypted=""; 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"; $decrypted=""; //$encrypted="JBeapcp9iWWYJYElgqtrZxfxM4wVkCaSn/oJZ7NjfR23o76fdbxEXpf+PGWACw3PeTdObwL4108wR3ihKmy2iYkIExGjBYyvx2w9aHies8ZsOIP3LjiMHYTm93Rr8Sc5XxHWQc3Dhbq16JWHYZ2d+RrOpHd4x84GF3JXwivrGO4="; echo "private key decrypt:\n"; openssl_private_decrypt(base64_decode($encrypted),$decrypted,$pi_key);//私钥解密 echo "--->:".$decrypted,"\n"; ?>
I hope this article will be helpful to everyone in PHP programming.
For more articles related to PHP's rsa encryption and decryption examples based on openssl, please pay attention to the PHP Chinese website!