Friday, April 13, 2012

Bouncy Castle Decryption - Illegal Key Size


Recently I was asked to implement a solution that decrypts a PGP encrypted ZIP file.  I had never worked with encryption/decryption in Java before, but the task seemed simple enough. I found Bouncy Castle, fished though the API, which us loaded with examples, and poof, I was ready to test.

This is where I ran into a problem.  I received an 'Illegal Key Size' error. I turned to Google and found an answer on StackOverflow 

It turns out that the decryption provider I was using, JCA, cannot handle secret keys greater than 128 bits. The solution is to download updated JAR files from oracle and add them to our JRE.  This isn't really the best solution since I would rather not touch my installation of Java.

At this point I turned back to the API to look for a better solution. This is where I found a better solution. The trick is to remove the dependency on JCA altogether by replacing the decryptor factory as below.
Replace:

InputStream clear = pbe.getDataStream(new JcePublicKeyDataDecryptorFactoryBuilder().setProvider(SECURITY_PROVIDER).build(sKey));

with:

InputStream clear = pbe.getDataStream(new BcPublicKeyDataDecryptorFactory(sKey));

Success. No need to tweek your Java installation.

References:
http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files.shtml
http://stackoverflow.com/questions/6481627/java-security-illegal-key-size-or-default-parameters