alipay_rsa.function.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. $pubKey = file_get_contents($ali_public_key_path);
  35. $res = openssl_get_publickey($pubKey);
  36. $result = (bool)openssl_verify($data, base64_decode($sign), $res);
  37. openssl_free_key($res);
  38. return $result;
  39. }
  40. /**
  41. * RSA解密
  42. * @param $content 需要解密的内容,密文
  43. * @param $private_key_path 商户私钥文件路径
  44. * return 解密后内容,明文
  45. */
  46. function rsaDecrypt($content, $private_key_path) {
  47. $priKey = file_get_contents($private_key_path);
  48. $res = openssl_get_privatekey($priKey);
  49. //用base64将内容还原成二进制
  50. $content = base64_decode($content);
  51. //把需要解密的内容,按128位拆开解密
  52. $result = '';
  53. for($i = 0; $i < strlen($content)/128; $i++ ) {
  54. $data = substr($content, $i * 128, 128);
  55. openssl_private_decrypt($data, $decrypt, $res);
  56. $result .= $decrypt;
  57. }
  58. openssl_free_key($res);
  59. return $result;
  60. }
  61. ?>