Java Cipher - AES Padding Problem
It should work exactly the same with AES, i.e. the padding mode has to be specified together with the cipher. Which padding modes are implemented depends on the provider and should be described in its documentation.
According to the JCE documentation: http://java.sun.com/j2se/1.5.0/docs/guide/security/jce/JCERefGuide.html#AppA standard padding modes like PKCS5Padding should be always supported (at least, that's how I interpret it).
Ciaran Archer
Ciarán Archer works for Zendesk. https://github.com/ciaranarcher
Updated on December 05, 2020Comments
-
Ciaran Archer over 3 years
I am using a AES cipher with a 16 byte block size.
If I try and encrypt a 16 byte string I have no problems, but any other length not a multiple of 16 is throwing an exception.
I know with 3-DES you can specify a padding type as part of the algorithm and it's handled with no extra work (e.g. DES/CBC/PKCS5Padding), but is there a way to specify this with AES?
Or do I need to pad the pytes manually to a multiple of 16, and then strip them when I decrypt? Here is an abbreviated code sample.
encrypt = Cipher.getInstance("AES", provider); encrypt.init(Cipher.ENCRYPT_MODE, key) ; byte[] encrypted = encrypt.doFinal(plainTxt.getBytes()) ;
Any and all replies appreciated!
Thanks in advance, Ciarán
-
Ciaran Archer over 15 yearsBoy am I familiar with that page :) When you say the provider, do you mean the implementation of the JCE I am using? I will check the docs for that.
-
Michael Borgwardt over 15 yearsYes, the provider (the second parameter in the getInstance() method) basically implements the Cipher interface. You can have more than one cryptography provider active. Sun's JDK comes with the SunJCE provider pre-installed
-
Ciaran Archer over 15 yearsSince I was coding a 'proof of concept' of the AES through Java/Coldfusion, I implemented my own padding using method 2 described here: di-mgt.com.au/cryptopad.html. I might take a closer look for the real thing. I'll mark this as the answer though.