WXBizDataCrypt.js 977 B

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