使用node.js解密mcrypt编码的文本 [英] Decrypting mcrypt encoded text with node.js

查看:513
本文介绍了使用node.js解密mcrypt编码的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have text encoded with Blowfish using PHP's mcrypt:

$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的crypto库解码数据时,我得到垃圾输出。

When trying to decode the data with Node's crypto library I get garbage output.

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(crypto库是一个包装器)直接给出相同的乱码结果:

Using openssl (which the crypto library is a wrapper for) directly gives the same garbled result:

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

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

So it doesn't look like a problem with the Javascript code.

推荐答案

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

这篇关于使用node.js解密mcrypt编码的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆