WXBizDataCrypt.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. /**
  3. * Author: luzheng.liu
  4. * Time: 2020/10/23 22:21
  5. */
  6. namespace app\common\service\wechat\decode;
  7. class WXBizDataCrypt {
  8. private $appid;
  9. private $sessionKey;
  10. /**
  11. * 构造函数
  12. * @param $sessionKey string 用户在小程序登录后获取的会话密钥
  13. * @param $appid string 小程序的appid
  14. */
  15. public function __construct($appid, $sessionKey) {
  16. $this->sessionKey = $sessionKey;
  17. $this->appid = $appid;
  18. }
  19. /**
  20. * 检验数据的真实性,并且获取解密后的明文.
  21. * @param $encryptedData string 加密的用户数据
  22. * @param $iv string 与用户数据一同返回的初始向量
  23. * @param $data string 解密后的原文
  24. *
  25. * @return int 成功0,失败返回对应的错误码
  26. */
  27. public function decryptData($encryptedData, $iv, &$data) {
  28. if (strlen($this->sessionKey) != 24) {
  29. return ErrorCode::$IllegalAesKey;
  30. }
  31. $aesKey = base64_decode($this->sessionKey);
  32. if (strlen($iv) != 24) {
  33. return ErrorCode::$IllegalIv;
  34. }
  35. $aesIV = base64_decode($iv);
  36. $aesCipher = base64_decode($encryptedData);
  37. $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
  38. $dataObj = json_decode($result);
  39. if ($dataObj == NULL) {
  40. return ErrorCode::$IllegalBuffer;
  41. }
  42. if ($dataObj->watermark->appid != $this->appid) {
  43. return ErrorCode::$IllegalBuffer;
  44. }
  45. $data = $result;
  46. return ErrorCode::$OK;
  47. }
  48. }