Link to home
Start Free TrialLog in
Avatar of Ryan McCauley
Ryan McCauleyFlag for United States of America

asked on

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.
ASKER CERTIFIED SOLUTION
Avatar of chapmanjw
chapmanjw
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Ryan McCauley

ASKER

Outstanding - that did the trick. I would never have expected their default implementations to be different, but that definitely solved the problem.