Java AES 256 Encryption Decryption Example

Learn to use Java AES 256 bit encryption to create secure passwords, and decryption for password validation. To read simple AES encryption, read 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 encrypting and decrypting, so the sender and the receiver must both know — and use — the same secret key.

In below encryption and decryption example, I have used base64 encoding in UTF-8 charset. It is done for displaying the output of program. If 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_ho_ho_ho";
  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 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_ho_ho_ho";
  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. Java AES 256 Example

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 original string from encrypted string.

Happy Learning !!

Read More:

What is AES?

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

21 thoughts on “Java AES 256 Encryption Decryption Example”

  1. Hi Team,

    Thanks for the awesome tutorial.

    Do you have an alternative of the same encryptions methods in swift?

    Thanks in advance,
    Ram

  2. Thanks for the contribution, but you should warn readers about the use of hardcoded salt and IV. I know some people that used your exemple “as is” in a project, hardcoding a fixed salt and a fixed IV for all their encryptions and decryptions!

  3. Error while encrypting: java.security.NoSuchAlgorithmException: PBKDF2WithHmacSHA256 SecretKeyFactory not available

  4. AES 256 encrypt and decrypt method is take too much of time during retrieve multiple rows query , how quickly decrypt multiple rows retrieve using java

  5. You didn’t mention the import statements in the code sample. I am getting conflicts for that when i am trying to use this.Can u provide the import statements too so that we can use that code with out conflicts as it is having some conflicts in importing the some other packages.

    • import java.security.spec.KeySpec;
      import java.util.Base64;

      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;

  6. Did you just list “secure passwords” as an example for encryption and decryption? Did you consider using hashing instead of encryption for that?

  7. How are people using this code example? You attempt to use secretKey to init spec, before secretKey is even defined. I tried rearranging the order of declarations, but they all depend on something else in a way such that it is impossible to use as written. If I declare secretKey before the KeySpec declaration – that won’t work because secretKey declaration requires tmp which needs spec and spec can’t be defined until secret key exists.

    Quoted code snippet (from encrypt):

    SecretKeyFactory factory = SecretKeyFactory.getInstance(“PBKDF2WithHmacSHA256”);
    KeySpec spec = new PBEKeySpec(secretKey.toCharArray(), salt.getBytes(), 65536, 256);
    SecretKey tmp = factory.generateSecret(spec);
    SecretKeySpec secretKey = new SecretKeySpec(tmp.getEncoded(), “AES”);

    • Nevermind I got it. The variable names overlap, but the toCharArray() is in reference to the string value.

  8. Hi Lokesh,

    I want to use your encryption and decryption methods. But I m getting this error ;
    “java.security.NoSuchAlgorithmException: PBKDF2WithHmacSHA256 SecretKeyFactory not available”.
    I cant solve this problem.
    I use Java 1.6 version.
    How can I fix it.

    Thank you,

  9. In your code for 2. AES 256 Encryption, you have this line…

    public static String encrypt(String strToEncrypt, String secret)

    As Antonio Carlos Stumpf Souto pointed out previously, you never use “String secret” anywhere in the method. Is it that “secret” should have been “secretKey”) or did you leave out a line in the method?

    Thanks,

    =Jay

  10. hi Lokesh,

    I have used your example to do AES encrypt/decrypt. Here is problem, if i run it standalone it works, however when i copy the encrypted string to a properties file and read it in groovy/grails webapplication ( which uses your code to decrypt), i am getting error like :
    I am getting java.lang.IllegalArgumentException: Illegal base64 character 5c.

    so i changed the decode code to the following :
    return new String(cipher.doFinal(Base64.getMimeDecoder().decode(strToDecrypt)));

    Now its giving me a different error :
    Error while decrypting: java.lang.IllegalArgumentException: Last unit does not have enough valid bits

    btw the input string i have which is encrypted by your example is of length 15 characters.
    and the encrypted string is of length 24 characters
    this is the encrypted string :
    vHsfqebYndXnWc78jk/qsQ==

    I have been trying to make this work for the last two days with little success, as always in a time crunch, any help is truly appreciated.

    Thanks
    Chandra

  11. AES uses the same secret key is used for the both encryption and decryption. Unlike AES 128 bit encryption and decryption, if we need a stronger AES 256 bit key, we need to have Java cryptography extension (JCE) unlimited strength jurisdiction policy files.

    If we have not installed the JCE we will be getting the error like “java.security.InvalidKeyException: Illegal key size” or “org.apache.xml.security.encryption.XMLEncryptionException: Illegal key size or default parameters”

  12. If i pass key as 256 bit(string length as 32) the algorithm gives the error as invalid key , Is this implementation for 256bit key or just 128 bit key( string length 16 )?

Comments are closed.

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.