IV + 密文格式
// 生成 AES 金鑰
const aesKey = CryptoJS.lib.WordArray.random(32);
console.log("aesKey (Base64):", CryptoJS.enc.Base64.stringify(aesKey));
// RSA 加密 AES 金鑰
const rsa = forge.pki.publicKeyFromPem(publicKeyPEM);
const encryptedAESKey = forge.util.encode64(rsa.encrypt(aesKey.toString(CryptoJS.enc.Base64)));
// 生成 IV
const iv = CryptoJS.lib.WordArray.random(16);
// AES 加密數據
const encryptedData = CryptoJS.AES.encrypt(
JSON.stringify(data),
aesKey, // 直接用 WordArray
{
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7,
iv: iv
}
);
// 確保 IV + 密文格式正確
const finalCiphertext = CryptoJS.enc.Base64.stringify(
CryptoJS.lib.WordArray.create(iv.words.concat(encryptedData.ciphertext.words))
);