Wednesday, February 13, 2008

Avoiding DataLengthException in Bouncy Castle

This exception occurs usually when the output buffer is too small to accomodate the result of an encryption/decryption/has computation, etc. A (possible) way to avoid it is like this:

PaddedBufferedBlockCipher padBufBlockCipher = new PaddedBufferedBlockCipher(new AESEngine());
byte[] key = ......
KeyParameter keyParam = new KeyParameter(key);
padBufBlockCipher.init(true, keyParam);

String l_message = "Himanshu";
byte[] out = new byte[padBufBlockCipher.getOutputSize(l_message.getBytes().length)];

Now the output buffer will be set to a minimum size that can accomodate a block generated while encrypting a block of length l_message.getBytes().length

Another method for reference is BufferedBlockCipher.getUpdateOutputSize(). Refer javadoc for Bouncy Castle.

No comments: