Detailed introduction to PHP using openssl extension to implement public key encryption

黄舟
Release: 2023-03-06 16:20:02
Original
1169 people have browsed it

Use openssl command to generate public and private keys

// 生成私钥
# openssl genrsa -out rsa_private_key.pem 1024
// 生成公钥
# openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
Copy after login


The following is the sample code:

<?php
// openssl 扩展检测
var_dump(extension_loaded(&#39;openssl&#39;));

$prikey = openssl_pkey_get_private(file_get_contents(&#39;rsa_private_key.pem&#39;)); //私钥
$pubkey = openssl_pkey_get_public(file_get_contents(&#39;rsa_public_key.pem&#39;)); //公钥

// 明文数据
$data = &#39;test-string!&#39;;

/**
 * 可能会出的问题:Don&#39;t know how to get public key from this private key
 * 原因:PHP 的 openssl 扩展和 Apache 的不一致导致, 当然在命令行下运行程序则不会出现此问题
 */
// 公钥加密
$encrypt_data = &#39;&#39;;
openssl_public_encrypt($data, $encrypt_data, $pubkey);
$encrypt_data = base64_encode($encrypt_data);
echo $encrypt_data;
echo &#39;<br/>&#39;;


// ------------------------------------------------------------


// 私钥解密
$encrypt_data = base64_decode($encrypt_data);
openssl_private_decrypt($encrypt_data, $decrypt_data, $prikey);
var_dump($decrypt_data);
Copy after login



The above is the detailed content of Detailed introduction to PHP using openssl extension to implement public key encryption. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!