我有以下代碼:
const crypto = require("crypto");
const algorithm = "aes-256-gcm";
const message = "This is a secret message";
const iv = crypto.randomBytes(12);
const sKey = crypto.randomBytes(32);
const cipher = crypto.createCipheriv(algorithm, sKey, iv);
const decipher = crypto.createDecipheriv(algorithm, sKey, iv)
let encryptedData = cipher.update(message, "utf-8", "hex");
encryptedData = cipher.final("hex");
let decData = decipher.update(encryptedData, "hex", "utf-8");
decData = decipher.final("utf-8");
console.log("Encrypted message: " encryptedData);
console.log("Decrypted message: ", decData)
當我運行它時,我收到以下例外:
node:internal/crypto/cipher:193
const ret = this[kHandle].final();
^
Error: Unsupported state or unable to authenticate data
at Decipheriv.final (node:internal/crypto/cipher:193:29)
at Object.<anonymous> ([...]/crypto-test.js:15:21)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:17:47
呼叫時拋出錯誤decipher.final()。我該如何解決?
uj5u.com熱心網友回復:
使用經過身份驗證的密碼(即aes-256-gcm)時,您需要密碼中的 auth 標簽;否則Decipher.final()會拋出(如您所見),因為它具有(或在這種情況下,沒有)的身份驗證標簽與它認為的解密文本的身份驗證標簽不匹配。
const crypto = require('crypto');
const algorithm = 'aes-256-gcm';
const message = 'This is a secret message';
const iv = crypto.randomBytes(12);
const sKey = crypto.randomBytes(32);
const cipher = crypto.createCipheriv(algorithm, sKey, iv);
let encryptedData = cipher.update(message, 'utf-8', 'hex');
encryptedData = cipher.final('hex');
const authTag = cipher.getAuthTag().toString("hex"); // <- new
console.log({authTag, encryptedData}); // for debugging
const decipher = crypto.createDecipheriv(algorithm, sKey, iv);
decipher.setAuthTag(Buffer.from(authTag, 'hex')); // <- new
let decData = decipher.update(encryptedData, 'hex', 'utf-8');
decData = decipher.final('utf-8');
console.log('Decrypted message: ', decData)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/453606.html
標籤:javascript 节点.js AES
