HowToDoInJava

  • Java 8
  • Regex
  • Concurrency
  • Best Practices
  • Spring Boot
  • JUnit5
  • Interview Questions
  • Dark Mode

Java AES 256 Encryption Decryption Example

By Lokesh Gupta | Filed Under: Java Security

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?

TwitterFacebookLinkedinRedditPocket

About Lokesh Gupta

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

13
Leave a Reply

This comment form is under antispam protection
10 Comment threads
3 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
11 Comment authors
This comment form is under antispam protection
  Subscribe  
newest oldest most voted
Notify of
Sudheshna

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.

Vote Up0Vote Down  Reply
1 month ago
Bram P

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

Vote Up0Vote Down  Reply
2 months ago
Lokesh Gupta

Password is just an usecase. It can be anything.

Vote Up0Vote Down  Reply
2 months ago
ppp

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

Vote Up0Vote Down  Reply
5 months ago
David H.

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

Vote Up0Vote Down  Reply
6 months ago
David H.

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

Vote Up0Vote Down  Reply
6 months ago
CEK

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,

Vote Up0Vote Down  Reply
7 months ago
Jay Glasgow

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

Vote Up0Vote Down  Reply
8 months ago
chandra

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

Vote Up0Vote Down  Reply
8 months ago
Lokesh Gupta

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

Vote Up0Vote Down  Reply
8 months ago
mehdi

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”

Vote Up0Vote Down  Reply
8 months ago
Antonio Carlos Stumpf Souto

The methods’ secret argument is never used,

Vote Up0Vote Down  Reply
10 months ago
Ramveer

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 )?

Vote Up0Vote Down  Reply
1 year ago

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

Popular Tutorials

  • Java 8 Tutorial
  • Core Java Tutorial
  • Collections in Java
  • Java Concurrency
  • Spring Boot Tutorial
  • Spring AOP Tutorial
  • Spring MVC Tutorial
  • Spring Security Tutorial
  • Hibernate Tutorial
  • Python Tutorial
  • Jersey Tutorial
  • Maven Tutorial
  • Log4j Tutorial
  • Regex Tutorial

Meta Links

  • Advertise
  • Contact Us
  • Privacy policy
  • About Me

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 © 2016 · HowToDoInjava.com · All Rights Reserved. | Sitemap

wpDiscuz