蚂蚁论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

扫一扫,访问微社区

查看: 38|回复: 0

Node.js中AES加密和其它语言不一致问题解决办法

[复制链接]

1979

主题

1

好友

1609

积分

管理员

Rank: 64Rank: 64Rank: 64Rank: 64

  • TA的每日心情
    奋斗
    2016-1-22 16:23
  • 签到天数: 4 天

    [LV.2]偶尔看看I

    荣誉管理 论坛元老 热心会员 活跃会员 最佳新人 灌水之王

    发表于 2017-10-13 06:55:57 |显示全部楼层
    Node.js中AES加密和其它语言不一致问题解决办法
    例子一:
    这几天被一个问题困扰着。Nodejs的AES加密和Java,C加密出来的不一致。当然,这样就不能解密了。纠结了许久:后来还是实在不行了,看了下源代码,要不然还得继续纠结下去。网上说,通常的nodejs AES和其他语言实现不一样。好吧~~或许吧。nodejs的crypto模块。复制代码 代码如下:var crypto = require('crypto');
    var data = "156156165152165156156";consolelog('Original cleartext: ' + data);var algorithm = 'aes-128-ecb';var key = '78541561566';var clearEncoding = 'utf8';//var cipherEncoding = 'hex';//If the next line is unmented, the final cleartext is wrongvar cipherEncoding = 'base64';/*加密*/var cipher = cryptocreateCipher(algorithm, key);
    var cipherChunks = [];cipherChunkspush(cipherupdate(data, clearEncoding, cipherEncoding));cipherChunkspush(cipherfinal(cipherEncoding));consolelog(cipherEncoding + ' ciphertext: ' + cipherChunksjoin(''));/*解密*/var decipher = cryptocreateDecipher(algorithm, key);var plainChunks = [];for (var i = 0;i lt; cipherChunkslength;i++) {plainChunkspush(decipherupdate(cipherChunks[i], cipherEncoding, clearEncoding));
    }plainChunkspush(decipherfinal(clearEncoding));consolelog("UTF8 plaintext deciphered: " + plainChunksjoin(''));的确,没错~~加密解密成功。但是和java,C中加密出来的不一样啊。神啊。我想,大家都在这里纠结着吧~~对不对。其实只要加个向量,就可以和一致了。网上搜索出来的资源太少。才让自己纠结那么久。好吧,正确代码是:复制代码 代码如下:var crypto = require('crypto');
    var data = "156156165152165156156";consolelog('Original cleartext: ' + data);var algorithm = 'aes-128-ecb';var key = '78541561566';var clearEncoding = 'utf8';var iv = "";//var cipherEncoding = 'hex';//If the next line is unmented, the final cleartext is wrongvar cipherEncoding = 'base64';var cipher = cryptocreateCipheriv(algorithm, key,iv);
    var cipherChunks = [];cipherChunkspush(cipherupdate(data, clearEncoding, cipherEncoding));cipherChunkspush(cipherfinal(cipherEncoding));consolelog(cipherEncoding + ' ciphertext: ' + cipherChunksjoin(''));
    var decipher = cryptocreateDecipheriv(algorithm, key,iv);var plainChunks = [];for (var i = 0;i lt; cipherChunkslength;i++) {plainChunkspush(decipherupdate(cipherChunks[i], cipherEncoding, clearEncoding));
    }plainChunkspush(decipherfinal(clearEncoding));consolelog("UTF8 plaintext deciphered: " + plainChunksjoin(''));对比发现,加密出来是一致的。好吧,结贴~~~我恨你,浪费了我一天时间。
    例子二:
    工作中遇到nodejs端通过aes加密,安卓客户端java解密,同意nodejs也需要解密安卓客户端加密过来的内容,发现两个加密结果不一样,查询资料发现java端需要对密钥za再MD5加密一遍,以下是aes ecb加密的内容,如果是cbc也同样需要对秘钥MD5加密:
    nodejs:复制代码 代码如下:/** * aes加密 * @param data * @param secretKey */encryptUtilsaesEncrypt = function(data, secretKey) {var cipher = cryptocreateCipher('aes-128-ecb',secretKey);return cipherupdate(data,'utf8','hex') + cipherfinal('hex');}/** * aes解密 * @param data * @param secretKey * @returns {*} */encryptUtilsaesDecrypt = function(data, secretKey) {var cipher = cryptocreateDecipher('aes-128-ecb',secretKey);return cipherupdate(data,'hex','utf8') + cipherfinal('utf8');}java:复制代码 代码如下:package iofamilyutil;import javasecurityMessageDigest;import javaxcryptoCipher;import javaxcryptospecSecretKeySpec;/** * AES加密,与Nodejs 保持一致 * @author lmiky * @date 2014-2-25 */public class AESForNodejs {public static final String DEFAULT_CODING = "utf-8";/** * 解密 * @author lmiky * @date 2014-2-25 * @param encrypted * @param seed * @return * @throws Exception */private static String decrypt(String encrypted, String seed) throws Exception {byte[] keyb = seedgetBytes(DEFAULT_CODING);MessageDigest md = MessageDigestgetInstance("MD5");byte[] thedigest = mddigest(keyb);SecretKeySpec skey = new SecretKeySpec(thedigest, "AES");Cipher dcipher = CiphergetInstance("AES");dcipherinit(CipherDECRYPT_MODE, skey);byte[] clearbyte = dcipherdoFinal(toByte(encrypted));return new String(clearbyte);}/** * 加密 * @author lmiky * @date 2014-2-25 * @param content * @param key * @return * @throws Exception */public static String encrypt(String content, String key) throws Exception {byte[] input = contentgetBytes(DEFAULT_CODING);MessageDigest md = MessageDigestgetInstance("MD5");byte[] thedigest = mddigest(keygetBytes(DEFAULT_CODING));SecretKeySpec skc = new SecretKeySpec(thedigest, "AES");Cipher cipher = CiphergetInstance("AES/ECB/PKCS5Padding");cipherinit(CipherENCRYPT_MODE, skc);byte[] cipherText = new byte[ciphergetOutputSize(inputlength)];int ctLength = cipherupdate(input, 0, inputlength, cipherText, 0);ctLength += cipherdoFinal(cipherText, ctLength);return parseByte2HexStr(cipherText);}/** * 字符串转字节数组 * @author lmiky * @date 2014-2-25 * @param hexString * @return */private static byte[] toByte(String hexString) {int len = hexStringlength() / 2;byte[] result = new byte[len];for (int i = 0; i lt; len; i++) {result[i] = IntegervalueOf(hexStringsubstring(2 * i, 2 * i + 2), 16)byteValue();}return result;}/** * 字节转16进制数组 * @author lmiky * @date 2014-2-25 * @param buf * @return */private static String parseByte2HexStr(byte buf[]) {StringBuffer sb = new StringBuffer();for (int i = 0; i lt; buflength; i++) {String hex = IntegertoHexString(buf[i]  0xFF);if (hexlength() == 1) {hex = '0' + hex;}sbappend(hex);}return sbtoString();}public static void main(String[] args) throws Exception {Systemoutprintln(AESForNodejsencrypt("fsadfsdafsdafsdafsadfsadfsadf", "1234fghjnmlkiuhA"));Systemoutprintln(AESForNodejsdecrypt("5b8e85b7a86ad15a275a7cb61fe4c0606005e8741f68797718a3e90d74b5092a", "1234fghjnmlkiuhA"));}}
    您需要登录后才可以回帖 登录 | 立即注册

    关闭

    蚂蚁站长论坛推荐上一条 /1 下一条

    QQ|Archiver|手机版|广告服务|蚂蚁站长-站长之家 ( 黔ICP备16008478号-1  

    GMT+8, 2017-10-23 06:48

    Powered by 站长论坛

    © 2007-2013 Jzant.com Inc.

    回顶部