Search code examples
javaaesbouncycastle

Will Java Bouncy Castle Always Throw Exception when decrypt Plain text


I have a process in my system that will receive input either random plain texts or a ciphertexts. Since performance is not an issue, i'm planning to try decrypt all incoming input, with pseudo-code something like this:

//get the input, either a plain text, or cipher text 'in disguise'
//ex of plain text: "some text".getBytes()
byte[] plainText = getInput();
try {

    //try to decrypt whatever it is. Using Bouncy Castle as the AES crypto engine
    plainText = AESDecryptor.decrypt(HARDCODED_AES_KEY, plainText);
} catch(Exception ex) {
    ...
}

//do some process with the plain text
process(plainText);

I'm using AES for the encryption method.

The code above rely heavily on an assumption that trying to decrypt a plain text using bouncy castle will always throws exception. But is the assumption 100% correct? will it always throws exception when trying to decrypt plain, human readable text?

Thanks in advance!


Solution

  • Short answer

    No, you cannot guarantee an exception.

    Longer answer

    The probability of receiving an exception is dependent upon the padding scheme used. When a cryptographic library decrypts data using an algorithm that includes padding, it expects to find correctly padded plaintext. If the padding is malformed (e.g. because the input was plaintext, not ciphertext) an exception is likely to be thrown.

    If you are not using a padding scheme in your decryption and your input is a multiple of the block size of the cipher (in the case of AES - 16 bytes), then your library will happily decrypt plaintext and give you junk.


    As an example, consider PKCS #7 padding. This appends a non-zero number of bytes to the end of the plaintext, with a value that is equal to the number of padding bytes. Sufficient bytes are added to align the plaintext with the block size of the cipher. For example:

    12 34 56 78 9A BC DE F0 08 08 08 08 08 08 08 08
    

    Where the 08 values are eight bytes of padding to align with the AES block size. So, if you decrypt some plaintext is it likely to result in valid padding? Probably not. But it could and so it is a sloppy way to design your system.


    You need to add another layer to your proposed protocol to indicate whether the data is encrypted or not. It may also be useful at this point to specify the algorithm used, as this might give you more flexibility in the future to support additional algorithms.