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

Anthony Kong
  • 37,791
  • 46
  • 172
  • 304

2 Answers2

0

Initialization vector parameter is not passed in createCipheriv method.

var IV = new Buffer(crypto.randomBytes(16)); 
var cipher = crypto.createCipheriv(algorithm, password, IV);
Ashok JayaPrakash
  • 2,115
  • 1
  • 16
  • 22
  • 2
    Thanks for the answer! Now I get a different error: `Invalid key length`. What should be the right length? – Anthony Kong May 30 '18 at 10:10
  • Might be late to the party here, but for those who come across this. The invalid key length is because the "password" is too short. aes-256 requires a 32 byte key – Slaphead Sep 09 '18 at 17:40
  • @Slaphead I have used `crypto.randomBytes(32)` but now it says `Invalid IV length`. Any suggestion? – Anthony Kong Jul 09 '19 at 01:46
0

Have a look at this:

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

// this needs to be a 12 byte buffer for 'aes-256-gcm'