我在嘗試解密某些加密文本時遇到了一些麻煩。 CheckpswdBasedKey總是返回false,因爲在c.doFInal 的BadPaddingException的我使用AES,basicaly加密:AES解密時的瘋狂例外 - BadPaddingException
public static String generatePswdBasedKey(String password){
String finalKey = null;
SecretKey sk = null;
KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, IT, KEY_LENGTH);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();
sk = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance(Cifrador.AES_MODE);//AES_MODE = AES/CBC/PKCS5Padding
IvParameterSpec ivParams = new IvParameterSpec(iv);//IV already initialized
cipher.init(Cipher.ENCRYPT_MODE, sk, ivParams);
byte pwdbytes[] = password.getBytes();//I also tried using Base64 to decode... without success
byte cc[] = cipher.doFinal(pwdbytes);
finalKey = Base64.encodeToString(cc, false); //.encodeToString(byte[] sArr, boolean lineSep)
return finalKey;
現在解密模式:
//This method compares a password received from keyboard with the decrypted password (decrypting output from generatePswdBasedKey(String password))
public static boolean checkPswdBasedKey(String password, String passwordInput){
byte bufferBytes[] = Base64.decode(password);
SecretKey sk = new SecretKeySpec(bufferBytes, 0, bufferBytes.length, "AES"); //Also tried new SecretKeySPec(bufferBytes, "AES");...
Cipher c = Cipher.getInstance(Cifrador.AES_MODE);//AES_MODE = AES/CBC/PKCS5Padding
IvParameterSpec ivParams = new IvParameterSpec(iv);//IV already initialized
c.init(Cipher.DECRYPT_MODE, sk, ivParams);
byte result[] = c.doFinal(bufferBytes);
String resultStr = Base64.encodeToString(result, false); //.encodeToString(byte[] sArr, boolean lineSep)
if(passwordInput.equalsIgnoreCase(resultStr)){
return true;
}
return false;
}
我比較了四字節@ checkPswdBasedKey和iv @generatePswdBasedKey,它們都是相同的。 secretkey @checkPswdBasedKey(我得到這些字節:sk.getEncoded())和secretkey @generatePswdBasedKey ......它們都是平等的。 所以基本上當我解密我知道我使用相同的密鑰,相同的IV和相同的消息...和適當的長度(16字節鍵,16字節味精,16字節iv,使用AES 128)任何想法?
有點題外話,但任何特別的理由不使用安全散列的口令? – 2013-04-28 14:59:26
將解密端設置爲無填充並查看您獲得的內容。各種各樣的錯誤都是可能的,並且知道明文的末尾可以消除其中的一些錯誤。 – rossum 2013-04-28 18:43:20
@rossum好吧,我做到了,thxü,現在沒有任何異常,但解密輸出doenst匹配passwordInput – Aero 2013-04-28 18:59:24