WXBizDataCrypt.js 998 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. /**
  2. * 微信小程序用户数据解密工具
  3. */
  4. import crypto from 'crypto';
  5. class WXBizDataCrypt {
  6. constructor(appId, sessionKey) {
  7. this.appId = appId;
  8. this.sessionKey = sessionKey;
  9. }
  10. decryptData(encryptedData, iv) {
  11. // base64 decode
  12. const sessionKey = Buffer.from(this.sessionKey, 'base64');
  13. encryptedData = Buffer.from(encryptedData, 'base64');
  14. iv = Buffer.from(iv, 'base64');
  15. try {
  16. // 解密
  17. const decipher = crypto.createDecipheriv('aes-128-cbc', sessionKey, iv);
  18. // 设置自动 padding 为 true,删除填充补位
  19. decipher.setAutoPadding(true);
  20. let decoded = decipher.update(encryptedData, 'binary', 'utf8');
  21. decoded += decipher.final('utf8');
  22. decoded = JSON.parse(decoded);
  23. } catch (err) {
  24. throw new Error('Illegal Buffer');
  25. }
  26. if (decoded.watermark.appid !== this.appId) {
  27. throw new Error('Illegal Buffer');
  28. }
  29. return decoded;
  30. }
  31. }
  32. export default WXBizDataCrypt;