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

时间:2016-08-19 02:24:18

标签: 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 I中将其转换为:

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在线运行)

哪个输出错误:error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt

1 个答案:

答案 0 :(得分:2)

这里有几个问题:

  1. buf缺少字符串编码。默认情况下,使用utf8,但字符串实际上是base64编码的。为了解决这个问题,请改为使用它:

    const buf = Buffer.from("AutMdzthDvPlE+UnhcHa2h4UZGPdme7t", "base64");
    
  2. 传递给createDecipher()的第二个参数是密码不是 密钥。区别在于createDecipher()哈希密码参数(使用MD5)来生成密钥。由于您已经拥有密钥,因此您需要的是createDecipheriv(),它需要密钥和IV。 IV参数可以只是一个零长度的缓冲区,因为ECB模式不使用IV。所以请改用它:

    const decipher = require('crypto').createDecipheriv('bf-ecb', keyBytes, Buffer.alloc(0));
    
  3. 最后,如果要匹配Java输出的字节,可以用以下代码替换console.log(newBytes)

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