• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2818
  • Last Modified:

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

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.
Ryan McCauley
Ryan McCauley
1 Solution
Java’s default RSA implementation is "RSA/None/PKCS1Padding", whereas BC’s is “RSA/None/NoPadding”. Try changing BC’s version of the Cipher.getInstance line to:

RSADecrypter = Cipher.getInstance("RSA/None/PKCS1Padding", "BC");
Ryan McCauleyData and Analytics ManagerAuthor Commented:
Outstanding - that did the trick. I would never have expected their default implementations to be different, but that definitely solved the problem.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now