2

One: Generate RSA private key and public key

1: RSA private key generation

 $resource = openssl_pkey_new();
openssl_pkey_export($resource, $privateKey);
echo($privateKey);

2: RSA public key generation

 $resource = openssl_pkey_new();
$detail = openssl_pkey_get_details($resource);
$publicKey = $detail['key'];
echo($publicKey);

Notice:
If the following prompt appears when generating the private key and public key:
image.png
You need to add the openssl.cnf file address in your php environment to the system environment variable, add the variable name OPENSSL_CONF, and the variable value is the openssl.cnf file address

Two: RSA realizes private key encryption and public key decryption

1: RSA private key encryption

 $key = '123';//需要加密的字符串
$pkey=openssl_pkey_get_private($privateKey);//$privateKey为私钥字符串
openssl_private_encrypt($key, $encryptedData, $pkey);
$encryptedData = base64_encode($encryptedData);
echo($encryptedData);

2: RSA public key decryption

 $pkey = openssl_pkey_get_public($publicKey);//$publicKey为公钥字符串
openssl_public_decrypt(base64_decode($encryptedData), $data, $pkey);//$encryptedData为私钥加密串
echo($data);

Three: RSA realizes signature and verification

1: Private key signature

 $key = '123';//需要签名的字符串
$pkey=openssl_pkey_get_private($privateKey);//$privateKey为私钥字符串
openssl_sign($key, $signature,$privateKey);
openssl_free_key($pkey);
$signature = base64_encode($signature);
echo($signature);

2: Public key verification

 $pkey = openssl_pkey_get_public($publicKey);//公钥字符串
$verify = openssl_verify($key, base64_decode($signature),$publicKey);//$key为需要签名的字符串//$signature为签名后字符串
openssl_free_key($pkey);
echo($verify);

According to the above, we can realize the encryption and decryption of RSA and use the private key and public key of RSA to realize the function of signature and verification!


huaweichenai
679 声望114 粉丝