PHP实现RSA2加密
PHP实现RSA2加密
1.
需要开启php的 php_openssl扩展
1 <?php 2 3 /* 4 * RSA2签名 5 * @param array 请求的参数 6 * @param string 私钥 7 * return string 8 * time 2019-09-11 9 * author chen 10 * email 869476711@qq.com 11 * 12 * */ 13 protected function RSA2($data,$pikey){ 14 15 16 //将请求的参数进行排序 17 ksort($data);//ksort()函数 根据参数的键进行升序排序 18 reset($data); 19 $signStr = ''; 20 foreach ($data as $key => $value) { 21 if ($key == 'sign' || $value == '') continue; 22 $signStr .= $key .'=' .$value .'&'; 23 } 24 $signStr = substr($signStr, 0, -1); 25 26 27 $res = "-----BEGIN RSA PRIVATE KEY-----\n" . wordwrap($pikey, 64, "\n", true) . "\n-----END RSA PRIVATE KEY-----"; 28 // 请注意密钥 是不是有带 -----BEGIN RSA PRIVATE KEY----- -----END RSA PRIVATE KEY----- 29 30 $piKey = openssl_pkey_get_private($res); 31 32 if ($piKey) { 33 $res = openssl_get_privatekey($res); 34 openssl_sign($signStr, $sign, $res, 'SHA256'); 35 $sign = base64_encode($sign); 36 openssl_free_key($piKey); 37 return $sign; 38 } 39 }