Javascript 节点JS crypto.createCipheriv错误:密钥长度无效

Javascript 节点JS crypto.createCipheriv错误:密钥长度无效,javascript,node.js,encryption,cryptography,node-crypto,Javascript,Node.js,Encryption,Cryptography,Node Crypto,我正在尝试使用node.js加密模块加密文本 以下是代码: const crypto=require('crypto'); const password='password'; const key=crypto.scryptSync(密码'salt',24); 常数iv=加密随机字节(16); 常量密码=crypto.createCipheriv('aes-256-gcm',密钥,iv); var encrypted=cipher.update(“Hello”、“utf8”、“hex”)+cip

我正在尝试使用node.js加密模块加密文本

以下是代码:

const crypto=require('crypto');
const password='password';
const key=crypto.scryptSync(密码'salt',24);
常数iv=加密随机字节(16);
常量密码=crypto.createCipheriv('aes-256-gcm',密钥,iv);
var encrypted=cipher.update(“Hello”、“utf8”、“hex”)+cipher.final(“hex”);
console.log(加密);
我得到以下错误:

internal/crypto/cipher.js:103
    this[kHandle].initiv(cipher, credential, iv, authTagLength);
                  ^

Error: Invalid key length
[90m    at Cipheriv.createCipherBase (internal/crypto/cipher.js:103:19)[39m
[90m    at Cipheriv.createCipherWithIV (internal/crypto/cipher.js:121:20)[39m
[90m    at new Cipheriv (internal/crypto/cipher.js:225:22)[39m
[90m    at Object.createCipheriv (crypto.js:117:10)[39m
    at Object.<anonymous> (F:\Misc\App\MySQL-Buzzer-Electron\demo.js:7:23)
[90m    at Module._compile (internal/modules/cjs/loader.js:1156:30)[39m
[90m    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1176:10)[39m
[90m    at Module.load (internal/modules/cjs/loader.js:1000:32)[39m
[90m    at Function.Module._load (internal/modules/cjs/loader.js:899:14)[39m
[90m    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)[39m
internal/crypto/cipher.js:103
此[kHandle].initiv(密码、凭证、iv、authTagLength);
^
错误:无效的密钥长度
[Cipheriv.createCipherse上的90m(内部/加密/密码js:103:19)[39m]
[90米在Cipheriv.CreateCippherWithIV(internal/crypto/cipher.js:121:20)[39米
[90米在新Cipheriv(内部/加密/密码js:225:22)[39米
[90米在Object.createCipheriv(crypto.js:117:10)[39米
at对象。(F:\Misc\App\MySQL蜂鸣器Electron\demo.js:7:23)
[90米模块处。_编译(内部/modules/cjs/loader.js:1156:30)[39米
[90米在Object.Module._extensions..js(internal/modules/cjs/loader.js:1176:10)[39米
[Module.load处为90m(内部/modules/cjs/loader.js:1000:32)[39m
[90米功能模块加载(内部/modules/cjs/loader.js:899:14)[39米
[Function.executeUserEntryPoint[as runMain](internal/modules/run_main.js:74:12)[39m]

我做错了什么?

您使用了
aes-256-gmc
您需要使用
32的键长和
16的iv键长

const crypto = require('crypto');

const password = 'password';
const key = crypto.scryptSync(password, 'salt', 32);

const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
var encrypted = cipher.update("Hello", 'utf8', 'hex') + cipher.final('hex');

对于GCM,iv长度应该是12。但对于aes-256-GMC,则不是GMC。正如您所看到的,它是GCM.16,但12更有意义,因为任何其他内容都会导致计算预计数器块的额外工作。请阅读NIST SP 800-38D中的GCM,或查看nonce规范。@Seti请再次阅读Maarten的答案。它是cl早期声明,对于AES-GCM模式,IV的默认长度为12字节(不考虑密钥大小)。是的,它可以有不同的长度,但随后对IV进行哈希运算(“额外工作”,如James所说),以获得必要的长度,如果它首先具有正确的长度,则不需要该长度。