Search code examples
javaencryptionbouncycastlegnupg

Bouncy castle GNUPG decryption


I have some misunderstanding when trying to decrypt file encrypted using GNUPG.

Trying to work with sample code which is available here:

https://github.com/chids/bouncy-castle-pgp

Made some additional tests and everything works fine.

But when trying to decrypt sample file which, I get:

Caused by: java.security.InvalidKeyException: Illegal key size
at javax.crypto.Cipher.checkCryptoPerm(Cipher.java:1024)
at javax.crypto.Cipher.init(Cipher.java:1345)
at javax.crypto.Cipher.init(Cipher.java:1282)
... 4 more

As I understood that I need to replace two jar files, which are located in jdk security folder, I did that but still this exception is present.

When checking Cipher.getMaxAllowedKeyLength() for all algorithms I get that mainly there are 128bit lengths. I assume that it is not correct, is that right? Maybe jar files need to be added somehow seperately on my IDE?

I see thta public key which is provided is RSA 2048 bits, so maybe all this implementation needs to be done in some another way?

Edit: Just noticed that key used in unit tests is also RSA 2048 bits, so it should not be the case.


Solution

  • By default, Java as downloaded from Oracle's website contains policy files which restrict the maximum key lengths you can use. Here's the relevant part of default_local.policy inside jre/lib/security/local_policy.jar:

    grant {
        permission javax.crypto.CryptoPermission "DES", 64;
        permission javax.crypto.CryptoPermission "DESede", *;
        permission javax.crypto.CryptoPermission "RC2", 128,
                                     "javax.crypto.spec.RC2ParameterSpec", 128;
        permission javax.crypto.CryptoPermission "RC4", 128;
        permission javax.crypto.CryptoPermission "RC5", 128,
              "javax.crypto.spec.RC5ParameterSpec", *, 12, *;
        permission javax.crypto.CryptoPermission "RSA", *;
        permission javax.crypto.CryptoPermission *, 128;
    };
    

    As you can see, for RSA the key length is not restricted at all, but the last line makes everything else max out at 128 bits. The local_policy.jar from the UnlimitedJCEPolicy.zip replaces this with:

    grant {
        // There is no restriction to any algorithms.
        permission javax.crypto.CryptoAllPermission;
    };
    

    removing the limits. Your Illegal key size exception indicates that either you have not replaced the files in the correct directory, or that your IDE is not using a JRE with the correct security policy files. You haven't told us which IDE you are using. If it's Eclipse, go to Window->Preferences->Java->Installed JREs... and look at the list of JREs. If the one where you replaced is not listed, click Add..., then select Standard VM, then set the JRE home to the directory wher your patched Java resides. After doing that, you should be able to run your tests with the patched Java.