AES encrypts / decrypts with the Bouncy Castle provider

Here is my implementation of AES 256 encryption and decryption, developed using the native JDK 5 library:

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 searched a lot, tested a lot, with no results ... can someone help me?

thank

+5
source share
1 answer

You would either use

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

or more

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

However, it Cipher.getInstance("AES")uses the Electronic Code Book , which is unsafe. You either want to use Cipher Block Chaining ( Cipher.getInstance("AES/CBC/PKCS5Padding")) or Counter ( Cipher.getInstance("AES/CTR/NoPadding")); they are both safe, the main difference is that CBC requires indentation, while CTR does not.

+19

All Articles