WXBizDataCrypt.js 977 B

1234567891011121314151617181920212223242526272829303132333435
  1. 'use strict';
  2. const crypto = require('crypto');
  3. function WXBizDataCrypt(appId, sessionKey) {
  4. this.appId = appId;
  5. this.sessionKey = sessionKey;
  6. }
  7. WXBizDataCrypt.prototype.decryptData = function(encryptedData, iv) {
  8. // base64 decode
  9. const sessionKey = new Buffer(this.sessionKey, 'base64');
  10. encryptedData = new Buffer(encryptedData, 'base64');
  11. iv = new Buffer(iv, 'base64');
  12. let decoded;
  13. try {
  14. // 解密
  15. const decipher = crypto.createDecipheriv('aes-128-cbc', sessionKey, iv);
  16. // 设置自动 padding 为 true,删除填充补位
  17. decipher.setAutoPadding(true);
  18. decoded = decipher.update(encryptedData, 'binary', 'utf8');
  19. decoded += decipher.final('utf8');
  20. decoded = JSON.parse(decoded);
  21. } catch (err) {
  22. throw new Error('Illegal Buffer');
  23. }
  24. if (decoded.watermark.appid !== this.appId) {
  25. throw new Error('Illegal Buffer');
  26. }
  27. return decoded;
  28. };
  29. module.exports = WXBizDataCrypt;