【问题标题】:Node JS crypto.createCipheriv Error: Invalid key length节点 JS crypto.createCipheriv 错误:无效的密钥长度
【发布时间】:2021-03-02 18:26:25
【问题描述】:

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

代码如下:

const crypto = require('crypto');

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

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

console.log(encrypted);

我收到以下错误:

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

我做错了什么?

【问题讨论】:

    标签: javascript node.js encryption cryptography node-crypto


    【解决方案1】:

    你使用了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,或查看RFC 5288 nonce 规范。
    • @Seti 请再次阅读 Maarten 的回答。它明确指出,对于 AES-GCM 模式,IV 的默认长度为 12 字节(无论密钥大小如何)。是的,它可以有不同的,但随后 IV 被散列(正如詹姆斯所说的“额外工作”)以获得必要的长度,如果它首先具有正确的长度,则不需要。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-18
    • 2018-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-23
    • 2022-09-26
    相关资源
    最近更新 更多