我正在使用下面的方法,如果我輸入正確的關鍵所有工作正常。 但是,如果我輸入一個錯誤的鍵我收到BadPaddingException:墊塊損壞... 我做錯了什麼?Android aes加密墊塊損壞
public void initKey(String passwd, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException{
byte[] localsalt = salt;
PBEKeySpec password = new PBEKeySpec(passwd.toCharArray(),localsalt, 1024,128);//, localsalt, 1000, 128); //128bit enc aes
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBEWithMD5And128BitAES-CBC-OpenSSL","BC");
PBEKey key = (PBEKey) factory.generateSecret(password);
encKey = new SecretKeySpec(key.getEncoded(), "AES");
}
public String txt2enc(String etxt) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
final Cipher cipher = Cipher.getInstance("AES");//AES
cipher.init(Cipher.ENCRYPT_MODE, encKey);
byte[] encrypted = cipher.doFinal((etxt).getBytes("UTF-8"));
return Base64.encodeToString(encrypted, 0);
}
//decryption
public String txt2dec(String dtxt) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException{
final Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, encKey);
byte[] decrypt = cipher.doFinal(Base64.decode(dtxt, 0));
return new String(decrypt);//return Base64.encodeToString(decrypt, 0);
}
當我嘗試解密以Base64格式存儲的passwd時,出現BadPaddingException .. passwd是用戶(現在我插入它)插入的passwd。所以您認爲沒關係當我輸入錯誤的密鑰?(當我說錯了我的意思是我試圖解密一個不同於加密密鑰的字符串) – Stelios 2011-04-12 14:24:20
如果它來自Base64.decode,則dtxt不是有效的Base64編碼的字符串。由於無效的字符串不是有效的密碼,我只是趕上例外並視爲失敗。如果dtxt是在應用程序內部生成的,我會研究爲什麼它有一個無效的編碼。 – 2011-04-12 15:13:24