HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / Java Security / Java AES 256 Encryption Decryption Example

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.

private static String secretKey = "boooooooooom!!!!";
private static String salt = "ssshhhhhhhhhhh!!!!";

public static String encrypt(String strToEncrypt, String secret) 
{
    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(secretKey.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("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.

private static String secretKey = "boooooooooom!!!!";
private static String salt = "ssshhhhhhhhhhh!!!!";

public static String decrypt(String strToDecrypt, String secret) {
    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(secretKey.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 static void main(String[] args) 
{
    String originalString = "howtodoinjava.com";
    
    String encryptedString = AES.encrypt(originalString, secretKey) ;
    String decryptedString = AES.decrypt(encryptedString, secretKey) ;
     
    System.out.println(originalString);
    System.out.println(encryptedString);
    System.out.println(decryptedString);
}

Program output.

howtodoinjava.com
biXhp3Ha1fgxVEp48zHrvVoXMStmxPuAPHo3TVz5lHU=
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?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Ram

    May 7, 2020

    Hi Team,

    Thanks for the awesome tutorial.

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

    Thanks in advance,
    Ram

  2. Pooja

    February 6, 2020

    i got error in main method at secreteKey

    • Adi

      March 6, 2020

      Rename the secretKey of SecretKeySpec to something else. That should help.

  3. wiseowl4

    January 14, 2020

    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!

  4. amila

    January 6, 2020

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

    • Lokesh Gupta

      January 7, 2020

      Please see if this helps.

  5. Manju m

    December 27, 2019

    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

  6. Sudheshna

    November 8, 2019

    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.

    • Arul

      December 27, 2019

      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;

  7. Bram P

    October 3, 2019

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

    • Lokesh Gupta

      October 4, 2019

      Password is just an usecase. It can be anything.

  8. ppp

    June 26, 2019

    what i have to put in string salt=????????

  9. David H.

    May 17, 2019

    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”);

    • David H.

      May 17, 2019

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

  10. CEK

    April 11, 2019

    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,

  11. Jay Glasgow

    April 3, 2019

    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

  12. chandra

    March 19, 2019

    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

    • Lokesh Gupta

      March 20, 2019

      That’s weird. I know you may probably have already crosschecked it, but be sure you are not copying any extra whitespaces.

  13. mehdi

    March 16, 2019

    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”

  14. Antonio Carlos Stumpf Souto

    January 22, 2019

    The methods’ secret argument is never used,

  15. Ramveer

    October 24, 2018

    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 on this article!

Search Tutorials

Java Security Tutorial

  • Java – Generate Secure Hash
  • Java – Debug SSL Issues
  • Java – AES Algorithm
  • Java – AES 256
  • Java – REST Security Guide
  • Java – Bypass SSL Checking
  • Java – Set Env Variables without Admin Access

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces