java - 无法使用 Blowfish ECB 将解密代码从 Java 转换为 Node.js

标签 java node.js encryption blowfish

我似乎无法弄清楚是什么导致了语言之间的差异。在Java中我有:

byte[] buf = Base64.getDecoder().decode("AutMdzthDvPlE+UnhcHa2h4UZGPdme7t");
System.out.println(buf.length);
String key = "" + 2270457870L;
byte[] keyBytes = key.getBytes("UTF8");
System.out.println(keyBytes.length);

Cipher cipher = Cipher.getInstance("Blowfish/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(keyBytes, "Blowfish"));

byte[] newBytes = cipher.doFinal(buf);
System.out.println(newBytes.length);
System.out.println(Arrays.toString(newBytes));

(可在 http://ideone.com/0dXuJL 在线运行)

然后在 Node 中我把它变成了:

const buf = Buffer.from("AutMdzthDvPlE+UnhcHa2h4UZGPdme7t");
console.log(buf.length);
const keyBytes = Buffer.from('2270457870', 'utf8');
console.log(keyBytes.length);
const decipher = require('crypto').createDecipher('bf-ecb', keyBytes);

const buffers = [];
buffers.push(decipher.update(buf));
buffers.push(decipher.final());

const newBytes = Buffer.concat(buffers);
console.log(newBytes.length);
console.log(newBytes);

(可在 https://tonicdev.com/paulbgd/57b66c8ea0630d1400081ad0 在线运行)

输出错误:错误:06065064:数字信封例程:EVP_DecryptFinal_ex:解密错误

最佳答案

这里有几个问题:

  1. buf 缺少字符串编码。默认情况下,使用 utf8,但该字符串实际上是 base64 编码的。要解决此问题,请改用此方法:

    const buf = Buffer.from("AutMdzthDvPlE+UnhcHa2h4UZGPdme7t", "base64");
    
  2. 传递给 createDecipher() 的第二个参数是密码不是 key 。不同之处在于 createDecipher() 对密码参数进行哈希处理(使用 MD5)以生成 key 。既然你已经有了 key ,你想要的是 createDecipheriv() ,需要一个 key 和 IV。 IV 参数可以是零长度缓冲区,因为 ECB 模式不使用 IV。所以用这个代替:

    const decipher = require('crypto').createDecipheriv('bf-ecb', keyBytes, Buffer.alloc(0));
    

最后,如果您想匹配 Java 的字节输出,您可以将 console.log(newBytes) 替换为如下内容:

for (var i = 0; i < newBytes.length; ++i)
  process.stdout.write(newBytes.readInt8(i) + ' ');
console.log();

关于java - 无法使用 Blowfish ECB 将解密代码从 Java 转换为 Node.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39030204/

相关文章:

java - 将 Neo4j 密码查询转换为 orientdb/gremlin(在 java 中)

java - 异常转换器 com.itextpdf.text.pdf.parser.InlineImageUtils$InlineImageParseException : Could not find image data or EI 420

java - Android套接字客户端 - 无法发送消息

javascript - 如何理解这个 Node.js 代码片段?

node.js - Terra (LUNA) 获取 NodeJs 交易列表

java - FragmentManager 知道 fragment 何时恢复

javascript - 在输入字段内使用图标后,默认 'input is required/Please fill out this field' 消息不显示

ios - CCCrypto解密: exactly one block less

ios - 是否可以仅使用 Javascript 来加密/解密 SQLite 数据库?

javascript - PHP 和 cryptoJS IV