Core Java

AES Encryption and Decryption in Java (CBC Mode)

Transmitting confidential data such as plain text password through 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 algorithm for this.In this post, we will be discussing about AES(Advanced Encryption Standard) symmetric encryption algorithm in java with CBC mode which is faster and more secure than 3DES.

Encryption Type

As we know, there are 2 basic types of encryption – Asymmetric and Symmetric encryption. Asymmetric encryption 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.

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 and 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.Here is the wiki link for AES.The AES engine requires a plain-text and a secret key for encryption and same secret key is required to again decrypt it.

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

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

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.Here is an online tool for aes encryption.

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.

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.

Published on Java Code Geeks with permission by Dhiraj Ray, partner at our JCG program. See the original article here: AES Encryption and Decryption in Java(CBC Mode)

Opinions expressed by Java Code Geeks contributors are their own.

Dhiraj Ray

He is a technology savvy professional with an exceptional capacity to analyze, solve problems and multi-task. He is an avid reader and a technology enthusiast who likes to be up to date with all the latest advancements happening in the techno world. He also runs his own blog @ devglan.com
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

12 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
6 years ago

Hi,
Could you please explain:::Cipher cipher = Cipher.getInstance(“AES/CBC/PKCS5PADDING”);

HENIL CHOPRA
HENIL CHOPRA
5 years ago

Thank you very much;

epson error code 0xf1
5 years ago

AES is one of the encryption algorithms to go with the encryption and decryption process to secure the websites from the both users end, and with that, it has also provided the shortest path security also. which is very helpful.

Alok Singh
5 years ago

Very nice
very helpfull

Sumanth
Sumanth
5 years ago

Well, You said that the above program talks about AES 128. Now can you please tell me how to convert the above to AES256. I would like to know the difference between them.

Dhiraj Ray
5 years ago
Reply to  Sumanth

You can play with this tool here – https://www.devglan.com/online-tools/aes-encryption-decryption to understand these differences.

Devin Wilson
Devin Wilson
4 years ago

I took away a lot of very good points from this post and will definitely save it in my bookmarks.
Thanks for the effort you took to elaborate on this subject so thoroughly. For instant support related to the Change MSN Email Password please visit http://www.emailcustomerservice247.com/change-msn-password/ for the proper solution.

Bailey Raimo
Bailey Raimo
4 years ago

I like your blog post. Keep on writing this type of great stuff. I make sure to follow up on your blog in the future. We are providing instant support related to AOL Desktop Gold Update Problems then please visit http://www.emailscustomercare.com/aol-desktop-gold-update-error/ for the better result.

Russ
Russ
3 years ago

Hi,

Thanks for your tutorial. I was trying out the code myself but was having an error with the Base64 methods encodeBase64String() and decodeBase64(). Looks like you are using the Apache version of Base64.

I imported java.util.Base64 into my program so had to modify these to Base64.getEncoder().encodeToString() and Base64.getDecoder().decode().

Not sure how these two APIs differ but I thought I’d post it here in case someone else was having a similar issue.

Gbemiro
Gbemiro
3 years ago
Reply to  Russ

Use the commons library from apache, org.apache.commons.codec.binary.Base64. That is what he used, I believe

Saravanan Subramani
Saravanan Subramani
3 years ago

Hi It’s really helpful…stand alone code is working fine. but when deploying into tomcat, some characters not decrypted well. added URIEncoding=”UTF-8″ in tomcat server.xml, still getting this problem.. any idea how to fix it

Guido
Guido
3 years ago

Excelent post! very usefull.

Back to top button