我有一些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
答案 0 :(得分: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());
答案 1 :(得分: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)。