Java AES-256 Encryption and Decryption

Learn to use Java AES-256 bit encryption to create secure passwords and decryption for password validation. To read simple AES encryption, read the linked post.

1. AES – Advanced Encryption Standard

AES is a symmetric encryption algorithm. It was intended to be easy to implement in hardware and software, as well as in restricted environments and offer good defenses against various attack techniques.

AES is block cipher capable of handling 128 bit blocks, using keys sized at 128, 192, and 256 bits. Each cipher encrypts and decrypts data in blocks of 128 bits using cryptographic keys of 128-, 192- and 256-bits, respectively.

It uses the same key for encryption and decryption processes, so the sender and the receiver, both must know — and use — the same secret key.

In given encryption and decryption example, I have used base64 encoding in UTF-8 charset. It is done for displaying the output of program.

In your application, you can store and validate the data in byte array format as well.

2. AES-256 Encryption

Java program to encrypt a password (or any information) using AES 256 bits.

import javax.crypto.Cipher;
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.nio.charset.StandardCharsets;
import java.security.spec.KeySpec;
import java.util.Base64;
 
public class AES256 {
  private static final String SECRET_KEY = "my_super_secret_key";
  private static final String SALT = "ssshhhhhhhhhhh!!!!";
 
  public static String encrypt(String strToEncrypt) {
    try {
      byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
      IvParameterSpec ivspec = new IvParameterSpec(iv);
 
      SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
      KeySpec spec = new PBEKeySpec(SECRET_KEY.toCharArray(), SALT.getBytes(), 65536, 256);
      SecretKey tmp = factory.generateSecret(spec);
      SecretKeySpec secretKey = new SecretKeySpec(tmp.getEncoded(), "AES");
 
      Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
      cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivspec);
      return Base64.getEncoder()
          .encodeToString(cipher.doFinal(strToEncrypt.getBytes(StandardCharsets.UTF_8)));
    } catch (Exception e) {
      System.out.println("Error while encrypting: " + e.toString());
    }
    return null;
  }
}

Do not forget to use the same secret key and salt in encryption and decryption.

3. AES 256 Decryption

Java program to decrypt a password (or any information) using AES 256 bits.

import javax.crypto.Cipher;
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.nio.charset.StandardCharsets;
import java.security.spec.KeySpec;
import java.util.Base64;
 
public class AES256 {
  private static final String SECRET_KEY = "my_super_secret_key";
  private static final String SALT = "ssshhhhhhhhhhh!!!!";
 
  public static String decrypt(String strToDecrypt) {
    try {
      byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
      IvParameterSpec ivspec = new IvParameterSpec(iv);
 
      SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
      KeySpec spec = new PBEKeySpec(SECRET_KEY.toCharArray(), SALT.getBytes(), 65536, 256);
      SecretKey tmp = factory.generateSecret(spec);
      SecretKeySpec secretKey = new SecretKeySpec(tmp.getEncoded(), "AES");
 
      Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
      cipher.init(Cipher.DECRYPT_MODE, secretKey, ivspec);
      return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
    } catch (Exception e) {
      System.out.println("Error while decrypting: " + e.toString());
    }
    return null;
  }
}

4. Demo

Let’s test our AES256 encryption and decryption methods with a simple string.

public class AES256Example {
  public static void main(String[] args) {
    String originalString = "howtodoinjava.com";
 
    String encryptedString = AES256.encrypt(originalString);
    String decryptedString = AES256.decrypt(encryptedString);
 
    System.out.println(originalString);
    System.out.println(encryptedString);
    System.out.println(decryptedString);
  }
}

Program output.

howtodoinjava.com
BfNFPRgfKF8Ke9kpoNAagmcI4/Hya5o/rq9/fq97ZiA=
howtodoinjava.com

Clearly, we are able to use AES256 encryption to encrypt a string, and decryption to get back the original string from the encrypted string.

Happy Learning !!

Download Sourcecode

Leave a Reply

21 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.