PHP RSA2 encryption and decryption and interface signature and verification

Is it under development? We often have to deal with interfaces. Whether it is to call someone else's interface or provide someone with an interface, how to ensure the security and consistency of the data of both parties when the interface is called? This involves data encryption and signature verification services. This article uses PHP examples to explain the implementation of RSA2 data encryption and decryption and signature verification functions.

In the previous article " What are the common encryption methods in WEB development ", we introduced the asymmetric encryption RSA2 algorithm, which is suitable for encrypting a small amount of data, such as payment data and other scenarios with high security requirements.

We first need to generate public and private key files:

openssl genrsa -out private_key.pem 2048
openssl rsa -in private_key.pem -pubout -out public_key.pem

RSA2 encryption

We assume that the user payment information needs to be encrypted and submitted to the back-end payment system through the interface. The user client uses the public key to encrypt the data, and the back-end payment system uses the private key to decrypt the data.

$publicKey = '-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDRJ6it8Vnl3BUfJok8JYPMkAra
vmjj/cUElcBgp9Ez4hw9rzloqszOye1cyYdkH9EJhp55wwhZl2B6Mx7kahu08wJn
h90j0IVArKUYau9u2hOQ52+VvEAbTYh8LkWfN1gvtcquSVwqKRjmBApo1LTpOooD
FrLRji8oiE7bLXHNgQIDAQAB
-----END PUBLIC KEY-----';

//需要加密的数据
$data = [
    'order_id' => 'N2020020212345689232',
    'money' => 1000000,
    'user_id' => 1982,
    'pay_type' => 'alipay',
    'pay_time' => 1583213421
];

$publicKey = openssl_pkey_get_public($publicKey); //解析公钥
$rs = openssl_public_encrypt(json_encode($data), $encrypted, $publicKey) ? base64_encode($encrypted) : null; 
echo $rs;

We can copy and paste the generated public key directly into the code file, or use fopen()Open to read the public key file. Note that the openssl_public_encrypt()encrypted plaintext content cannot be too long. For too long content, you can consider segmentation encryption or use DES encryption.

After running, get the encrypted content:

A7yj2Yjuc4Y8jhtmz5MdxrMFGhyortBJ53kYQZ8MMNNsjW2rW21a/l4DH247xh0zkPPHHzygGqNIFwuiPFaK2RvubfjZxyqIfNts8RkNXGSTIYCKv6BobI3AWcgF+eyyrhaoTiiCUVwDqNrVoLVZdOPReyK5dOvOPd1nXemhg9Q=

RSA2 decryption

After the back-end payment system receives the encrypted content, it uses the private key to decrypt it.

$privateKey = '-----BEGIN PRIVATE KEY-----
MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBANEnqK3xWeXcFR8m
iTwlg8yQCtq+aOP9xQSVwGCn0TPiHD2vOWiqzM7J7VzJh2Qf0QmGnnnDCFmXYHoz
HuRqG7TzAmeH3SPQhUCspRhq727aE5Dnb5W8QBtNiHwuRZ83WC+1yq5JXCopGOYE
CmjUtOk6igMWstGOLyiITtstcc2BAgMBAAECgYBmCrlLE+NON8++QOjXhV4GIYiK
LDe0dAz5La6L+ZQhggFRPvn9TMdbZDz/9fquKK+tvBX5ReP/AdG6DNLXkcUt4yuG
JomQ0qiUw8e2J5xglb0lfgMvFJAUAnBRr8bOwg6YrUcRI9PiXM/bwOnjjX9eA/Ox
Bf7rmvQtfvSWqpEqgQJBAO++2sCInm8Mdy/RrN9A8CLx2Utzbb5e3K5i6Qr3H3As
++Gxx6RVhKhBoF2Kpy2abQclFnzuURH2d8Smun9yDjkCQQDfVdu0zi1OsX5mUuJa
AUfali+eF+HK7uYte9oTJULn1ykJaBkUFYFK08bWURc/SKN4WT4wf537clFVbCl2
KbmJAkEAjR8KAwUoRXPQAJzqpmvCLr+vycMDWWjbe+cLCIJYxh4kkkCkpK4WLTic
HhPMvoJFJUyGhTl/DRTIgUAnTXekuQJAP3FLZVRAaJ9hMb4P0NOWTtDlG/rayGQO
/RK2w0ONewCTBroMjbkCLnh0foMwoGiJD3ICiZJnFXvHAQYlzQxTSQJAFHFi5UmT
99AX8DZ7gRnjFqrzjkEMIY2klKv26x6fSGcoQ7pYhbnj4S9pmUMthfdACWp9kTkW
w5gQhVfGr8dOXA==
-----END PRIVATE KEY-----';

$key = openssl_pkey_get_private($privateKey); //解析私钥
$encrypted = base64_decode($encrypted);
//解密
$mydata = openssl_private_decrypt($encrypted, $decrypted, $key) ? $decrypted : null;
echo $mydata;

After running, get the decrypted data:

{"order_id":"N2020020212345689232","money":1000000,"user_id":1982,"pay_type":"alipay","pay_time":1583213421}

RSA2 signature

First of all, we need to understand why we need to sign? When we are making data requests, in order to prevent data from being intercepted or tampered with, causing bad effects, we need to perform signature verification when sending and receiving data through the data interface. The principle of signing is: the client and the server use the same signature algorithm to calculate the signature. When the signature submitted by the client is consistent with the signature provided by the server, the signature is successful.

We use RSA2 to sign client data. Note that the signing party uses the private key to prove that the signature is sent from your client. Of course, the verification party is the server that uses the public key to verify the signature. In the following example, we still use the public and private keys generated at the beginning of the article.

//要签名的数据
$data = [
    'order_id' => 'N2020020212345689232',
    'money' => 1000000,
    'user_id' => 1982,
    'pay_type' => 'alipay',
    'pay_time' => 1583213421
];

$privateKey = openssl_pkey_get_private($privateKey);
$signature = openssl_sign(json_encode($data), $sign, $privateKey, OPENSSL_ALGO_SHA256) ? base64_encode($sign) : null;
echo $signature;

The function openssl_sign()signs the payment data with RS2 and gets the signature after running:

eYg6ss/iOuie8SUikqdTTBmctOatTV+zrw5NGfR33rPJvzSrRRZvC/ynwaS3ZLoX4sUlD0mcF9WEoLwG1IXKeqszkCkY06DejvUZNk4N5Ie49MiBPOgTz2qdWP1Q0bnL2T7c+KqDLn9tk2vzDRUoMW8aPPXuJFiNTYaNf50aty0=

RSA2 verification

After the server receives the data and signature submitted by the client, it uses the public key to verify the signature.

//接收客户端的签名
$sign = 'eYg6ss/iOuie8SUikqdTTBmctOatTV+zrw5NGfR33rPJvzSrRRZvC/ynwaS3ZLoX4sUlD0mcF9WEoLwG1IXKeqszkCkY06DejvUZNk4N5Ie49MiBPOgTz2qdWP1Q0bnL2T7c+KqDLn9tk2vzDRUoMW8aPPXuJFiNTYaNf50aty0=';
//接收客户端的原始数据
$data = [
    'order_id' => 'N2020020212345689232',
    'money' => 1000000,
    'user_id' => 1982,
    'pay_type' => 'alipay',
    'pay_time' => 1583213421
];

$publicKey = openssl_pkey_get_public($publicKey);
$rs = openssl_verify(json_encode($data), base64_decode($sign), $publicKey, OPENSSL_ALGO_SHA256);
var_dump($rs);
if ($rs) {
    echo 'ok';
    ...do something...
} else {
    echo 'fail...';
}

In the above code, in order to demonstrate the assignment of two variables to $signand $data, in fact, these two values ​​are passed from the client, usually postsubmitted, here is not a demonstration in the code, you can practice by yourself.

After running the above code, "ok" is successfully output, that is, the verification is successful.

the above.

 

This article comes from: helloweba.net

Original link: https://www.helloweba.net/php/630.html

Guess you like

Origin blog.csdn.net/z3287852/article/details/113421794