php RSA公钥私钥加解密和验证用法
现在很多项目中会使用到rsa加解密和验证相关的技术,分别整理代码如下,方便记忆和使用。
【签名和验证】
1 //获得签名 2 function getSign($data) { 3 $pem = 'my_rsa_private_key.pem'; 4 $privateKey = openssl_get_privatekey(file_get_contents($pem)); 5 openssl_sign($data, $sign, $privateKey); 6 openssl_free_key($privateKey); 7 return base64_encode($sign); 8 } 9 //验证签名 10 function checkSign($data, $sign) { 11 $pem = 'my_rsa_public_key.pem'; 12 $publicKey = openssl_get_publickey(file_get_contents($pem)); 13 $result = openssl_verify($data, $sign, $publicKey); 14 openssl_free_key($publicKey); 15 return $result; 16 } 17 $signData = 'php-rsa'; 18 $getSign = getSign($data); 19 $checkSign = checkSign($data, base64_decode($sign));
20 echo '签名数据:'.$signData; 21 echo '获得签名:'.$getSign; 22 echo '验证签名:'.$checkSign;
运行结果如下:
签名数据:php-rsa
签名结果:LOVAjWTgHeUvJIK0scVOQO2VlId+1qEuUc70cb7Z/dyMONpheldefkKJXZDF9HelTz/UnwEd00Tre698VGN1IX/sV7WTQJFCY+ypArfNx9mCzaEhMt0U60yGkIPh8wXqNG10YhgzPIw3Lvd/36FnRlTBXOZeJMbxFxhdJmSdeOQ=
验证签名:1
【数据加解密】
1 //加密数据 2 function sslEncrypt($source, $type, $key) { 3 $maxlength = 117; 4 $output = ''; 5 while ($source) { 6 $input = substr($source, 0, $maxlength); 7 $source = substr($source, $maxlength); 8 if ($type == 'private') { 9 $ok = openssl_private_encrypt($input, $encrypted, $key); 10 } else { 11 $ok = openssl_public_encrypt($input, $encrypted, $key); 12 } 13 $output .= $encrypted; 14 } 15 return $output; 16 } 17 //解密数据 18 function sslDecrypt($source, $type, $key) { 19 $maxlength = 128; 20 $output = ''; 21 while ($source) { 22 $input = substr($source, 0, $maxlength); 23 $source = substr($source, $maxlength); 24 if ($type == 'private') { 25 $ok = openssl_private_decrypt($input, $out, $key); 26 } else { 27 $ok = openssl_public_decrypt($input, $out, $key); 28 } 29 $output .= $out; 30 } 31 return $output; 32 } 33 $data = 'php-rsa'; 34 $privatekey = openssl_get_privatekey(file_get_contents('my_rsa_private_key.pem')); 35 $publickey = openssl_get_publickey(file_get_contents('my_rsa_public_key.pem')); 36 $sign = base64_encode(sslEncrypt($data, 'private', $privatekey)); 37 $jiemi = sslDecrypt(base64_decode($sign), 'public', $publickey);
38 echo '加密数据:'.$data;
39 echo '加密结果:'.$sign;
40 echo '解密数据:'.$jiemi;
运行结果如下:
加密数据:php-rsa
加密结果:aMCpl34vXbofR7a3OPPLElQg6jwG+xbdIsdfYGeVPtIhVp0INMu/0p9M8h+JiBBmGL/WVY9ynbrvNH6QtLXDoW23rm6EWPPKn53EIqt/9jM/fDX8EyaAvhIuaSJ2Q7dxz4hNF+Ykm0XZ5ytsCB71zYVPYfaHyo3Xk+VkZ/JvznE=
解密数据:php-rsa