如果我使用錯誤的鍵或錯誤的鹽進行解密BadPaddingException被拋出。 我期望一個不正確的字符串被返回。 的doFinal()導致異常的解密法AES BadPaddingException
消息:This is just an example
Unfug:'ΩÙΩ„SåF?V®ßs.k˚·ºç€èÀHfif∫ÙÉÕ
Exception in thread "main" javax.crypto.BadPaddingException: Given final block not properly padded
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.AESCipher.engineDoFinal(DashoA13*..)
at javax.crypto.Cipher.doFinal(DashoA13*..)
at casino.AES.decryptString(AES.java:130)
at casino.AES.main(AES.java:172)
public static void main(String[] args) throws Exception {
//Encryption
AES encr = new AES();
encr.setKey("KEY");
encr.setSalt("SALT");
encr.setup();
String message = "This is just an example";
System.out.println("Message : " + message);
byte[] code = encr.encrypt(message);
System.out.println("Encrypted Strinng : "+ new String(code, "UTF-8"));
//Decryption
AES dec = new AES();
dec.setKey("INCORRECT"); //<--- incorrect
dec.setSalt("SALT");
dec.setup();
System.out.println(dec.decryptString(code));
}
public synchronized void setKey(String key) throws UnsupportedEncodingException {
this.key = key.getBytes("UTF-8");
isPasswordAlreadySet = true;
}
public synchronized void setSalt(String salt) throws UnsupportedEncodingException {
this.salt = salt.getBytes("UTF-8");
}
public synchronized void setup() throws Exception {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.update(key);
digest.update(salt);
byte[] raw = digest.digest();
skeySpec = new SecretKeySpec(raw, "AES");
cipher = Cipher.getInstance("AES");
}
public synchronized byte[] encrypt(byte[] klartext) throws Exception {
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(klartext);
return encrypted;
}
public synchronized byte[] encrypt(String klartext) throws Exception{
return encrypt(klartext.getBytes("UTF-8"));
}
public synchronized byte[] decrypt(byte[] code) throws Exception {
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] original = cipher.doFinal(code);
return original;
}
public synchronized double decryptDouble(byte[] code) throws Exception {
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] original = cipher.doFinal(code);
return doubleFromBytes(original);
}
謝謝! 弗雷德裏克
我已經改變了密碼的initline在一個提供者無關的方式的密鑰:密碼= Cipher.getInstance( 「AES/CBC/PKCS5Padding」); 但是拋出同樣的異常。 爲了獲得正確的長度,我使用了SHA-Hash - 我認爲這應該足夠了。 此外,我第一次使用setup()方法時不會引發異常 – Frederik 2011-04-08 15:28:21
@Frederik:您必須瞭解填充的工作方式:填充模式將在加密之前將一些填充內容附加到純文本數據。解密後,該填充再次被剝離。但要知道有多少個字節需要去除,填充的內容很重要,如果我們使用錯誤的密鑰解密,最後一些字節不是將被填充算法添加的格式之一。如上所述,使用'NoPadding',但是您必須確保您的數據長度是塊長度的倍數。 – 2011-04-08 15:49:48
對於'PKCS5Padding',它與DES CBC的[RFC 1423](http://tools.ietf.org/html/rfc1423#section-1.1)中描述的相同。 – 2011-04-08 15:57:51