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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With