We help IT Professionals succeed at work.

Check out our new AWS podcast with Certified Expert, Phil Phillips! Listen to "How to Execute a Seamless AWS Migration" on EE or on your favorite podcast platform. Listen Now


Decrypting RSA with BouncyCastle gives different result than Java RSA with same key - what am I missing?

Ryan McCauley
Medium Priority
Last Modified: 2012-05-11
When I target Java 1.5 or 1.6, I can decrypt an RSA value with the key I have, so I know everything works. When I target Java 1.4.2 (I know…), RSA decryption is unavailable, so I resorted to BouncyCastle. The RSA decryption appears to succeed (no exception), but the value it comes up with is completely different than what Java’s Cipher gets – my encrypted byte array is 128 bytes long, and while the properly decrypted value is just 32 bytes (and Java’s RSA returns it), BouncyCastle’s RSA gives me back 128 bytes of gibberish. Here’s the code I’m working with:

Boolean UseBouncyCastle = Boolean.TRUE;
Cipher RSADecrypter;
// Choose between Java and BouncyCastle
if (UseBouncyCastle == Boolean.TRUE)
    Security.addProvider(new BouncyCastleProvider());
    RSADecrypter = Cipher.getInstance("RSA", "BC");    
} else
    RSADecrypter = Cipher.getInstance("RSA");
//Initialize the Cipher using our the first key in the keystore – works fine for both
RSADecrypter.init(Cipher.DECRYPT_MODE, keystore.getKey("1", PrivateKeyPassword.toCharArray()));

//Decrypt first 128 bytes of the array – Java RSA gives 32 byte result, BouncyCastle gives 128 bytes of randomness
aegEncryptionKey = RSADecrypter.doFinal(binaryDataEncrypted,0,128);

Open in new window

Clearly I’m missing something obvious here, but all I’m changing is the Boolean value at the top, which switches between Java-based decryption and BC-based. Also, I can only test this on Java 1.5, since 1.4.2 doesn’t support RSA decryption, but the result is the same in both cases.

Thanks for any help you’re able to provide.
Watch Question

Unlock this solution with a free trial preview.
(No credit card required)
Get Preview
Ryan McCauleySenior Data Architect


Outstanding - that did the trick. I would never have expected their default implementations to be different, but that definitely solved the problem.
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a free trial preview!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.


Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.