2016-05-06 123 views
0

我一直在做填充加密的問題。我想我已經分離出的問題給這個函數:用於填充加密的密鑰長度不正確

static String AESEncryptStringWithPassword(String s, String p) throws...{ 
    //function to create key from string password 
    SecretKey secret = deriveAESKey(p); 
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 
    cipher.init(Cipher.ENCRYPT_MODE, secret); 
    AlgorithmParameters params = cipher.getParameters(); 
    iv = params.getParameterSpec(IvParameterSpec.class).getIV(); 
    byte[] ciphertext = cipher.doFinal(s.getBytes(Charset.forName("UTF-8"))); 
    String str = Base64.getEncoder().encodeToString(ciphertext); 
    return str; 

} 

向下行,當我去解密我會得到一個錯誤,像這樣:帶襯墊的加密解密時輸入長度必須是16的倍數。

我檢查了這個方法是壞長度字符串的來源。沒有更多的方法破壞它。我不確定我做錯了什麼。我在這裏的基礎上我的代碼在這裏的問題:Java 256-bit AES Password-Based Encryption

任何幫助將不勝感激。

編輯:我改變了編碼稍微使用字符串(字節[],字符集),而不是。然而,現在使用defaultcharset,我有一個合適的字符串長度,而用utf-8我沒有。

回答

1

整個程序中byte []和String之間的轉換似乎是問題所在。儘可能保持爲byte [],然後工作。

所以,經驗教訓:仔細轉換字節[]和字符串。