Search code examples
javaexceptionbouncycastle

Bouncy Castle DataLengthException not being caught


I am using bouncy castle to decrypt and trying to catch the DataLengthException that it throws. However, for some reason, the JVM does not recognize the Exception as a DataLengthException. Has anyone else had this problem?

Code:

for (int i = 0; i < transformations.length; i++) {
    try {
        cipher = Cipher.getInstance(transformations[i], "BC");
        cipher.init(Cipher.DECRYPT_MODE, certificate);
        return cipher.doFinal(bytesTimestampEncrypted);
    }
    catch (ArrayIndexOutOfBoundsException e1) {
        // try the next transformation
    }
    catch (BadPaddingException e1) {
        // try the next transformation
    }
    catch (IllegalBlockSizeException e1) {
        // try the next transformation
    }
    catch (NoSuchPaddingException e) {
        // try the next transformation
    }
    catch (NoSuchAlgorithmException e) {
        // try the next transformation
    }
    catch (InvalidKeyException e) {
        // try the next transformation
    }
    catch (NoSuchProviderException e) {
        // try the next transformation
    }
    catch (DataLengthException e) {  
        // This is the one I am trying to catch
        Log.debug("Input too large for RSA cipher, trans=" + transformations[i], e);
    }
    catch (RuntimeException e) {   
        // This is the one that actually ends up catching it.
        throw e;
    }
}

As you can see from the comments, the exception is not caught until the catch(RuntimeException) which I added simply for testing reasons. I have debugged the exception and set a break point on the RuntimeException. The exception is: org.bouncycastle.crypto.DataLengthException: input too large for RSA cipher however, when I test e instance of org.bouncastle.crypto.DataLengthException i get false.

Any ideas here would be very helpful.


Solution

  • If the same class file is loaded by two different classloaders it will never be considered the same class, because the class identity is made by the class loader AND the full class name.

    This is the only way I can see that an object of a class with the same full name would fail the instance of test. Check your workspace/runtime for multiple copies of bouncycastle jars.