基于Nodejs的微信消息加密与解密实现概要

微信团队提供了多种语言的示例代码,但不包含Nodejs实现版本。通过大量查证和尝试,我已完成并测试经过,下面说说实现要点。javascript

准备

  • Nodejs为0.12.1版或0.12.2版,当前最新稳定版。
  • 平台支持Windows和Linux。
  • 基于Python版本改写,经过Python的加解密验证及实际部署验证。

关键点

  • 密匙key应当经过Buffer转换为binary字符串。
  • 经过String.fromCharCode得到补位所用的字符,经过charCodeAt判断须要删除的补位字符长度。
  • 设置明文长度时,应经过Buf.writeUInt32BE写入,并转换为binary字符串;读取时,使用Buf.readUInt32BE
  • 加密时,XML原文需经过Buffer转换为binary字符串。
  • 加密使用crypto.createCipheriv,解密使用crypto.Decipheriv;须设置cipher.setAutoPadding(auto_padding=false),不然不能正确加解密。
  • 加密时,输入编码为binary,输出编码为base64
  • 解密时,输入编码为base64,输出编码为utf8
  • 每一个中文字符经过Buffer转换后,实际计算长度为3,所以最后分离from_appid时,需便宜行事:P

密匙key经过以下方式转换:html

this.key = new Buffer(sEncodingAESKey + '=', 'base64').toString('binary');

加密部分代码片断:java

// 16位随机字符串添加到明文开头
// 使用自定义的填充方式对明文进行补位填充
var text = new Buffer(xml), // 一个中文长度为3
    pad = this.enclen(text.length),
    pack = PKCS7.encode(20 + text.length + appid.length),
    random = crypto.randomBytes(8).toString('hex'),
    content = random + pad + text.toString('binary') + appid + pack;
try {
     var cipher = crypto.createCipheriv(this.mode, this.key, this.key.slice(0, 16));
     cipher.setAutoPadding(auto_padding=false);
     var crypted = cipher.update(content, 'binary', 'base64') + cipher.final('base64');
     return [ierror.OK, crypted];
} catch (e) {
     console.log(e.stack);
     return  [ierror.EncryptAES_Error, null];
}

解密部分代码片断:算法

var decipher, plain_text;
try {
      decipher = crypto.Decipheriv(this.mode, this.key, this.key.slice(0, 16));
      // 使用BASE64对密文进行解码,而后AES-CBC解密
      decipher.setAutoPadding(auto_padding=false);
      plain_text = decipher.update(text, 'base64', 'utf8') + decipher.final('utf8');
} catch (e) {
      console.log(e.stack);
      return [ierror.DecryptAES_Error, null];
}
var pad = plain_text.charCodeAt(plain_text.length - 1);
plain_text = plain_text.slice(20, -pad);

Pad计算方法enclen:微信

this.enclen = function (len) {
    var buf = new Buffer(4);
    buf.writeUInt32BE(len);
    //console.log('enclen:', len, buf.toString('binary'));
    return buf.toString('binary');
}

对须要加密的明文进行填充补位算法:app

PKCS7.encode = function (text_length) {
    // 计算须要填充的位数
    var amount_to_pad = PKCS7.block_size - (text_length % PKCS7.block_size);
    if (amount_to_pad === 0) {
        amount_to_pad = PKCS7.block_size;
    }
    // 得到补位所用的字符
    var pad = String.fromCharCode(amount_to_pad), s = [];
    //console.log('pad:', amount_to_pad, pad);
    for (var i=0; i<amount_to_pad; i++) s.push(pad);
    return s.join('');
}

关键思路及代码如上,建议参考Python版进行比对阅读。dom

转载请注明出处:http://my.oschina.net/u/2324376/blog/397296测试

相关文章
相关标签/搜索