萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

Node.js AES 加密與 Java/C# 互通:關鍵在 createCipheriv 與 IV 參數

Node.js crypto 模組預設 createCipher 使用 OpenSSL 的 EVP_BytesToKey 衍生金鑰與 IV,導致與 Java/C# 標準 AES (PKCS5Padding、固定 IV) 不相容。解決關鍵:**改用 createCipheriv 明確指定 IV**,並統一填充模式。

問題重現


// Node.js 錯誤寫法:createCipher 自動衍生 IV
var cipher = crypto.createCipher('aes-128-ecb', key); // ECB 模式不需 IV,但金鑰衍生方式不同

正確寫法:createCipheriv + 明確 IV


const crypto = require('crypto');

const data = '156156165152165156156';
const algorithm = 'aes-128-ecb'; // ECB 模式不使用 IV
const key = '78541561566';       // 16 bytes key for aes-128
const iv = '';                   // ECB 模式 IV 必須為空字串或 Buffer.alloc(0)

function encrypt(clearText) {
    const cipher = crypto.createCipheriv(algorithm, key, iv);
    let encrypted = cipher.update(clearText, 'utf8', 'base64');
    encrypted += cipher.final('base64');
    return encrypted;
}

function decrypt(cipherText) {
    const decipher = crypto.createDecipheriv(algorithm, key, iv);
    let decrypted = decipher.update(cipherText, 'base64', 'utf8');
    decrypted += decipher.final('utf8');
    return decrypted;
}

console.log('加密:', encrypt(data));
console.log('解密:', decrypt(encrypt(data)));

CBC 模式完整範例(含 IV)


const algorithm = 'aes-256-cbc';
const key = crypto.scryptSync('password', 'salt', 32); // 32 bytes key
const iv = crypto.randomBytes(16); // 16 bytes IV

function encryptCBC(text) {
    const cipher = crypto.createCipheriv(algorithm, key, iv);
    let enc = cipher.update(text, 'utf8', 'hex');
    enc += cipher.final('hex');
    return iv.toString('hex') + ':' + enc; // IV 隨密文傳輸
}

function decryptCBC(data) {
    const [ivHex, encHex] = data.split(':');
    const decipher = crypto.createDecipheriv(algorithm, key, Buffer.from(ivHex, 'hex'));
    let dec = decipher.update(encHex, 'hex', 'utf8');
    dec += decipher.final('utf8');
    return dec;
}

Java/C# 互通關鍵點

項目Node.jsJava (JCE)C# (AesManaged)
演算法aes-128-ecb / aes-256-cbcAES/ECB/PKCS5Padding / AES/CBC/PKCS5PaddingAesManaged { Mode=CipherMode.ECB/CBC, Padding=PaddingMode.PKCS7 }
金鑰長度16/32 bytes16/32 bytes16/32 bytes
IVECB: 空; CBC: 16 bytesECB: 不用; CBC: 16 bytes同左
金鑰處理直接用字串或 Buffer常對密碼做 MD5 取 16 bytes常用 Rfc2898DeriveBytes 或直接指定 Key

常見坑點

  • ECB 模式不安全:相同明文產生相同密文,生產環境請用 CBC/GCM。
  • 金鑰長度不符:aes-128 需 16 bytes,aes-256 需 32 bytes,不足會報錯。
  • 字元編碼:統一用 UTF-8 將字串轉 Buffer。
  • 輸出格式:Base64 或 Hex,雙方需一致。
copyright © 萬盛學電腦網 all rights reserved