wxBizDataCrypt.php 1.8 KB

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