I am trying to encrypt and decrypt some simple text. But for some reason I am getting a strange error: javax.crypto.BadPaddingException
. Why would JCE generates byt
Cipher.update returns a byte[] as well. So you are missing part of the encrypted data when you go to decrypt. Update the last section to read as follows:
Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
c.init(Cipher.ENCRYPT_MODE, k, iv);
byte[] someData = c.update(textData);
byte[] moreData = c.doFinal();
System.out.println("E: " + (someData.length + moreData.length));
c = Cipher.getInstance("AES/CBC/PKCS5Padding");
c.init(Cipher.DECRYPT_MODE, k, iv);
byte[] someDecrypted = c.update(someData);
byte[] moreDecrypted = c.doFinal(moreData);
System.out.println("R: " + (someDecrypted.length + moreDecrypted.length));
You can forgo the calls to update
and just pass the byte[]
data directly to doFinal
performing the operation of encrypting or decrypting in one step.