Search code examples
node.jsnode-crypto

cipher.js TypeError: IV must be a buffer


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);

Then I got this error:

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)

My node version is 9.11.1

I have verified that the source files exists.

Why it failed? It was working in older version of node (Earlier than version 8.x)


Solution

  • Initialization vector parameter is not passed in createCipheriv method.

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