“不支持的状态或无法验证数据"在节点中使用aes-128-gcm [英] "Unsupported state or unable to authenticate data" with aes-128-gcm in Node
问题描述
我正在尝试使用节点密码提供的aes-128-gcm实现加密/解密功能.据我了解,gcm对密文进行加密,但也对其进行哈希处理,并将其作为身份验证标签"提供.但是,我不断收到错误消息:状态不受支持或无法验证数据".
I'm trying to implement encrypt/decrypt functions using aes-128-gcm as provided by node crypto. From my understanding, gcm encrypts the ciphertext but also hashes it and provides this as an 'authentication tag'. However, I keep getting the error: "Unsupported state or unable to authenticate data".
我不确定这是否是我的代码中的错误-查看加密的密文和auth标记,解密函数获取的与加密函数产生的相同.
I'm not sure if this is an error in my code - looking at the encrypted ciphertext and auth tag, the one being fetched by the decrypt function is the same as the one produced by the encrypt function.
function encrypt(plaintext) {
// IV is being generated for each encryption
var iv = crypto.randomBytes(12),
cipher = crypto.createCipheriv(aes,key,iv),
encryptedData = cipher.update(plaintext),
tag;
// Cipher.final has been called, so no more encryption/updates can take place
encryptedData += cipher.final();
// Auth tag must be generated after cipher.final()
tag = cipher.getAuthTag();
return encryptedData + "$$" + tag.toString('hex') + "$$" + iv.toString('hex');
}
function decrypt(ciphertext) {
var cipherSplit = ciphertext.split("$$"),
text = cipherSplit[0],
tag = Buffer.from(cipherSplit[1], 'hex'),
iv = Buffer.from(cipherSplit[2], 'hex'),
decipher = crypto.createDecipheriv(aes,key,iv);
decipher.setAuthTag(tag);
var decryptedData = decipher.update(text);
decryptedData += decipher.final();
}
decipher.final()引发错误.
The error is being thrown by decipher.final().
推荐答案
我设法解决了这个问题:问题是我没有为cipher.final()指定编码类型,而是在String中返回了它,因此它并没有返回decipher.final()期望的Buffer对象.
I managed to fix this: the issue was that I wasn't specifying an encoding type for cipher.final() and I was returning it within a String, so it wasn't returning a Buffer object, which decipher.final() was expecting.
要解决此问题,我在cipher.update和cipher.final中的"hex"编码参数中添加了"utf-8",反之亦然.
To fix, I add 'utf-8' to 'hex' encoding parameters within my cipher.update and cipher.final, and vice versa in decipher.
这篇关于“不支持的状态或无法验证数据"在节点中使用aes-128-gcm的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!