2013-04-21 64 views
0

我試圖創建一個簡單的加密和解密類。兩種方法都給出了相同的字符串。我有點困惑。請需要幫助。創建一個簡單的AES加密和解密

這裏是我的代碼片段:

public class UltimateEncryptor { 

    private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding"; 
    private static final String RANDOM_GENERATOR_ALGORITHM = "AES"; 


    // Encrypts string and encodes in Base64 
    public String encrypt(String password, String data) throws Exception 
    { 
    byte[] secretKey = password.getBytes(); 
    byte[] clear = data.getBytes(); 

    SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey, CIPHER_ALGORITHM); 
    Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); 
    cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); 

    byte[] encrypted = cipher.doFinal(clear); 
    String encryptedString = Base64.encodeToString(encrypted, Base64.DEFAULT); 

    return encryptedString; 
    } 

    // Decrypts string encoded in Base64 
    public String decrypt(String password, String encryptedData) throws Exception 
    { 
    byte[] secretKey = password.getBytes(); 
    SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey, CIPHER_ALGORITHM); 
    Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); 
    cipher.init(Cipher.DECRYPT_MODE, secretKeySpec); 

    byte[] encrypted = Base64.decode(encryptedData, Base64.DEFAULT); 
    byte[] decrypted = cipher.doFinal(encrypted); 

    return new String(decrypted); 
    } 
} 
+0

whaat我正在這裏做的是加密/解密字符串日期occording給定的密碼。 – 2013-04-21 10:18:31

+1

'我創建的兩個方法都給出相同的字符串。 '你是什麼意思 – stinepike 2013-04-21 10:20:53

+0

我的意思是兩種方法,即加密和解密接收兩個字符串一個是關鍵字符串,另一個是一些字符串數據。謝謝, – 2013-04-21 16:53:12

回答

0

你的代碼中有幾個錯誤,但它的工作並不遠。這裏有問題:

  1. 你應該通過RANDOM_GENERATOR_ALGORITHMSecretKeySpec構造函數,而不是CIPHER_ALGORITHM

  2. 您需要爲加密和解密指定一個IV。沒有指定IV,解密將不起作用,因爲加密將使用隨機IV,並且您的解密方法將不知道該值是什麼。

    cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, 
        new IvParameterSpec(/* 16 byte value */)); 
    
    cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, 
        new IvParameterSpec(/* same 16 byte value */)); 
    

    請注意,您將不得不將IV與密文一起存儲,因此它可以用於解密。這樣做的一種常見方法是將密文值與IV相加(注意:IV不是敏感值)。每次您加密時,您應該使用隨機IV值。

一些其他意見:

  1. 你的方法應該是static,因爲他們不使用任何實例字段。

  2. 您不應該使用密碼的原始字節作爲關鍵字。相反,你應該使用like PBKDF2來從密碼中得到一個密鑰。

如果您想查看一些正確執行此操作的代碼,請參閱JNCryptor。這是一個Android兼容的Java庫,可以執行基於密碼的加密和解密。特別是,檢查出的源代碼,看看:

+0

會回覆給你 – 2013-04-23 08:59:10