node.js从随机源创建初始化向量(IV)

时间:2014-08-21 13:43:02

标签: node.js

如何从NodeJS中的随机源创建初始化向量(IV),就像我在PHP中一样,如下所示:

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

在NodeJS中,我认为crypto.createCipheriv可能有所帮助,但没有。

1 个答案:

答案 0 :(得分:28)

你走在正确的轨道上,仍然需要使用:

Crypto.createCipheriv()

可以为您生成随机初始化向量的函数是:

Crypto.randomBytes(16)

16表示满足向量所需长度所需的字节数。

举个例子:

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')

为了完整起见,以下是解密上述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();