Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js Create initialization vector (IV) from random source

Tags:

node.js

How to create a initialization vector (IV) from a random source in NodeJS, like I do in PHP as follows:

$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_RAND);

In NodeJS I thought crypto.createCipheriv could help but no.

like image 777
Jack M. Avatar asked Aug 21 '14 13:08

Jack M.


1 Answers

You are on the right track and will still need to use:

Crypto.createCipheriv()

The function that can generate you a randomized initialization vector would be:

Crypto.randomBytes(16)

The 16 signifies the number of bytes required to fulfil the required length of the vector.

To give an example:

var iv = Crypto.randomBytes(16);
var cipher = Crypto.createCipheriv('aes-128-cbc', new Buffer(<128 bit password>), iv);
var encrypted = cipher.update(clearText);
var finalBuffer = Buffer.concat([encrypted, cipher.final()]);
//Need to retain IV for decryption, so this can be appended to the output with a separator (non-hex for this example)
var encryptedHex = iv.toString('hex') + ':' + finalBuffer.toString('hex')

For the sake of completeness, here's an example for decrypting the above encryptedHex

var encryptedArray = encryptedHex.split(':');
var iv = new Buffer(encryptedArray[0], 'hex');
var encrypted = new Buffer(encryptedArray[1], 'hex');
var decipher = Crypto.createDecipheriv('aes-128-cbc', new Buffer(<128 bit password>), iv);
var decrypted = decipher.update(encrypted);
var clearText = Buffer.concat([decrypted, decipher.final()]).toString();
like image 188
gyamana Avatar answered Oct 13 '22 00:10

gyamana