replace JCE with Bouncycastle jar

别来无恙 提交于 2020-01-06 05:07:09

问题


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.


回答1:


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));
    }
}



回答2:


To encrypt using AES 256, you have to use the ‘Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files’. There are 2 jars, local_policy.jar and US_export_policy.jar.

You can get these files from oracle website.

Once you have these jars, replace the "your_java_installation_directory/jre/lib/security" jars with these.



来源:https://stackoverflow.com/questions/25208799/replace-jce-with-bouncycastle-jar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!