0

我有一些 PHP 代码会产生一些密文,如下所示:

<?php
$data = '12345678123456781234567812345678123456781234567812345678123456781234567812345678';

$ciphertext = mcrypt_encrypt('rijndael-128', 'M02cnQ51Ji97vwT4', $data, 'ecb');

echo base64_encode($ciphertext);
?>

产生:

6tJ67oaF1X12X/FE4ahLdOrSeu6GhdV9dl/xROGoS3Tq0nruhoXVfXZf8UThqEt06tJ67oaF1X12X/FE4ahLdOrSeu6GhdV9dl/xROGoS3Q=

我知道 ECB 不是用于此类数据的最佳模式,但我不是加密它的人。

我遇到的麻烦是 node-crypto 试图解密它。我的节点脚本如下:

var crypto = require("crypto");    

var data = "6tJ67oaF1X12X/FE4ahLdOrSeu6GhdV9dl/xROGoS3Tq0nruhoXVfXZf8UThqEt06tJ67oaF1X12X/FE4ahLdOrSeu6GhdV9dl/xROGoS3Q=";

var out = '';

var decipher = crypto.createDecipher("aes-256-ecb", "M02cnQ51Ji97vwT4");

decipher.setAutoPadding(false); //this needs to be set otherwise i get an error:06065064:bad decrypt

out += decipher.update(data, "base64", "ascii");

out += decipher.final("ascii");

console.log(out);

产生:

"3i<1pzV7A

      vnE"3i<1pzV7A

                   vnE"3i<1pzV7A

                                vnE"3i<1pzV7A

                                             vnE"3i<1pzV7A

                                                          vnE

我无法判断这里出了什么问题,原始数据的重复模式已恢复但不正确。我很难在 openssl 中找到等效的“rijndael-128”,而且它似乎必须是“aes-256-ecb”,并且不需要 IV,因为它是 ECB。我怎样才能让这两个库一起工作?

谢谢,J

4

2 回答 2

1

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

var mcrypt = require('mcrypt');

var bfEcb = new mcrypt.MCrypt('rijndael-128', 'ecb');
bfEcb.open('M02cnQ51Ji97vwT4');

var ciphertext = new Buffer('6tJ67oaF1X12X/FE4ahLdOrSeu6GhdV9dl/xROGoS3Tq0nruhoXVfXZf8UThqEt06tJ67oaF1X12X/FE4ahLdOrSeu6GhdV9dl/xROGoS3Q=', 'base64');
var plaintext = bfEcb.decrypt(ciphertext);
console.log(plaintext.toString());
于 2013-09-23T17:33:20.970 回答
1

尝试这个:

var crypto = require("crypto");    
var data = "6tJ67oaF1X12X/FE4ahLdOrSeu6GhdV9dl/xROGoS3Tq0nruhoXVfXZf8UThqEt06tJ67oaF1X12X/FE4ahLdOrSeu6GhdV9dl/xROGoS3Q=";

var out = '';

var decipher = crypto.createDecipheriv("aes-256-ecb", "M02cnQ51Ji97vwT4", '');
out += decipher.update(data, "base64");
out += decipher.final();

console.log(out);

在我的例子中,使用空的第三个参数(所谓的初始化向量)将 createDecipher(...) 更改为 createDecipheriv(最后注意iv )可以解决问题。在这种情况下,删除 setAutoPadding(false)。

于 2013-11-05T11:16:43.643 回答