Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2493
  • 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.
0
Ryan McCauley
Asked:
Ryan McCauley
1 Solution
 
chapmanjwCommented:
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");
0
 
Ryan McCauleyAuthor Commented:
Outstanding - that did the trick. I would never have expected their default implementations to be different, but that definitely solved the problem.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

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