Java AES 256 Encryption and Decryption

Tags: Crypto AES AES-256 AESUtils

In this Java tutorial, we learn how to implement a Java utility class which use AES (Advanced Encryption Standard) with 256 bits key length to encrypt and decrypt String data in Java programming language.

How to implement AES-256 encryption and descryption in Java

At this first step, we create a new Java class named AESUtils.

In this new class, implement public utility methods which using the Java Cryptography Architecture (JCA) API to encrypt and decrypt data. With this implementation we use the AES/CBC/PKCS5Padding algorithm and 256 bit key length which is highly recommend for AES.

  • The encrypt(String dataToEncrypt, String password, String salt) static method to encrypt a given String into encrypted byte array with given password and salt, and then use the Base64 encoder to make a String presentation of encrypted bytes.
  • The decrypt(String dataToDecrypt, String password, String salt) static method to decrypted a String in Base64 format of encrypted bytes to a clear text String with given password and salt.

AESUtils.java

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.util.Base64;

public class AESUtils {

    private static String ALGORITHM = "AES/CBC/PKCS5Padding";

    private static int KEY_LENGTH = 256;

    private static byte[] DEFAULT_IV = {0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1};

    /**
     * To encrypt String data with encryption password and salt
     * @param dataToEncrypt
     * @param password
     * @param salt
     * @return
     */
    public static String encrypt(String dataToEncrypt, String password, String salt) {
        try {
            SecretKey key = makeKey(password, salt);
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            IvParameterSpec ivParameterSpec = new IvParameterSpec(DEFAULT_IV);
            cipher.init(Cipher.ENCRYPT_MODE, key, ivParameterSpec);
            byte[] encryptedData = cipher.doFinal(dataToEncrypt.getBytes());
            String encryptedText = Base64.getEncoder().encodeToString(encryptedData);
            return encryptedText;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * To decrypt String data with decryption password and salt
     * @param dataToDecrypt
     * @param password
     * @param salt
     * @return
     */
    public static String decrypt(String dataToDecrypt, String password, String salt) {
        try {
            SecretKey key = makeKey(password, salt);
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            IvParameterSpec ivParameterSpec = new IvParameterSpec(DEFAULT_IV);
            cipher.init(Cipher.DECRYPT_MODE, key, ivParameterSpec);
            byte[] decryptedData = cipher.doFinal(Base64.getDecoder().decode(dataToDecrypt));
            String decryptedText = new String(decryptedData);
            return decryptedText;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        }

        return null;
    }

    private static SecretKey makeKey(String password, String salt) throws NoSuchAlgorithmException, InvalidKeySpecException {
        SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
        KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt.getBytes(), 65536, KEY_LENGTH);
        SecretKey secretKey = new SecretKeySpec(secretKeyFactory.generateSecret(keySpec).getEncoded(), "AES");
        return secretKey;
    }

}

In the the following example Java code, we learn how to use the above AESUtils class to encrypt and descrypt String data in Java program.

AESUtilsExample.java

public class AESUtilsExample {
    public static void main(String... args) {
        String clearTextToEncrypt = "Simple Solution";

        String encryptionPassword = "123@321aBC";
        String salt = "salt1";

        // Java AES 256 Encryption
        String encryptedText = AESUtils.encrypt(clearTextToEncrypt, encryptionPassword, salt);

        // Java AES 256 Decryption
        String decryptedText = AESUtils.decrypt(encryptedText, encryptionPassword, salt);

        System.out.println("Clear text to encrypt: " + clearTextToEncrypt);
        System.out.println("Encrypted text: " + encryptedText);
        System.out.println("Decrypted text: " + decryptedText);
    }
}
The output as below.
Clear text to encrypt: Simple Solution
Encrypted text: E5sUXq2urZ43oztyrbH2LQ==
Decrypted text: Simple Solution

Happy Coding 😊

Java AES Advanced Encryption Standard Encryption and Decryption

Java MD5 Hashing String

Java SHA-1 Hashing String