Java AES Encryption Decryption Example

Java support many secure encryption algorithms but some of them are weak to be used in security-intensive applications. For example, the Data Encryption Standard (DES) encryption algorithm is considered highly insecure; messages encrypted using DES have been decrypted by brute force within a single day by machines such as the Electronic Frontier Foundation’s (EFF) Deep Crack.

A more secure encryption algorithm is AESAdvanced Encryption Standard which is a symmetric encryption algorithm. AES encryption is used by U.S. for securing sensitive but unclassified material, so we can say it is enough secure.

Read More : Java AES 256 Encryption Decryption Example

1. AES Encryption and Decryption

Let’s see an example of using AES encryption into java program.

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class AES {

	private static SecretKeySpec secretKey;
	private static byte[] key;

	public static void setKey(String myKey) 
	{
		MessageDigest sha = null;
		try {
			key = myKey.getBytes("UTF-8");
			sha = MessageDigest.getInstance("SHA-1");
			key = sha.digest(key);
			key = Arrays.copyOf(key, 16); 
			secretKey = new SecretKeySpec(key, "AES");
		} 
		catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} 
		catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

	public static String encrypt(String strToEncrypt, String secret) 
	{
		try 
		{
			setKey(secret);
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE, secretKey);
			return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
		} 
		catch (Exception e) 
		{
			System.out.println("Error while encrypting: " + e.toString());
		}
		return null;
	}

	public static String decrypt(String strToDecrypt, String secret) 
	{
		try 
		{
			setKey(secret);
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
			cipher.init(Cipher.DECRYPT_MODE, secretKey);
			return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
		} 
		catch (Exception e) 
		{
			System.out.println("Error while decrypting: " + e.toString());
		}
		return null;
	}
}

2. Encryption and decryption example

Let’s test if we are able to get the decrypted string back from encrypted string.

public static void main(String[] args) 
{
	final String secretKey = "ssshhhhhhhhhhh!!!!";
	
	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);
}
Output:

howtodoinjava.com
Tg2Nn7wUZOQ6Xc+1lenkZTQ9ZDf9a2/RBRiqJBCIX6o=
howtodoinjava.com

Drop me your question and comments below.

Happy Learning !!

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

40 thoughts on “Java AES Encryption Decryption Example”

  1. Hi, The encryption works good for me. But when I try to decrypt the string its returning the null value. Could you explain why is it happening and how to solve it? Below is the line of code for decryption:
    Cipher cipher = Cipher.getInstance(“AES/ECB/PKCS5PADDING”);
    cipher.init(Cipher.DECRYPT_MODE, secretKey);
    return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));

    Reply
  2. Is there a reason why you have SecretKeySpec as you instance variable resulting in the encrypt() and decrypt() methods having to init the ciphers every time?

    Could you init the two ciphers and keep these as your instance variables?

    Reply
  3. Can be customize to support for 512 Key length(encryption key)? How?
    Suppose, I want to encrypt message with 512 key if possible, Are there any possibilities?

    Reply
  4. This method works very good! Thanks for that!
    However, I’d like to send some encrypted data to my PHP API, and decipher the data there, applying the same key.
    Do you have, by change, any idea how I manage that?

    And also, do you have any solution how I can avoid hardcoding the encryption key?

    Reply
  5. Hie, thank you for this really informative blogpost.
    Kindly help me please. Here’s my encryption block:

     
    private String encrypt(String Data, String password) throws Exception {
            SecretKeySpec key = generateKey(password);
            Cipher c = Cipher.getInstance("AES/ECB/PKCS7Padding"); 
            c.init(Cipher.ENCRYPT_MODE, key);
    
            byte[] encVal = c.doFinal(Data.getBytes("UTF-8"));    
            Log.d("encVal", "val is "+encVal);              //value changes at every click
            String encryptedValue = Base64.encodeToString(encVal, Base64.DEFAULT); 
            Log.d("encryptedValue", "val is "+encryptedValue);                  
    
            return encryptedValue;
        }
    

    When I print the values in console, the final encrypted value remains same for an unchanging message and key (exactly what I desire).
    However, I just want to know that why ‘encVal’ which is the value resulting from doFinal() method, changes every time for the same unchanging message and key?
    Thank you 🙂

    Reply
  6. while sending the encrypted string in URl , its considering the special character as spaces.. so how we can remove special characters while encrypting the number.

    Reply
  7. Hi,
    Its working fine. but what my doubt is, Is this enough for complete security or need something more.

    Thank you.
    Satya.

    Reply
  8. I want to encrypt and decrypt a JSON object. Can I use this code with some changes? If yes, what all changes required? Thanks in advance!

    Reply
  9. how do we write this code mySQL ? I tried with aes_encrypt() and decrypt() getting null value so please guide me

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.