用Bouncycastle jar替换JCE [英] replace JCE with Bouncycastle jar

查看:396
本文介绍了用Bouncycastle jar替换JCE的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须摆脱JCE jar,应该替换为弹性城堡jar AES加密和解密。

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

我更换无效的键大小异常,当我更换JCE策略jar与BC jar为AES 256算法。但它适用于键大小128.

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.

如果是AES 256算法,我如何使用BC jar。

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

感谢。

推荐答案

Cipher 是在 Cipher 类本身。

而是可以使用Bouncy Castle轻量级API。

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.

例如(AES CBC with PKCS#7( PKCS#5 compatible)padding:

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

这篇关于用Bouncycastle jar替换JCE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆