Search code examples
javaencryptioncryptographyaesbouncycastle

replace JCE with Bouncycastle jar


I have to get rid of JCE jars and should be replaced with bouncy castle jar for AES encryption and decryption.

I am getting invalid key size exception when i replace JCE policy jars with BC jars for AES 256 algorithm. But it works well with key size 128.

How can i make use of BC jars in case of AES 256 algorithm.

Thanks.


Solution

  • This answer assumes that it is not possible to install the unlimited strength jurisdictional cryptography files using the scripting mentioned.


    The key size restraint of Cipher is in the Cipher class itself. It is not (easily) possible to bypass it.

    Instead you could use the Bouncy Castle lightweight API. The lightweight API is lightweight for the amount of classes are required for the API implementation itself, not so much for you though.

    For example (AES CBC with PKCS#7 (PKCS#5 compatible) padding:

    public class BouncyLightWeightCipherExample {
    
        private static final boolean FOR_DECRYPTION = false;
    
        public static void main(String[] args) throws NoSuchAlgorithmException, Exception {
            final byte[] keyData = new byte[256 / Byte.SIZE];
            final byte[] ivData = new byte[16];
            final byte[] testData = "owlstead".getBytes(UTF_8);
    
            // JCE creation
            final Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
    
            // initialization
            c.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyData, "AES"), new IvParameterSpec(ivData));
    
            // and encryption
            final byte[] ciphertext = c.doFinal(testData);
    
            // Bouncy Castle creation
            final BlockCipher blockCipher = new AESFastEngine();
            final CBCBlockCipher withModeOfOperation = new CBCBlockCipher(blockCipher);
            final PaddedBufferedBlockCipher withPadding = new PaddedBufferedBlockCipher(withModeOfOperation);
    
            // initialization
            final ParametersWithIV keyAndIV = new ParametersWithIV(new KeyParameter(keyData), ivData);
            withPadding.init(FOR_DECRYPTION, keyAndIV);
    
            // and decryption
            int plaintextSize = withPadding.processBytes(ciphertext, 0, ciphertext.length, ciphertext, 0);
            plaintextSize += withPadding.doFinal(ciphertext, plaintextSize);
            final byte[] plaintext = Arrays.copyOf(ciphertext, plaintextSize);
    
            // there we are
            System.out.println(new String(plaintext, UTF_8));
        }
    }