2016-08-19 62 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