Home >Backend Development >PHP Tutorial >Detailed explanation of the steps to implement public key encryption using PHP+openssl extension
This time I will bring you a detailed explanation of the steps to implement public key encryption with the PHP openssl extension. What are the precautions for the PHP openssl extension to implement public key encryption. The following is a practical case, let's take a look.
looks like this:
// 生成私钥 # openssl genrsa -out rsa_private_key.pem 1024 // 生成公钥 # openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
Here is the sample code:
<?php // openssl 扩展检测 var_dump(extension_loaded('openssl')); $prikey = openssl_pkey_get_private(file_get_contents('rsa_private_key.pem')); //私钥 $pubkey = openssl_pkey_get_public(file_get_contents('rsa_public_key.pem')); //公钥 // 明文数据 $data = 'test-string!'; /** * 可能会出的问题:Don't know how to get public key from this private key * 原因:PHP 的 openssl 扩展和 Apache 的不一致导致, 当然在命令行下运行程序则不会出现此问题 */ // 公钥加密 $encrypt_data = ''; openssl_public_encrypt($data, $encrypt_data, $pubkey); $encrypt_data = base64_encode($encrypt_data); echo $encrypt_data; echo '<br/>'; // ------------------------------------------------------------ // 私钥解密 $encrypt_data = base64_decode($encrypt_data); openssl_private_decrypt($encrypt_data, $decrypt_data, $prikey); var_dump($decrypt_data);
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
Detailed explanation of the steps for PHP local API interface testing
Detailed explanation of the payment steps for php server integration with Alipay APP
Detailed explanation of the steps for PHP to use PDO to operate mysql to read data
The above is the detailed content of Detailed explanation of the steps to implement public key encryption using PHP+openssl extension. For more information, please follow other related articles on the PHP Chinese website!