AES Encryption and Decryption in Java

By | 6th July 2019
AES

While there are many encryption and decryption algorithms available, AES is one of the robust and reliable modes of encrypting the data. The implementation can be done in many languages as there are libraries and packages available for multiple languages.

Creating the AES encryption/decryption library

We do not need any special library to be downloaded for creating the AES encryption/decryption library. All we need is the javax.crypto package which is already available as a part of JDK

package com.java.encdec;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;

public final class EncDec 
{
public static String encrypt(String value, String ivVal, String key) {
    try {

        IvParameterSpec iv = new IvParameterSpec(ivVal.getBytes("UTF-8"));
        SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        cipher.init(1, skeySpec, iv);

        byte[] encrypted = cipher.doFinal(value.getBytes());

        return DatatypeConverter.printBase64Binary(encrypted);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return null;
}

public static String decrypt(String encrypted, String ivVal, String key) {
    try {

        IvParameterSpec iv = new IvParameterSpec(ivVal.getBytes("UTF-8"));
        SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        cipher.init(2, skeySpec, iv);

        byte[] original = cipher.doFinal(DatatypeConverter.parseBase64Binary(encrypted));
        return new String(original);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return null;
}
}

Now let us look into the above code by each section

Imports required for AES Encryption

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;

These are the classes required to perform encryption/decryption. AES is using Cipher padding for performing the encryption. There are two main classes that we are using here. IvParameterSpec will receive a byte array of the iv(initial vector).

IV is used along with the secret key to prevent the repetition of sequence in encryption. This will make the job of a hacker tough.

IvParameterSpec iv = new IvParameterSpec(ivVal.getBytes("UTF-8"));

The next one is the secret key. Similar to IvParameterSpec the SecretKeySpec class will also accept a byte array of the secret key. Along with that, it will receive the value of the encryption type that we want to use.

SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

After this, the Cipher object will be created with the above two objects and the mode(Encryption or Decryption) is indicated with the help of the first parameter while creating the Cipher object.

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(1, skeySpec, iv);

The different types of cipher class instances are

  • 1 – Encryption
  • 2 – Decryption
  • 3 – Key wrapping
  • 4 – Key unwrapping

The next part is receiving the encrypted content as bytes array and converting it to a string

byte[] encrypted = cipher.doFinal(value.getBytes());
return DatatypeConverter.printBase64Binary(encrypted);

Next, we will compile and export the full code to a java library.

Creating a java client to use the library

Now that we have created the library that can encrypt and decrypt the string, we will create a sample client to import and use this library.

package com.crypto.client;

import com.java.encdec.EncDec;

public class AESEncDecClient {

	public static void main(String[] args) {
		
		//Plain text message that we are going to encrypt
		String plainMessage = "We are learning AES encryption/decryption in techieshouts.com";
		String encryptedMessage = "";
		String decryptedMessage = "";
		String iv = "TestMeInitVector";
		String encryptionKey = "YourSampleEncKey";

		
		System.out.println("Plain text: " + plainMessage);
		
		System.out.println("\nEncrypting the plain text..");
		
		//Calling the encrypt method of the library to encrypt the plain text
		encryptedMessage = EncDec.encrypt(plainMessage, iv, encryptionKey);
		System.out.println("Encrypted text: " + encryptedMessage);
		
		System.out.println("\nDecrypting the encrypted text..");
		//Calling the decrypt method of the library to decrypt the encrypted message
		decryptedMessage = EncDec.decrypt(encryptedMessage, iv, encryptionKey);
		System.out.println("Decrypted text: " + decryptedMessage);

	}

}

In the above code snippet, we are first importing the library that we created earlier for encrypting and decrypting the text

import com.java.encdec.EncDec;

After that, we are creating the iv and key for encryption.

String iv = "TestMeInitVector";
String encryptionKey = "YourSampleEncKey";

Care should be taken while choosing the iv and encryptionKey values. Both of these values should be of 16 digits. The reason is, the block size of AES-128 or AES-256 algorithm is 16 bytes(128 bits). So the iv and keys used to encrypt the message should be of the same size as the block.

Also, check the same “AES Encryption and Decryption using Python”

Reference – Advance Encryption Standard

Leave a Reply

Your email address will not be published. Required fields are marked *