当前位置:网站首页>Design of PHP asymmetric encryption algorithm (RSA) encryption mechanism
Design of PHP asymmetric encryption algorithm (RSA) encryption mechanism
2022-06-26 13:45:00 【Wild young man】
explain
Asymmetric encryption algorithm You need two keys : Public key (publickey) And a private key (privatekey).
- Public key and private key are a pair , If you encrypt data with a public key , Only the corresponding private key can be used to decrypt ;
- If you encrypt data with a private key , Then only the corresponding public key can be decrypted .
- Because encryption and decryption use two different keys , So this algorithm is called asymmetric encryption algorithm .
Use scenarios
PHP For the client To write API, Add... To the data / Decrypt .
Create private key 、 Public key
// Generate original RSA Private key file
openssl genrsa -out rsa_private_key.pem 1024
// The original RSA Private key to pkcs8 Format
openssl pkcs8 -topk8 -inform PEM -in rsa_private_key.pem -outform PEM -nocrypt -out private_key.pem
// Generate RSA Public key
openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
// We will rsa_private_key.pem Used on the server side , Public key issued to android Follow ios Equal front end .The private key here can use the original or pkcs8 Format , We send the public key to each other for decryption .
Server class library
<?php
/**
* Created by PhpStorm.
* Desc: Rsa class
* 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-----';
/**
* Get private key
* @return bool|resource
*/
private static function getPrivateKey()
{
$privKey = self::$PRIVATE_KEY;
return openssl_pkey_get_private($privKey);
}
/**
* To obtain the public key
* @return bool|resource
*/
private static function getPublicKey()
{
$publicKey = self::$PUBLIC_KEY;
return openssl_pkey_get_public($publicKey);
}
/**
* Private key encryption
* @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;
}
/**
* Public key encryption
* @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;
}
/**
* Private key decryption
* @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;
}
/**
* Public key decryption
* @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;
}
}Class call cases
$rsa = new Rsa();
$data['name'] = 'Tom';
$data['age'] = '20';
$privateEncrypt = $rsa->privateEncrypt(json_encode($data));
echo ' After private key encryption :'.$privateEncrypt.'<br>';
$publicDecrypt = $rsa->publicDecrypt($privateEncrypt);
echo ' After public key decryption :'.$publicDecrypt.'<br>';
$publicEncrypt = $rsa->publicEncrypt(json_encode($data));
echo ' After public key encryption :'.$publicEncrypt.'<br>';
$privateDecrypt = $rsa->privateDecrypt($publicEncrypt);
echo ' After decrypting the private key :'.$privateDecrypt;
边栏推荐
- [MySQL from introduction to mastery] [advanced part] (II) representation of MySQL directory structure and tables in the file system
- sed编辑器
- Jenkins build prompt error: eacces: permission denied
- Chapter 10 setting up structured logging (2)
- 微信小程序注册指引
- Reflect the technical depth (unable to speed up)
- Nlp-d60-nlp competition D29
- Zero basics of C language lesson 8: Functions
- MySQL explanation (I)
- Basic type of typescript
猜你喜欢

Basic configuration and test of Beifu twincat3 NCI in NC axis interface

Network remote access using raspberry pie

Es sauvegarde et restauration des données par instantané

嵌入式virlog代码运行流程

Exercise set 1
![[how to connect the network] Chapter 2 (Part 1): establish a connection, transmit data, and disconnect](/img/e3/a666ba2f48e8edcc7db80503a6156d.png)
[how to connect the network] Chapter 2 (Part 1): establish a connection, transmit data, and disconnect

Common faults of MySQL database - forgetting database password

MySQL讲解(二)

Beifu realizes the control of time slice size and quantity through CTU and ton

ES基於Snapshot(快照)的數據備份和還原
随机推荐
Applicable and inapplicable scenarios of mongodb series
Mysql database explanation (6)
Postman自动化接口测试
免费的机器学习数据集网站(6300+数据集)
ES基於Snapshot(快照)的數據備份和還原
[how to connect the network] Chapter 2 (Part 1): establish a connection, transmit data, and disconnect
NVM installation tutorial
Wechat applet -picker component is repackaged and the disabled attribute is added -- above
Zero basics of C language lesson 7: break & continue
Included angle of 3D vector
Input text to automatically generate images. It's fun!
Guruiwat rushed to the Hong Kong stock exchange for listing: set "multiple firsts" and obtained an investment of 900million yuan from IDG capital
There are many contents in the widget, so it is a good scheme to support scrolling
shell脚本详细介绍(四)
Bifu divides EtherCAT module into multiple synchronization units for operation -- use of sync units
es常用语法一
Beifu PLC realizes data power-off maintenance based on cx5130
Beifu PLC based on NT_ Shutdown to realize automatic shutdown and restart of controller
Basic type of typescript
【Spark】. Explanation of several icons of scala file in idea