php openssl加密解密

  1. 生成公钥和私钥
1
2
3
4
//生成私钥
openssl genrsa -out rsa_private_key.pem 1024
//生成公钥
openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
  1. 公钥加密,私钥解密的演示
1
2
3
4
5
6
7
8
9
10
11
12
13
//使用 public key加密
$publicKey = '';//公钥
$encrypted = ''; //接收加密返回资料
$teststr = 'test';//待加密的字符串
openssl_public_encrypt($teststr,$encrypted,$publicKey);
$encrypted = base64_encode($encrypted);
echo 'encrypted:'.$encrypted;

$privatekey = ''; //私钥
//私钥解密
$decrypted = '';
$result = openssl_private_decrypt(base64_decode($encrypted),$decrypted,$privatekey);
echo 'decrypted:'.$result;
Reference
  1. OpenSSL生成公钥私钥