使用node.js解密mcrypt编码的文本

时间:2012-01-17 13:24:38

标签: javascript node.js cryptography mcrypt blowfish

我使用PHP的mcrypt编写了使用Blowfish编码的文本:

$td = mcrypt_module_open ('blowfish', '', 'cfb', '');
$iv = mcrypt_create_iv (mcrypt_enc_get_iv_size ($td), MCRYPT_RAND);
mcrypt_generic_init ($td, "somekey", $iv);
$crypttext = mcrypt_generic ($td, "sometext");
mcrypt_generic_deinit ($td);
$res = base64_encode($iv.$crypttext);

当尝试使用Node的加密库解码数据时,我得到了垃圾输出。

var crypto = require("crypto"),
    ivAndCiphertext = "base64-encoded-ciphertext", 
    iv, cipherText, ivSize = 8, res= "";

ivAndCiphertext = new Buffer(ivAndCiphertext, 'base64');
iv = new Buffer(ivSize);
cipherText = new Buffer(ivAndCiphertext.length - ivSize);
ivAndCiphertext.copy(iv, 0, 0, ivSize);
ivAndCiphertext.copy(cipherText, 0, ivSize);

c = crypto.createDecipheriv('bf-cfb', "somekey", iv.toString("binary"));
res = c.update(cipherText, "binary", 'utf8');
res += c.final('utf8');

知道我做错了什么?

修改

使用openssl(加密库是包装器)会直接产生相同的乱码结果:

openssl enc -K the_key_in_hex bf-cfb -d -p -iv the_iv_in_hex -nosalt -nopad -a

所以它看起来不像Javascript代码的问题。

3 个答案:

答案 0 :(得分:3)

https://github.com/tugrul/node-mcrypt

加密:

var mcrypt = require('mcrypt');

var bfEcb = new mcrypt.MCrypt('blowfish', 'cfb');
var iv = bfEcb.generateIv();

bfEcb.open('somekey', iv);

var cipherText = bfEcb.encrypt('sometext');

console.log(Buffer.concat([iv, cipherText]).toString('base64'));

解密:

var mcrypt = require('mcrypt');
var bfEcb = new mcrypt.MCrypt('blowfish', 'cfb');

var ivAndCiphertext = new Buffer('AyvfjTyg24Y9fVCdjzRPEw==', 'base64');

var ivSize = bfEcb.getIvSize();
var iv = new Buffer(ivSize);
var cipherText = new Buffer(ivAndCiphertext.length - ivSize);

ivAndCiphertext.copy(iv, 0, 0, ivSize);
ivAndCiphertext.copy(cipherText, 0, ivSize);

bfEcb.open('somekey', iv);

console.log(bfEcb.decrypt(cipherText).toString());

答案 1 :(得分:0)

我不确定是否还有其他错误,但在使用IV时你应该使用createDecipheriv方法:

http://nodejs.org/docs/latest/api/crypto.html#crypto.createDecipheriv

答案 2 :(得分:0)

您正在使用ivAndCiphertext = "base64-encoded-ciphertext",后面紧跟ivAndCiphertext = new Buffer(ivAndCiphertext, 'base64');。您的变量将指向新缓冲区,因此您将获得解密新缓冲区的结果。