【问题标题】:cipher.js TypeError: IV must be a buffercipher.js TypeError: IV must be a buffer
【发布时间】:2018-05-30 08:35:12
【问题描述】:
var path = require('path');
var fs = require('fs');
var crypto = require('crypto');

var algorithm = 'aes-256-ctr';
var password = 'xxxxx';

var dir = '/Users/antkong/some/path';
var file = 'somefile.json';

var clearTextPath = path.join(dir, file);
var cipher = crypto.createCipheriv(algorithm, password);
var readStream = fs.createReadStream(clearTextPath);
var writeStream = fs.createWriteStream(path.join(dir, file + '.encrypted'));
readStream.pipe(cipher).pipe(writeStream);

然后我得到了这个错误:

internal/crypto/cipher.js:139
  this._handle.initiv(cipher, toBuf(key), toBuf(iv));
               ^

TypeError: IV must be a buffer
    at new Cipheriv (internal/crypto/cipher.js:139:16)
    at Object.createCipheriv (crypto.js:98:10)

我的节点版本是9.11.1

我已验证源文件存在。

为什么失败了?它在旧版本的节点上工作(早于版本 8.x)

【问题讨论】:

    标签: node.js node-crypto


    【解决方案1】:

    createCipheriv方法中没有传入初始化向量参数。

    var IV = new Buffer(crypto.randomBytes(16)); 
    var cipher = crypto.createCipheriv(algorithm, password, IV);
    

    【讨论】:

    • 感谢您的回答!现在我得到一个不同的错误:Invalid key length。合适的长度应该是多少?
    • 这里的聚会可能会迟到,但对于遇到这种情况的人来说。无效的密钥长度是因为“密码”太短。 aes-256 需要一个 32 字节的密钥
    • @Slaphead 我用过crypto.randomBytes(32),但现在它显示的是Invalid IV length。有什么建议吗?
    【解决方案2】:

    看看这个:

    var IV = new Buffer(crypto.randomBytes(12)); 
    

    // 这需要为 'aes-256-gcm' 的 12 字节缓冲区

    【讨论】:

      猜你喜欢
      • 2018-06-07
      • 1970-01-01
      • 2012-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-27
      相关资源
      最近更新 更多