Getting error of Invalid IV Length while using aes-256-cbc for encryption in node

From https://github.com/nodejs/node/issues/6696#issuecomment-218575039 -

The default string encoding used by the crypto module changed in v6.0.0 from binary to utf8. So your binary string is being interpreted as utf8 and is most likely becoming larger than 16 bytes during that conversion process (rather than smaller than 16 bytes) due to invalid utf8 character bytes being added.

Modifying your code so that ivstring is always 16 characters in length should solve your issue.

var ivstring = iv.toString('hex').slice(0, 16);

The above answer adds more overhead than needed, since you converted each byte to a hexidecimal representation that requires twice as many bytes all you need to do is generate half the number of bytes

  var crypto = require('crypto');
  var key = 'ExchangePasswordPasswordExchange';
  var  plaintext = '150.01';
  var iv = new Buffer(crypto.randomBytes(8))
  ivstring = iv.toString('hex');


  var cipher = crypto.createCipheriv('aes-256-cbc', key, ivstring)
  var  decipher = crypto.createDecipheriv('aes-256-cbc', key,ivstring);

  cipher.update(plaintext, 'utf8', 'base64');
  var encryptedPassword = cipher.final('base64');

Tags:

Node.Js