Search code examples
javabouncycastlerijndael

How can I do for Rijndael-256 with BouncyCastle API?


An ancient PHP guy wrote encryption code for Rijndael-256 (!AES256) / ECB / NoPadding.

I tried this.

PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(
        new RijndaelEngine(256), new ZeroBytePadding());
cipher.init(encrypt, new KeyParameter(Arrays.copyOf(KEY.getBytes(UTF_8), 16)));
byte[] source = supplier.get();
byte[] target = new byte[cipher.getOutputSize(source.length)];
int offset = cipher.processBytes(source, 0, source.length, target, 0);
cipher.doFinal(target, offset);

But encryption always adds paddings. Yes I know I used ZeroBytePadding.

How can I solve this? I failed to find any good references.


Solution

  • If the encryption really didn't add padding, then just initialise the cipher as:

    new BufferedBlockCipher(new RijndaelEngine(256))
    

    Be aware that the doFinal call will throw a DataLengthException if the data you are trying to decrypt is not actually block-aligned.

    BTW, it's also a good habit to check the return value of doFinal (how many bytes were output), since getOutputSize is allowed to be an overestimate.