AES Encryption Decryption

The Advanced Encryption Standard, or AES, is a symmetric block cipher chosen by the U.S. government to protect classified information and is implemented in software and hardware throughout the world to encrypt sensitive data.

In present day cryptography, AES is widely adopted and supported in both hardware and software. Till date, no practical cryptanalytic attacks against AES has been discovered. Additionally, AES has built-in flexibility of key length, which allows a degree of ‘future-proofing’ against progress in the ability to perform exhaustive key searches.

Encryption.java

import java.security.SecureRandom;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

public class Encryption {

    public static byte[] encrypt(byte[] data, String key, byte[] iv) throws Exception {
        SecretKey k = new SecretKeySpec(Util.revert(key), "AES");
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", new BouncyCastleProvider());
        cipher.init(Cipher.ENCRYPT_MODE, k, new IvParameterSpec(iv));
        return cipher.doFinal(data);
    }
    
    public static String generate(String content, String key) throws Exception {
        int ivSize = 16;
        byte[] iv = new byte[ivSize];
        SecureRandom random = new SecureRandom();
        random.nextBytes(iv);
        return (Util.toHex(iv)).concat("3a").concat(Util.toHex(encrypt((content).getBytes(), key, iv)));
    }
}

Decryption.java

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

public class Decryption {

    public static byte[] decrypt(byte[] data, String key, String iv) throws Exception {
        SecretKey k = new SecretKeySpec(Util.revert(key), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", new BouncyCastleProvider());
        cipher.init(Cipher.DECRYPT_MODE, k, new IvParameterSpec(Util.revert(iv)));
        
        return cipher.doFinal(data);
    }

    public static String decrypt(String content, String key, String iv) throws Exception {
        return new String(decrypt(Util.revert(content), key, iv));
    }

    public static String decryptingMeroResponse(String encryptedData, String keyStr) {

        StringBuffer encData = (new StringBuffer(encryptedData));
        System.out.println("encdata =" + encData);
        String ivData = encData.substring(0, 32);
        String d = (encData.replace(0, 34, "")).toString();
        try {
            return decrypt(d.trim(), keyStr, ivData);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }
}