AES Encryption and Decryption in Java

AES Encryption and Decryption in Java thumbnail
124K
By Dhiraj 17 December, 2017

Transmitting confidential data such as plain text password through a wire is always vulnerable to security. It is always recommended to encrypt such information and use SSL to transmit those confidential data. Java provides multiple encryption algorithms for this. In this post, we will be discussing about AES(Advanced Encryption Standard) symmetric encryption algorithm in java which is faster and more secure than 3DES.

Different Encryption Types

As we know, there are 2 basic types of encryption - Asymmetric and Symmetric encryption. Asymmetric encryption such as RSA uses two different keys as public and private keys. Here, you can encrypt sensitive information with a public key and a matching private key is used to decrypt the same. Asymmetric encryption is mostly used when there are 2 different endpoints are involved such as VPN client and server, SSH, etc.

You can use this online RSA tool to visualize this concept.

Similarly, we have another encryption technique called as Symmetric encryption.This type of encryption uses a single key known as private key or secret key to encrypt as well as decrypt sensitive information.This type of encryption is very fast as compared to asymmetric encryption and are used in systems such as database system. Some examples of symmetric encryptions are Twofish, Blowfish, 3 DES, AES.

What is AES Encryption

AES stands for Advanced Encryption System and its a symmetric encryption algorithm. It is a specification for the encryption of electronic data established by the U.S. National Institute of Standards and Technology (NIST) in 2001. The AES engine requires a plain-text and a secret key for encryption and same secret key is required again to decrypt it.

AES encryption operates in 2 different modes i.e. - ECB and CBC mode.

To see how AES encryption works in practical, you can check this - AES Encryption Tool

AES Architecture

aes

The input can be of 128 bit or 192 bit or 256 bit and corresponding bit of cipher text is generated.

But, as a developer behind Edu Jungles reports, if you are selecting 128 bits for encryption, then the secret key must be of 16 bits long and 24 and 32 bits for 192 and 256 bits of key size.

Differentt AES Encryption Modes

As we discussed above, AES operates in 2 modes - CBC and ECB mode.

ECB(Electronic Code Book) is the simplest encryption mode and does not require IV for encryption. The input plain text will be divided into blocks and each block will be encrypted with the key provided and hence identical plain text blocks are encrypted into identical cipher text blocks.

CBC mode is highly recommended and it requires IV to make each message unique. Hence, IV is used to randomize the encryption of each similar blocks. So any identical plain text blocks will be encrypted into disimmilar cipher text blocks. If no IV is entered then default will be used here for CBC mode and that defaults to a zero based byte[16].

AES Encryption in Java

Following is the sample program in java that performs AES encryption.Here, we are using AES with CBC mode to encrypt a message as ECB mode is not semantically secure.The IV mode should also be randomized for CBC mode.

If the same key is used to encrypt all the plain text and if an attacker finds this key then all the cipher can be decrypted in the similar way. We can use salt and iterations to improve the encryption process further. In the following example we are using 128 bit encryption key and the cipher is AES/CBC/PKCS5PADDING

private static final String key = "aesEncryptionKey";
private static final String initVector = "encryptionIntVec";

public static String encrypt(String value) {
	try {
		IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
		SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

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

		byte[] encrypted = cipher.doFinal(value.getBytes());
		return Base64.encodeBase64String(encrypted);
	} catch (Exception ex) {
		ex.printStackTrace();
	}
	return null;
}
 Other Interesting Posts
Spring Boot Security Password Encoding using Bcrypt Encoder
Spring Boot Security JWT Auth Example
Spring Boot Security OAuth2 Example
Spring Boot Security REST Basic Authentication
Spring Boot Actuator Complete Guide
Spring Boot Actuator  Rest Endpoints Example
Spring 5 Features and Enhancements
Spring Boot Thymeleaf Example
Spring Boot Security Hibernate Example with complete JavaConfig
Securing REST API with Spring Boot Security Basic Authentication
Websocket spring Boot Integration Without STOMP with complete JavaConfig

AES Decryption in Java

Following is the reverse process to decrypt the cipher.The code is self explainatory.

public static String decrypt(String encrypted) {
	try {
		IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
		SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
		cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
		byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted));

		return new String(original);
	} catch (Exception ex) {
		ex.printStackTrace();
	}

	return null;
}

Testing AES Encryption and Decryption

Following is the main() implementation to test our AES implementation.

public static void main(String[] args) {
	String originalString = "password";
	System.out.println("Original String to encrypt - " + originalString);
	String encryptedString = encrypt(originalString);
	System.out.println("Encrypted String - " + encryptedString);
	String decryptedString = decrypt(encryptedString);
	System.out.println("After decryption - " + decryptedString);
}

Following is the result.

aes-output

Conclusion

I hope this article served you that you were looking for. If you have anything that you want to add or share then please share it below in the comment section.In the next post we will be discussing about interoperability of AES between javascript and java.

Share

If You Appreciate This, You Can Consider:

We are thankful for your never ending support.

About The Author

author-image
A technology savvy professional with an exceptional capacity to analyze, solve problems and multi-task. Technical expertise in highly scalable distributed systems, self-healing systems, and service-oriented architecture. Technical Skills: Java/J2EE, Spring, Hibernate, Reactive Programming, Microservices, Hystrix, Rest APIs, Java 8, Kafka, Kibana, Elasticsearch, etc.

Further Reading on Core Java