wxbizdatacrypt.php 1.6 KB

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