AES-GCM 模式的正确 nonce/iv 大小

correct nonce/iv size for AES-GCM mode

编辑:问题可以简化为: 以下 Node.js 代码给出 "Invalid IV length" 错误。为什么? IV 应该是多少?

const crypto = require('crypto')
const decipher = crypto.createDecipheriv('aes-128-gcm', crypto.randomBytes(16), crypto.randomBytes(16))

我在 GCM 模式下使用 AES 来加密一些数据,但我使用两种不同的语言和库进行加密和解密,它们似乎对我需要的内容有不同的词汇表。

我正在使用 Python 库 (Crypto) 进行加密。 encrypt_and_digest 方法采用 128 位密钥和消息,returns 128 位随机数、128 位标签和密文。

(加密代码取自this example

我正在使用默认 Node.js 解密 crypto library. That library expects a session key, a tag, and an IV. When I pass the nonce from the Python library as the IV, it gives me an “invalid iv size” error. Examples Node 库似乎使用 12 个字符的字符串作为 IV。

我的解密代码是这样的(取自here):

var decipher = crypto.createDecipheriv(algorithm, password, nonce)
decipher.setAuthTag(encrypted.tag);
var dec = decipher.update(encrypted.content, 'hex', 'utf8')

这个方案的IV和nonce有什么区别?我应该如何解决这个问题?谢谢!

原来 GCM 的随机数应该是 12 个字节长。我不确定为什么 python 库默认自动生成一个 16 字节的随机数,但您可以生成自己的随机数并在 AES 构造函数中手动指定它,这就是我所做的。整个系统现在完美运行