AES padding issue
I searched this forum and couldn't find anything that explained my exact situation so here it is....
I am trying to decrypt some data and I end up with 0 bytes padded at the end. Any idea what I am doing wrong? Here is my decrypt() method:
protectedfinalbyte[] decrypt(finalbyte[] key,finalbyte[] value )
throws Exception{
SecretKeySpec skeySpec =new SecretKeySpec( key,"AES" );
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding" );
cipher.init( Cipher.DECRYPT_MODE, skeySpec );
byte[] buffer =newbyte[cipher.getOutputSize( value.length )];
int size = cipher.update( value, 0, value.length, buffer, 0 );
size += cipher.doFinal( buffer, size );
byte[] trimmed =newbyte[size];
System.arraycopy( buffer, 0, trimmed, 0, size );
return trimmed;
}
# 3
> Well, if I understand things correctly, update() and
> doFinal() return the number of bytes they stored
> which could be less than the size of the output
> buffer. That is why I am trimming the result.
Yes, that is correct.
> But,
> my issue is the number of bytes output is always the
> size of the output buffer and the output buffer is
> padded at the end with 0 bytes chars even though I
> specified "NoPadding".
If you specify NoPadding then
cipher.getOutputSize( value.length )
will be able to calculate the exact length of the result since without padding ALL bytes are to be returned.
If you had specified a padding then
cipher.getOutputSize( value.length )
would have to return an upper bound because the actual length of output will depend on how many padding bytes have been added and this will only be known after decryption.
# 6
> OK, so if I want to get rid of the 0 bytes, do I just
> remove them myself
Yes!
> or is there a way to figure out
> how much was padded from the cipher after I do the
> decryption (then I could just remove that many bytes)?
If the padding mode is one known the the JCE provider then the padding will be removed automatically as long as you specify the padding mode when you create the Cipher. I'm pretty sure that the use of zeros for padding is not one of the standard padding modes (it is not unambiguous) so I suspect that you will have to remove the padding yourself.
The question I have to ask is why are you padding with zeros rather than using something like PKCS5?