Node.js Create an Initialization Vector (IV) from a Random Source

How to create an initialization vector (IV) from a random source in NodeJS, as 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 might help, but no.

+6
source share
1 answer

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

 Crypto.createCipheriv() 

A function that can generate a randomized initialization vector for you will be:

 Crypto.randomBytes(16) 

A value of 16 means the number of bytes needed to complete the required vector length.

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 completeness, here is an example of 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(); 
+17
source

Source: https://habr.com/ru/post/974157/


All Articles