You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

80 lines
1.9 KiB

6 years ago
  1. <?php
  2. /**
  3. * 对微信小程序用户加密数据的解密示例代码.
  4. *
  5. * @copyright Copyright (c) 1998-2014 Tencent Inc.
  6. */
  7. /**
  8. * error code 说明.
  9. * <ul>
  10. * <li>-41001: encodingAesKey 非法</li>
  11. * <li>-41003: aes 解密失败</li>
  12. * <li>-41004: 解密后得到的buffer非法</li>
  13. * <li>-41005: base64加密失败</li>
  14. * <li>-41016: base64解密失败</li>
  15. * </ul>
  16. */
  17. class ErrorCode
  18. {
  19. public static $OK = 0;
  20. public static $IllegalAesKey = -41001;
  21. public static $IllegalIv = -41002;
  22. public static $IllegalBuffer = -41003;
  23. public static $DecodeBase64Error = -41004;
  24. }
  25. class WXBizDataCrypt
  26. {
  27. private $appid;
  28. private $sessionKey;
  29. /**
  30. * 构造函数
  31. * @param $sessionKey string 用户在小程序登录后获取的会话密钥
  32. * @param $appid string 小程序的appid
  33. */
  34. public function __construct( $appid, $sessionKey)
  35. {
  36. $this->sessionKey = $sessionKey;
  37. $this->appid = $appid;
  38. }
  39. /**
  40. * 检验数据的真实性,并且获取解密后的明文.
  41. * @param $encryptedData string 加密的用户数据
  42. * @param $iv string 与用户数据一同返回的初始向量
  43. * @param $data string 解密后的原文
  44. *
  45. * @return int 成功0,失败返回对应的错误码
  46. */
  47. public function decryptData( $encryptedData, $iv, &$data )
  48. {
  49. if (strlen($this->sessionKey) != 24) {
  50. return ErrorCode::$IllegalAesKey;
  51. }
  52. $aesKey=base64_decode($this->sessionKey);
  53. if (strlen($iv) != 24) {
  54. return ErrorCode::$IllegalIv;
  55. }
  56. $aesIV=base64_decode($iv);
  57. $aesCipher=base64_decode($encryptedData);
  58. $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
  59. $dataObj=json_decode( $result );
  60. if( $dataObj == NULL )
  61. {
  62. return ErrorCode::$IllegalBuffer;
  63. }
  64. if( $dataObj->watermark->appid != $this->appid )
  65. {
  66. return ErrorCode::$IllegalBuffer;
  67. }
  68. $data = $result;
  69. return ErrorCode::$OK;
  70. }
  71. }