Quantcast

HELP: How come getOutputSize() returns 8 bytes more than what I need?

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

HELP: How come getOutputSize() returns 8 bytes more than what I need?

Vernon Chin
Hi all,
 
Using BC lightweight API to do 3DES with PaddedBufferedBlockCipher and ZeroBytePadding.
 
This is how I create the cipher:
 
BlockCipher engine = new DESedeEngine();
PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(engine, new ZeroBytePadding());
 
When I have plaintext input that is a multiple of the block size (8 bytes), I get 8 more bytes when I call getOutputSize(input).  For example, an input length of 8 gives me 16, 24 --> 32 etc.  If the input length is not a multiple of 8, it does what is expected (e.g. 7 byte length --> 8, 14 --> 16).
 
I am using 2 64-bit keys, and encrypting and decrypting works fine, except at the end I get 8 extra empty bytes after decrypting.
 
Why does getOutputSize() do this?  How come it doesn't think an 8/16/24 byte output buffer is big enough for 8/16/24 byte input?
 
Thanks in advance,
Vernon
 
 
==
private final static String ENCODE_METHOD = FrameworkConstants.ENCODING_64;
 
public static String encrypt(String encodedKey, String plainText)
{
    if (StringUtil.isEmpty(plainText))
    {
        return plainText;
    }
 
    String retVal = null;
 
    try
    {
        BlockCipher engine = new DESedeEngine();
        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(engine, new ZeroBytePadding());
 
        
        byte[] key = Base64.decodeBase64(encodedKey.getBytes(ENCODE_METHOD));
        byte[] input = plainText.getBytes();
 
        cipher.init(true, new KeyParameter(key));
 
        byte[] cipherText = new byte[cipher.getOutputSize(input.length)];
 
        int outputLen = cipher.processBytes(input, 0, input.length, cipherText, 0);
        cipher.doFinal(cipherText, outputLen);
 
        retVal = new String(Base64.encodeBase64(cipherText), ENCODE_METHOD);
    }
    catch (CryptoException ce)
    {
        log.error("Problem encrypting: " + ce);
    }
    catch (UnsupportedEncodingException uee)
    {
        log.error("bad encoding: " + uee);
    }
 
    return retVal;
}
 
 
___________________________
 
Vernon Chin
Developer, Professional Services
Infowave Software Inc.
 
Loading...