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 the 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 in this java program.

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(final 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 | UnsupportedEncodingException e) {

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

  public static String decrypt(final String strToDecrypt, final String secret) {
    try {
      Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
      cipher.init(Cipher.DECRYPT_MODE, secretKey);
      return new String(cipher.doFinal(Base64.getDecoder()
    } 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 the encrypted string.

final String secretKey = "ssshhhhhhhhhhh!!!!";

String originalString = "";
String encryptedString = AES.encrypt(originalString, secretKey) ;
String decryptedString = AES.decrypt(encryptedString, secretKey) ;


Program Output.

Drop me your question and comments below.

Happy Learning !!

Download Sourcecode

Leave a Reply

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.

Our Blogs

REST API Tutorial