在一些数据传输的过程中,使用最广的安全加密方法都是用的rsa2,下面说说在php中RSA2的加密,解密以及接口签名和验签的方法。

RSA加密算法

RSA加密算法又称为非对称加密,是提利用两个密钥来进行加密和解密,这两个秘钥分别是公钥(public key)和私钥(private key),非对称加密适合于对安全性要求很高的场景,适合加密少量数据,比如支付数据、CA数字证书等。

常见的非对称加密算法分为 RSA RSA2

非对称加密的优点:需要两组不同的密钥,安全性高,并且两个密钥可以互相解密

非对称加密的缺点:速度慢,只适合对少量的数据进行加密

PHP RSA2 加密算法的方法

RSA2 所使用的公钥和私钥可以利用一些在线工具生成,也可以在liunx系统中通过命令生成。

示例:

//公钥
$publicKey = '-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmvDCCwuz2tmBbnBF1Vlm
Qrww3xyOpZmRjsRLuGpAcRuH7A5hDiS9TslxoVeF8yZHIFsxPEEFYvlE39FxrBd6
T/UjSsEoK5EJWy9YYbycWA13gATCw0joJHGKS2d/sAVcCewvVe4vOiwyLDMKalwV
4TEfBP4dYySvHPMmsCLGUVXx5ygJTn0eza0mchdnZsVDoO1qHGP1Fj/89eCVOtlM
E4mMJD+uCXFtk4r8fnIJYRm4D34WLa2bI/11B089FUcnVe83UziENHPUqi8UqibJ
HQGkq98ZnHWv4VoNKynixzanbEE8Cu+zmbXliabc5qAMB0N974uGCNj3oSa3XTyS
iQIDAQAB
-----END PUBLIC KEY-----';
//下面是要加密的数据
$data = [
    'uid' => '10',
    'name' => 'mochu',
    'host' => 'feiniaomy.com',
];
$publicKey = openssl_pkey_get_public($publicKey); 
//加密后的数据进行base64加密
$rs = openssl_public_encrypt(json_encode($data), $encrypted, $publicKey) ? base64_encode($encrypted) : null; 
//输出加密后的字符串
echo $rs;

输出结果:

ZLD72pVZwO6+JeeDmNNlWdpobmBrpAAn7I5FcV9phuTVh7J+dgKuR5tDSl6Y9p//d7Z3WbEgk0GmQYNcH8Syw8vxkEAms+cyzn+GFsrzwGqivAtoKDRkHFsBC2jNlocKjPlA2qEqUsmGTXY3WPIEpYyLMlgBwN3hAtxsLiUVo05mcSOAbiN3/ovvoYlbygzXJAF0zH/Xix2lvIKquszQm5+G/eweqvwCgppQKEQ4tkGMUkyX+IYDvfr5bZzR/yID5iAyXXNJoes9shed3jV8g91hOiyhDrBp4l/ZbgM3c8ew62+u9qYtxBIAVsGQMN/ZJHKoIBost/mpfpc1qlC5Kg==

PHP RSA2 解密算法的方法

php rsa2 解密算法示例

//上面加密后的数据
$encrypted = 'ZLD72pVZwO6+JeeDmNNlWdpobmBrpAAn7I5FcV9phuTVh7J+dgKuR5tDSl6Y9p//d7Z3WbEgk0GmQYNcH8Syw8vxkEAms+cyzn+GFsrzwGqivAtoKDRkHFsBC2jNlocKjPlA2qEqUsmGTXY3WPIEpYyLMlgBwN3hAtxsLiUVo05mcSOAbiN3/ovvoYlbygzXJAF0zH/Xix2lvIKquszQm5+G/eweqvwCgppQKEQ4tkGMUkyX+IYDvfr5bZzR/yID5iAyXXNJoes9shed3jV8g91hOiyhDrBp4l/ZbgM3c8ew62+u9qYtxBIAVsGQMN/ZJHKoIBost/mpfpc1qlC5Kg==';
//私钥
$privateKey = '-----BEGIN PRIVATE KEY-----
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCa8MILC7Pa2YFu
cEXVWWZCvDDfHI6lmZGOxEu4akBxG4fsDmEOJL1OyXGhV4XzJkcgWzE8QQVi+UTf
0XGsF3pP9SNKwSgrkQlbL1hhvJxYDXeABMLDSOgkcYpLZ3+wBVwJ7C9V7i86LDIs
MwpqXBXhMR8E/h1jJK8c8yawIsZRVfHnKAlOfR7NrSZyF2dmxUOg7WocY/UWP/z1
4JU62UwTiYwkP64JcW2Tivx+cglhGbgPfhYtrZsj/XUHTz0VRydV7zdTOIQ0c9Sq
LxSqJskdAaSr3xmcda/hWg0rKeLHNqdsQTwK77OZteWJptzmoAwHQ33vi4YI2Peh
JrddPJKJ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ClGPWa4OQAl7FGD7vfp8
0Jz0JKf9DKimXO6i8HFnapO6Fko0nVn2MjaPeF93smV3Kosx+pZuqOzK5aEE7rLC
7Qpc9qoiVMD2SJJvZAuL1kKOHyBbZs8fpaHJcPN3aIIjkDphgaeYokJQ5qixB39u
PNOOMZ+rikAEshVb201T5A==
-----END PRIVATE KEY-----';
$key = openssl_pkey_get_private($privateKey); //解析私钥
$encrypted = base64_decode($encrypted); // base64 解密
//解密
$data = openssl_private_decrypt($encrypted, $decrypted, $key) ? json_decode($decrypted,true) : null;
print_r($data);

输出结果:

Array
(
    [uid] => 10
    [name] => mochu
    [host] => feiniaomy.com
)