2012-03-12 51 views
0

我正在使用Blowfish實現一個簡單的密碼存儲。一切都很好,直到我嘗試了幾個不同的密碼/組合鍵,並且遇到了大量解密值仍然是垃圾的實例。Java Blowfish解密不給原始字符串

下面是一個演示此問題的獨立類。我得到以下輸出:

'Aaaaaaa7' encrypted: 'r?—èLèdÓ,·Ã¸ÍÒ'* 
'Aaaaaaa7' decrypted: 'ñü=€¼(T'* 

任何想法,我需要做什麼來保證它始終正確解密。

由於(在JDK 1.6.0_26使用jce.jar),

大衛

import javax.crypto.Cipher; 
import javax.crypto.spec.SecretKeySpec; 

public class BlowfishTwoWayHashImpl { 

    static { 
     test(); 
    } 

    public static void test() { 
     String key = "wibble"; 

     String passwordToEnrypt = "Aaaaaaa7"; 

     String enc = BlowfishTwoWayHashImpl.encryptBlowfish(passwordToEnrypt, key); 
     System.out.println("'" + passwordToEnrypt + "' encrypted: '" + enc + "'"); 

     String dec = BlowfishTwoWayHashImpl.decryptBlowfish(enc, key); 
     System.out.println("'" + passwordToEnrypt + "' decrypted: '" + dec + "'"); 
    } 


    private static final String CIPHER_NAME = "Blowfish"; 

    public static String encryptBlowfish(String toEncrypt, String key) { 
     return processString(toEncrypt, key, Cipher.ENCRYPT_MODE); 
    } 

    public static String decryptBlowfish(String toDecrypt, String key) { 
     return processString(toDecrypt, key, Cipher.DECRYPT_MODE); 
    } 

    private static String processString(String toEncrypt, String key, int encryptDecryptMode) { 

     SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), CIPHER_NAME); 

     Cipher cipher; 
     try { 
      cipher = Cipher.getInstance(CIPHER_NAME); 
      cipher.init(encryptDecryptMode, secretKeySpec); 
      return new String(cipher.doFinal(toEncrypt.getBytes())); 
     } 
     catch (Exception e) { 
      throw new RuntimeException(e.toString()); 
     } 
    } 

} 

回答

4

不要這樣做:

return new String(cipher.doFinal(toEncrypt.getBytes())); 

您使用平臺默認編碼遍佈整個地方。 不要這樣做。它會丟失數據。

當您將真正的文本轉換爲字節(例如加密時)時,請使用特定的字符集 - UTF-8是一個不錯的選擇。使用相同的字符集從「編碼文本」解碼到String

當您將任意二進制數據轉換爲文本時,請使用base64編碼(例如,通過this public domain Base64 encoding library

基本上,當您使用String(byte[])String(byte[], String)構造函數創建一個新字符串時,您會說:「這是真正的文本數據 - 請將其解碼爲字符串。」當數據實際上是加密的結果時,它是而不是文本數據......它是一個任意的字節串。

+0

好吧,我使用了Apache Base64實現,而不是做這項工作。 – user1016765 2012-03-12 16:08:51