DIV CSS 佈局教程網

Node.js AES 加密結果與 Java、C# 不一致的原因與解法
編輯:JavaScript綜合知識     

跨語言通訊時,Node.js 用 crypto 模組算出的 AES 密文,和 Java、C# 那邊算出來的完全對不上,密鑰、演算法名稱都一樣卻怎麼樣都無法互相解密。這個問題困擾過不少人,其實癥結在於兩點:金鑰的處理方式,以及是否顯式指定 IV。

案例一:createCipher 與 createCipheriv 的差異

先看一段能正常加解密的 Node.js 程式碼:

var crypto = require('crypto');

var data = "156156165152165156156";
console.log('Original cleartext: ' + data);

var algorithm = 'aes-128-ecb';
var key = '78541561566';
var clearEncoding = 'utf8';
var cipherEncoding = 'base64';

/* 加密 */
var cipher = crypto.createCipher(algorithm, key);
var cipherChunks = [];
cipherChunks.push(cipher.update(data, clearEncoding, cipherEncoding));
cipherChunks.push(cipher.final(cipherEncoding));
console.log(cipherEncoding + ' ciphertext: ' + cipherChunks.join(''));

/* 解密 */
var decipher = crypto.createDecipher(algorithm, key);
var plainChunks = [];
for (var i = 0; i < cipherChunks.length; i++) {
    plainChunks.push(decipher.update(cipherChunks[i], cipherEncoding, clearEncoding));
}
plainChunks.push(decipher.final(clearEncoding));
console.log("UTF8 plaintext deciphered: " + plainChunks.join(''));

在 Node 內部跑,加解密完全正確。但把密文丟給 Java 或 C# 去解,就是解不開;反過來也一樣。

癥結所在

Node.js 的 crypto 在處理金鑰時,會對傳入的字串自行做一次雜湊推導,這一步其他語言的實作並不會做,於是雙方拿到的實際金鑰根本不是同一組位元組。

把 createCipher 換成 createCipheriv,顯式傳入 IV(ECB 模式下傳空字串),繞過 Node 的金鑰推導邏輯,結果就與其他語言一致了:

var crypto = require('crypto');

var data = "156156165152165156156";
var algorithm = 'aes-128-ecb';
var key = '78541561566';
var clearEncoding = 'utf8';
var iv = "";
var cipherEncoding = 'base64';

var cipher = crypto.createCipheriv(algorithm, key, iv);
var cipherChunks = [];
cipherChunks.push(cipher.update(data, clearEncoding, cipherEncoding));
cipherChunks.push(cipher.final(cipherEncoding));
console.log(cipherEncoding + ' ciphertext: ' + cipherChunks.join(''));

var decipher = crypto.createDecipheriv(algorithm, key, iv);
var plainChunks = [];
for (var i = 0; i < cipherChunks.length; i++) {
    plainChunks.push(decipher.update(cipherChunks[i], cipherEncoding, clearEncoding));
}
plainChunks.push(decipher.final(clearEncoding));
console.log("UTF8 plaintext deciphered: " + plainChunks.join(''));

案例二:Java 端對金鑰多做一次 MD5

另一種常見場景是 Node.js 加密、Android 端用 Java 解密。這時對不上,通常是因為 Java 端的慣例是先把金鑰字串做一輪 MD5,取 16 位元組的摘要作為真正的 AES 金鑰。ECB 與 CBC 模式都適用這個做法。

Node.js 側的加密與解密工具函式:

/**
 * AES 加密
 * @param data 明文
 * @param secretKey 金鑰種子
 */
encryptUtils.aesEncrypt = function(data, secretKey) {
    var cipher = crypto.createCipher('aes-128-ecb', secretKey);
    return cipher.update(data, 'utf8', 'hex') + cipher.final('hex');
}

/**
 * AES 解密
 */
encryptUtils.aesDecrypt = function(data, secretKey) {
    var cipher = crypto.createDecipher('aes-128-ecb', secretKey);
    return cipher.update(data, 'hex', 'utf8') + cipher.final('utf8');
}

Java 側對應的實作,重點在 MessageDigest.getInstance("MD5") 那段:

package com.iofamily.util;

import java.security.MessageDigest;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * AES 加密,與 Nodejs 保持一致
 */
public class AESForNodejs {

    public static final String DEFAULT_CODING = "utf-8";

    /** 解密 */
    private static String decrypt(String encrypted, String seed) throws Exception {
        byte[] keyb = seed.getBytes(DEFAULT_CODING);
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] thedigest = md.digest(keyb);
        SecretKeySpec skey = new SecretKeySpec(thedigest, "AES");
        Cipher dcipher = Cipher.getInstance("AES");
        dcipher.init(Cipher.DECRYPT_MODE, skey);
        byte[] clearbyte = dcipher.doFinal(toByte(encrypted));
        return new String(clearbyte);
    }

    /** 加密 */
    public static String encrypt(String content, String key) throws Exception {
        byte[] input = content.getBytes(DEFAULT_CODING);
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] thedigest = md.digest(key.getBytes(DEFAULT_CODING));
        SecretKeySpec skc = new SecretKeySpec(thedigest, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, skc);
        byte[] cipherText = new byte[cipher.getOutputSize(input.length)];
        int ctLength = cipher.update(input, 0, input.length, cipherText, 0);
        ctLength += cipher.doFinal(cipherText, ctLength);
        return parseByte2HexStr(cipherText);
    }

    /** 十六進位字串轉位元組陣列 */
    private static byte[] toByte(String hexString) {
        int len = hexString.length() / 2;
        byte[] result = new byte[len];
        for (int i = 0; i < len; i++) {
            result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2), 16).byteValue();
        }
        return result;
    }

    /** 位元組轉十六進位字串 */
    private static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex);
        }
        return sb.toString();
    }

    public static void main(String[] args) throws Exception {
        System.out.println(AESForNodejs.encrypt("fsadfsdafsdafsdafsadfsadfsadf", "1234fghjnmlkiuhA"));
        System.out.println(AESForNodejs.decrypt(
            "5b8e85b7a86ad15a275a7cb61fe4c0606005e8741f68797718a3e904b5092a",
            "1234fghjnmlkiuhA"));
    }
}

排查思路總結

跨語言 AES 對不上,通常就這幾個方向:

  • 金鑰推導是否一致——Node 的 createCipher 會自行雜湊金鑰,Java 端若做了 MD5,雙方就必須統一做法。
  • IV 是否相同——CBC 模式下 IV 必須完全一致,ECB 模式則無 IV。
  • 編碼格式——密文輸出是 hex 還是 base64,雙方要對齊。
  • 填充方式——PKCS5Padding、PKCS7Padding、NoPadding 的差異會直接導致解密失敗。

把這四項逐一核對,基本都能定位問題。老實說,這類問題一旦踩上,查資料的時間往往比寫程式碼還長。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved