2016-08-19 63 views
0

我似乎无法弄清楚是什么导致语言之间的差异。在Java中,我有:无法转换解密代码usingg Blowfish ECB从Java到Node.js

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

然后在节点我变成了这样:

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

回答

2

There ar e几个问题在这里:

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

    const buf = Buffer.from("AutMdzthDvPlE+UnhcHa2h4UZGPdme7t", "base64"); 
    
  2. 传递给createDecipher()第二个参数是一个密码一个关键。不同的是,createDecipher()散列密码参数(使用MD5)来生成密钥。既然你已经有了钥匙,你想要的却是createDecipheriv(),它需要一把钥匙和四把钥匙。由于ECB模式不使用IV,所以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(); 
+0

基于64位只是一个错误,我当复制它,但我没有意识到createDecipher期待一个密码!万分感谢。 – PaulBGD