alipay_rsa.function.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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, $aliapp_rsa_public, $sign) {
  34. //$pubKey = file_get_contents($ali_public_key_path);
  35. $pubkey = getPublicKeyFromX509($aliapp_rsa_public);
  36. $res = openssl_get_publickey($pubkey);
  37. $result = (bool)openssl_verify($data, base64_decode($sign), $res);
  38. openssl_free_key($res);
  39. return $result;
  40. }
  41. function getPublicKeyFromX509($certificate)
  42. {
  43. $publicKeyString = "-----BEGIN PUBLIC KEY-----\n" .
  44. wordwrap($certificate, 64, "\n", true) .
  45. "\n-----END PUBLIC KEY-----";
  46. return $publicKeyString;
  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. ?>