非对称加密:简单的实现rsa公钥秘钥生成和加密解密

2023-07-24 16:40:22 浏览765次 作者: 旋风

收藏
<?php
ob_start();
header("Content-type:text/html;charset=utf-8");
error_reporting(1);
if (!extension_loaded('OpenSSL')) {
exit("Need OpenSSL extension");
}
$opensslConfigPath = "E:/phpstudy_pro/Extensions/Apache2.4.39/conf/openssl.cnf"; //apache路径下的openssl.conf文件路径
$config = array(
        "digest_alg" => "sha512",
        "private_key_bits" => 4096,
        "private_key_type" => OPENSSL_KEYTYPE_RSA,
);
$res = openssl_pkey_new($config);
if(!$res) {
//当只生成公钥,无法生成私钥或私钥空白,需要调用openssl.cnf文件才可以
   $config['config'] = $opensslConfigPath;
   $res = openssl_pkey_new($config);
}
/*
//页面显示私钥
openssl_pkey_export($res, $privKey, NULL, $config);
echo $privKey;
*/
//生成私钥存储到private.key文件中
openssl_pkey_export_to_file($res,'./private.key',null,$config);
$pubKey = openssl_pkey_get_details($res);
/*
//页面显示公钥
* echo $pubKey['key'];
*/
//生成公钥存储到private.key文件中
file_put_contents('public.key',$pubKey['key']);
//获取公钥和私钥
$pri_key = file_get_contents('private.key');
$pub_key = file_get_contents('public.key');
//使用公钥加密
$data = '***APP公司经过长时间的运作,设备完善,技术先进,公司环境干净,运营较优。';
openssl_public_encrypt($data, $encrypt_str, $pub_key);
echo '加密后:'.$encrypt_str.'<br/>';
//使用私钥解密:
openssl_private_decrypt($encrypt_str, $unencrypt_text, $pri_key);
echo '<hr />解密后:'.$unencrypt_text.'<br/>';

运行结果如下:

1.png


顺便把公钥和私钥发出来,大家可以看一下格式

一、公钥:

-----BEGIN PUBLIC KEY-----

MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEArrQF6wsZex7qrjNiCcai

abqqZTGcNZ6OYDpwhMoyuCrFPCLi53YoOWQDVgDuiwL7HnVLoK3kmeR3EhJ0YtTt

XVbxaLn11lFkp2rYSM241q6QHwfdZ6upDUeEBYFKYRJYY6UV84xf1FtRIPNCzVTd

DcC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eFoHqyCdOFiLHz5F

OWRT0pueLrjwHjeeoVCIPXGqsrweqHcrbDMmerzuSKYZVpgO0olwWkcF+22J8V6j

bpFflQzR8JYB7jQMHeJX8ADb7AHpmN+So1gPIsQjdeVeVSNNjvG8Tlz9iXeViDSj

55mHygChdmfrqM1arx7Du3WNdgL29GDFCRrA8AfEXRipMax86vVL9rI+9ev80lIZ

WQKCAQEAq6SpBKbUVgw5h6XQHaGqGA/qUgefERlV4P4Hcslk0XxK/mpHAIr+BlBc

ItU548ZeDdtk7PqAfJKKaYuxgWMvLFkSWohJ3ceqbA8H95geHj2OqCazu5A2Xs7i

ZGU9GWbcY0etqrZK5Uf4heelofNubyRn7FN72/qRqm9ZOleFM6JdlMXbqGD6fiwR

52PLTtVRAYxx6RHuPiM2fsvIqiplDO3iboqzNyy9BZohGIdluq+LPup+grOB3eOc

XuzB/PQZB6DTapcYqYr/ZJusJxBa7G2iq3RWCQSQyj6cH3+FwJbp+bZ59fIDaXpt

8PpDdpYcf+a6F4P/pakpUEkOcLM4uA==

-----END PRIVATE KEY-----


当您发现内容错误或代码bug,以及下载链接无法使用等,请点击屏幕右下角的上报错误来进行提交,我们会尽快修正。
本程序所有源码和工具完全免费,当本网站内容如果侵犯了您的权益,请联系我们,我们会尽快处理,感谢您的合作。

收藏 分享

相关文章

评论:

文明上网理性发言,请遵守 新闻评论服务协议

当前还没有评论,快来评论吧

上报错误