alipay_rsa.function.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. /* *
  3. * 支付宝接口RSA函数
  4. * 详细:RSA签名、验签、解密
  5. * 版本:3.3
  6. * 日期:2012-07-23
  7. * 说明:
  8. * 以下代码只是为了方便商户测试而提供的样例代码,商户可以根据自己网站的需要,按照技术文档编写,并非一定要使用该代码。
  9. * 该代码仅供学习和研究支付宝接口使用,只是提供一个参考。
  10. */
  11. /**
  12. * RSA签名
  13. * @param $data 待签名数据
  14. * @param $private_key_path 商户私钥文件路径
  15. * return 签名结果
  16. */
  17. function rsaSign($data, $private_key_path) {
  18. $priKey = file_get_contents($private_key_path);
  19. $res = openssl_get_privatekey($priKey);
  20. openssl_sign($data, $sign, $res);
  21. openssl_free_key($res);
  22. //base64编码
  23. $sign = base64_encode($sign);
  24. return $sign;
  25. }
  26. /**
  27. * RSA验签
  28. * @param $data 待签名数据
  29. * @param $ali_public_key_path 支付宝的公钥文件路径
  30. * @param $sign 要校对的的签名结果
  31. * return 验证结果
  32. */
  33. function rsaVerify($data, $ali_public_key_path, $sign)
  34. {
  35. Log::record("pub key path={$ali_public_key_path}",Log::DEBUG);
  36. $pubKey = file_get_contents($ali_public_key_path);
  37. $res = openssl_get_publickey($pubKey);
  38. $sign = urldecode($sign);
  39. $sign = base64_decode($sign);
  40. $result = (bool)openssl_verify($data, $sign, $res);
  41. if($result == false) {
  42. $err = openssl_error_string();
  43. Log::record("openssl last error={$err}",Log::DEBUG);
  44. }
  45. openssl_free_key($res);
  46. return $result;
  47. }
  48. /**
  49. * RSA解密
  50. * @param $content 需要解密的内容,密文
  51. * @param $private_key_path 商户私钥文件路径
  52. * return 解密后内容,明文
  53. */
  54. function rsaDecrypt($content, $private_key_path) {
  55. $priKey = file_get_contents($private_key_path);
  56. $res = openssl_get_privatekey($priKey);
  57. //用base64将内容还原成二进制
  58. $content = base64_decode($content);
  59. //把需要解密的内容,按128位拆开解密
  60. $result = '';
  61. for($i = 0; $i < strlen($content)/128; $i++ ) {
  62. $data = substr($content, $i * 128, 128);
  63. openssl_private_decrypt($data, $decrypt, $res);
  64. $result .= $decrypt;
  65. }
  66. openssl_free_key($res);
  67. return $result;
  68. }
  69. ?>