AES encrypt/decrypt with Bouncy Castle provider [duplicate]

ⅰ亾dé卋堺 提交于 2019-12-03 03:58:32

问题


Here is my implementation of a AES 256 encrypt and decrypt, developed with the native library of JDK 5:

public static String encrypt(String key, String toEncrypt) throws Exception {
    Key skeySpec = generateKeySpec(key);
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    byte[] encrypted = cipher.doFinal(toEncrypt.getBytes());
    byte[] encryptedValue = Base64.encodeBase64(encrypted);
    return new String(encryptedValue);
}

public static String decrypt(String key, String encrypted) throws Exception {
    Key skeySpec = generateKeySpec(key);
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, skeySpec);
    byte[] decodedBytes = Base64.decodeBase64(encrypted.getBytes());
    byte[] original = cipher.doFinal(decodedBytes);
    return new String(original);
}

I want to implement the same methods with the Boucy Castle API (Java): I've searched a lot, tested a lot, without results ... can someone help me?

Thanks


回答1:


You would either use

Security.addProvider(new BouncyCastleProvider());
Cipher cipher = Cipher.getInstance("AES", "BC");

or else

Cipher cipher = Cipher.getInstance("AES", new BouncyCastleProvider());

That said, Cipher.getInstance("AES") uses Electronic Codebook, which is insecure. You either want Cipher Block Chaining (Cipher.getInstance("AES/CBC/PKCS5Padding")) or Counter (Cipher.getInstance("AES/CTR/NoPadding")) modes; they are both secure, the primary difference being that CBC requires padding while CTR does not.



来源:https://stackoverflow.com/questions/15925029/aes-encrypt-decrypt-with-bouncy-castle-provider

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