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,但金鑰衍生方式不同
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)));
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;
}
| 項目 | Node.js | Java (JCE) | C# (AesManaged) |
|---|---|---|---|
| 演算法 | aes-128-ecb / aes-256-cbc | AES/ECB/PKCS5Padding / AES/CBC/PKCS5Padding | AesManaged { Mode=CipherMode.ECB/CBC, Padding=PaddingMode.PKCS7 } |
| 金鑰長度 | 16/32 bytes | 16/32 bytes | 16/32 bytes |
| IV | ECB: 空; CBC: 16 bytes | ECB: 不用; CBC: 16 bytes | 同左 |
| 金鑰處理 | 直接用字串或 Buffer | 常對密碼做 MD5 取 16 bytes | 常用 Rfc2898DeriveBytes 或直接指定 Key |
aes-128 需 16 bytes,aes-256 需 32 bytes,不足會報錯。