WxBizDataCrypt.php 1.6 KB

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