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

后端 未结 1 1619
借酒劲吻你
借酒劲吻你 2021-02-05 16:11

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         


        
1条回答
  •  清歌不尽
    2021-02-05 16:54

    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();
    

    0 讨论(0)
提交回复
热议问题