Title: Getting BadPaddingException when decrypting with AES algorithm
Tags: java;encryption;cryptography;aes
Question: I am getting following error when decrypting with AES algorithm. I dont understand where I am going wrong. Few days back this code was working fine for me, but not its throwing such error.
Error that I am getting:-
java.io.IOException: javax.crypto.BadPaddingException: Given final block not properly eric25@example.net(CipherInputStream.java:121)
at javax.crypto.CipherInputStream.read(CipherInputStream.java:239)
at javax.crypto.CipherInputStream.read(CipherInputStream.java:215)
at userInterface.Decryption.decryption(Decryption.java:61)
at userInterface.DecodingTab$DecodeButtonActionListener.actionPerformed(DecodingTab.java:295)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at  ... 40 more
Encryption code :-
public Encryption(String key2, FileInputStream fileInputStream,
FileOutputStream fileOutputStream) {
this.key = key2;
this.is = fileInputStream;
this.os = fileOutputStream;
public boolean encryption() throws Throwable {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(key.getBytes());
SecretKeySpec key = new SecretKeySpec(md5.digest(), "AES");
cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, key);
cipherInputStream = new CipherInputStream(is, cipher);
byte[] bytes = new byte[64];
int numBytes;
while ((numBytes = cipherInputStream.read(bytes)) != -1) {
os.write(bytes, 0, numBytes);
os.flush();
os.close();
is.close();
cipherInputStream.close();
return true;
**Decryption Code :- **
public Decryption(String decodingKey, File fileOutput) {
this.key = decodingKey;
this.outputFile = fileOutput.getAbsolutePath();
public boolean decryption() throws IOException, Throwable {
encryptedFile = new File("Crypto\\EncryptedFile.txt");
is = new FileInputStream(encryptedFile);
File outputF = new File(outputFile);
os = new FileOutputStream(outputF);
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(key.getBytes());
SecretKeySpec key = new SecretKeySpec(md5.digest(), "AES");
cipher = Cipher.getInstance("AES");
//cipher = Cipher.getInstance("AES/CBC/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, key);
cipherInputStream = new CipherInputStream(is, cipher);
byte[] bytes = new byte[64];
int numBytes;
while ((numBytes = cipherInputStream.read(bytes)) != -1) {
os.write(bytes, 0, numBytes);
os.flush();
os.close();
cipherInputStream.close();
is.close();
encryptedFile.delete();
return true;
Please let me know where I am going wrong.
Comment: Ciphertext is not text and should not be saved in a file named `.txt`. Where exactly are you closing `os` here?

Comment: Besides the platform encoding issues, `String#getBytes` and `new String(byte[])` may lose data if characters cannot be encoded / decoded. They don't throw exceptions if any data is left out or replaced. That MD5 is performed afterwards doesn't make a difference to that; check if the key values are identical (in bytes) during encryption & decryption by e.g. printing out base64 or hex. Note that above code doesn't keep to best practices (MD5, NoPadding etc.).

Comment: question edited for the same, by adding stream closing code.

Comment: Your code is not portable, so if you're running the encryption and decryption and decryption pieces on different platforms that could be your problem. To make the code portable, eliminate the reliance on platform defaults. In your code, I see that in two areas. First, don't use `String.getBytes()`. Instead, use `String.getBytes(StandardCharsets.UTF-8)`. Second, don't use `Cipher.getInstance("AES")`. Always specify the full "Algorithm/Mode/Padding" string.


Here is another answer: You should use a CipherOutputStream in the encryption part, and make sure you call close on it so the final padding data is written.
Comment for this answer: Why? I see no reason to avoid using the `CipherInputStream` he currently has. Also, he appears to properly close his streams.

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 4, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2017:00:03/19/17', 'FavoriteCount': 2.0, 'PostTypeId': 1, 'Tags': '<java><encryption><cryptography><aes>', 'Title': 'Getting BadPaddingException when decrypting with AES algorithm', 'ViewCount': 607, 'id': 42884397, 'user_AboutMe': None, 'user_AccountId': 3216058.0, 'user_DisplayName': 'Yogesh Jadhav', 'user_Reputation': 107.0, 'user_Views': 57.0, 'user_id': 2714724.0}}