当前位置:网站首页>PHP非对称加密算法(RSA)加密机制设计
PHP非对称加密算法(RSA)加密机制设计
2022-06-26 12:53:00 【狂野小青年】
解释
非对称加密算法需要两个密钥:公钥(publickey)和私钥(privatekey)。
- 公钥与私钥是一对,如果用公钥对数据进行加密,只有用对应的私钥才能解密;
- 如果用私钥对数据进行加密,那么只有用对应的公钥才能解密。
- 因为加密和解密使用的是两个不同的密钥,所以这种算法叫作非对称加密算法。
使用场景
PHP 为客户端 编写API,对数据加/解密。
创建私钥、公钥
//生成原始 RSA私钥文件
openssl genrsa -out rsa_private_key.pem 1024
//将原始 RSA私钥转换为 pkcs8格式
openssl pkcs8 -topk8 -inform PEM -in rsa_private_key.pem -outform PEM -nocrypt -out private_key.pem
//生成RSA公钥
openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
//我们将私钥rsa_private_key.pem用在服务器端,公钥发放给android跟ios等前端。这里的私钥可以用原始的或者pkcs8格式,我们把公钥发给对方用于解密。
服务端类库
<?php
/**
* Created by PhpStorm.
* Desc: Rsa类
* Coder: Wanzhou Chen
* Date: 2022-06-24
* Time: 14:46
*/
class Rsa
{
private static $PRIVATE_KEY = '-----BEGIN PRIVATE KEY-----
MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMPqHJl5n3rCSv0J
XtCTdeNrD/XG+7GoJPsGYvjK1n7KxJMjXncslrWpVtKqX4fqxbS7Ervd93AZ5sG1
xzx8CNZoUjl4Pb8oJLRgoEA4NIszptucsXckzGd0zkC2vITYJ1vZTChuRkyis2Kj
DaGTfvFPkh7i8yTN30M5GrZptL31AgMBAAECgYAXw/iALZ7I93S9STu1NY4hbkVb
XS3/GRSTVuz+nSxz6Qj7iFjXQBNwKgCcQYqhJDujduYI4B45/QpfCTwH/Evd77EV
W36zjJLydIfwEMoFrIs4aATsi4/5XQ9Up3oM4e3tQLO+DX79QmATPGdTt4zAAn2+
F6XY7uXxt4LPkUxeKQJBAP8/vwP04AIZLOSZxnJVAI8HISzGsbx0cElNP9d84jS2
UcbeeVF6hrRZgtl9BfdndFGnFaq79E2MolMOmoWGiQMCQQDEfay75frt7zkwFQLt
SOOhDZGAbPmO1u/86yXgpIrf47PAmu9IK3Nzr4rCuFcfIsXbBRmpb+jMGKV9Hl1S
Hh+nAkEAqcV2gWUwUXT5PRtiuMz80CUH1cZalWRFAxxUaDlyI2lYvxNeUelTC0W2
GH5lp4ayAVVGvgbBmYr+tIu0DzfKjQJBAKmUUSzFWmBZMwD1UVZaruIDZMzywBrw
E6UziLgtKhH6YdtbnCGsJnL0UIynLcGYcCwLZc9e3wquRr0KJL5Hc0cCQDk6S9sM
M8PFGi1zJu4U9I113lta0SsIrxBv5qsHAHWwFuQ/s+UPcMvg8pzjuUL3K7DQJNvw
RusjJNMUOQ0oWeM=
-----END PRIVATE KEY-----';
private static $PUBLIC_KEY = '-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDD6hyZeZ96wkr9CV7Qk3Xjaw/1
xvuxqCT7BmL4ytZ+ysSTI153LJa1qVbSql+H6sW0uxK73fdwGebBtcc8fAjWaFI5
eD2/KCS0YKBAODSLM6bbnLF3JMxndM5AtryE2Cdb2UwobkZMorNiow2hk37xT5Ie
4vMkzd9DORq2abS99QIDAQAB
-----END PUBLIC KEY-----';
/**
* 获取私钥
* @return bool|resource
*/
private static function getPrivateKey()
{
$privKey = self::$PRIVATE_KEY;
return openssl_pkey_get_private($privKey);
}
/**
* 获取公钥
* @return bool|resource
*/
private static function getPublicKey()
{
$publicKey = self::$PUBLIC_KEY;
return openssl_pkey_get_public($publicKey);
}
/**
* 私钥加密
* @param string $data
* @return null|string
*/
public static function privateEncrypt($data = '')
{
if (!is_string($data)) {
return null;
}
return openssl_private_encrypt($data, $encrypted, self::getPrivateKey()) ? base64_encode($encrypted) : null;
}
/**
* 公钥加密
* @param string $data
* @return null|string
*/
public static function publicEncrypt($data = '')
{
if (!is_string($data)) {
return null;
}
return openssl_public_encrypt($data, $encrypted, self::getPublicKey()) ? base64_encode($encrypted) : null;
}
/**
* 私钥解密
* @param string $encrypted
* @return null
*/
public static function privateDecrypt($encrypted = '')
{
if (!is_string($encrypted)) {
return null;
}
return (openssl_private_decrypt(base64_decode($encrypted), $decrypted, self::getPrivateKey())) ? $decrypted : null;
}
/**
* 公钥解密
* @param string $encrypted
* @return null
*/
public static function publicDecrypt($encrypted = '')
{
if (!is_string($encrypted)) {
return null;
}
return (openssl_public_decrypt(base64_decode($encrypted), $decrypted, self::getPublicKey())) ? $decrypted : null;
}
}类调用案例
$rsa = new Rsa();
$data['name'] = 'Tom';
$data['age'] = '20';
$privateEncrypt = $rsa->privateEncrypt(json_encode($data));
echo '私钥加密后:'.$privateEncrypt.'<br>';
$publicDecrypt = $rsa->publicDecrypt($privateEncrypt);
echo '公钥解密后:'.$publicDecrypt.'<br>';
$publicEncrypt = $rsa->publicEncrypt(json_encode($data));
echo '公钥加密后:'.$publicEncrypt.'<br>';
$privateDecrypt = $rsa->privateDecrypt($publicEncrypt);
echo '私钥解密后:'.$privateDecrypt;
边栏推荐
- 【MySQL从入门到精通】【高级篇】(二)MySQL目录结构与表在文件系统中的表示
- There are many contents in the widget, so it is a good scheme to support scrolling
- Solutions to insufficient display permissions of find and Du -sh
- Prototype
- Thinking caused by the error < note: candidate expectations 1 argument, 0 provided >
- 古瑞瓦特冲刺港交所上市:创下“多个第一”,获IDG资本9亿元投资
- 计算两点之间的距离(二维、三维)
- HDU 3555 Bomb
- Beifu twincat3 can read and write CSV and txt files
- 33、使用RGBD相机进行目标检测和深度信息输出
猜你喜欢

Electron official docs series: Get Started

ES6 module

Detailed sorting of HW blue team traceability process
![[how to connect the network] Chapter 2 (next): receiving a network packet](/img/f5/33e1fd8636fcc80430b3860d069866.png)
[how to connect the network] Chapter 2 (next): receiving a network packet

微信小程序注册指引
![[how to connect the network] Chapter 1: the browser generates messages](/img/6b/e85f29ba97c261e01e177b5e77c423.png)
[how to connect the network] Chapter 1: the browser generates messages

三维向量的夹角

Included angle of 3D vector

ES基於Snapshot(快照)的數據備份和還原

Guruiwat rushed to the Hong Kong stock exchange for listing: set "multiple firsts" and obtained an investment of 900million yuan from IDG capital
随机推荐
Electron official docs series: Best Practices
es常用语法一
Beifu cx5130 card replacement and transfer of existing authorization files
Reflect the technical depth (unable to speed up)
7-2 a Fu the thief
Uva10341 solve it
Go language - pipeline channel
A few lines of code can realize complex excel import and export. This tool class is really powerful!
微信小程序注册指引
Log in to the server using SSH key pair
MySQL数据库讲解(六)
Bigint: handles large numbers (integers of any length)
Detailed practical sharing, two hours of funny videos after work, earning more than 7000 a month
HDU 3555 Bomb
Basic type of typescript
Beifu PLC realizes data power-off maintenance based on cx5130
Nexys A7开发板资源使用技巧
Coprime and non coprime of template problems of Chinese remainder theorem
Awk tools
Ubuntu installation and configuration PostgreSQL (18.04)