Вы находитесь на странице: 1из 5

03/06/2019 AES Encryption and Decryption in Java﴾CBC Mode﴿ | Java Code Geeks ‐ 2019

Knowledge Base Resources Deals Join Us About Login Register      è Search...


ANDROID JAVA JVM LANGUAGES SOFTWARE DEVELOPMENT AGILE CAREER COMMUNICATIONS DEVOPS META JCG

⌂ Home » Java » Core Java » AES Encryption and Decryption in Java(CBC Mode)

ABOUT 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

       

AES Encryption and Decryption in Java(CBC Mode)


 Posted by: Dhiraj Ray   in Core Java   March 12th, 2018   6 Comments   12030 Views NEWSLETTER

Transmitting confidential data such as plain text password through wire is always vulnerable to security.It is always recommended to encrypt
Insiders are already enjoying weekly upda
such information and use SSL to transmit those confidential data.Java provides multiple encryption algorithm for this.In this post, we will be
complimentary whitepapers!
discussing about AES(Advanced Encryption Standard) symmetric encryption algorithm in java with CBC mode which is faster and more secure
than 3DES. Join them now to gain exclusiv
access to the latest news in the Java w
well as insights about Android, Scala, Gro
Encryption Type other related technologies.

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 Enter your e­mail...
same.Asymmetric encryption is mostly used when there are 2 different endpoints are involved such as VPN client and server, SSH etc.
I agree to the Terms and Privacy Pol
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 Sign up
used in systems such as database system.Some examples of symmetric encryptions are Twofish, Blowfish, 3 DES, AES.


What is AES Encryption JOIN US
AES stands for Advanced Encryption System and its a symmetric encryption algorithm.It is a specification for the encryption of electronic data
With  1,240,600
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
unique visitors and
plain­text and a secret key for encryption and same secret key is required to again decrypt it. 500  authors we 
placed among the
To see how AES encryption works in practical, you can check this – AES Encryption Tool related sites aroun
Constantly being o
lookout for partne
encourage you to 
So If you have a b
unique and interesting content then you sh
check out our JCG partners program. You 
be a guest writer for Java Code Geeks a
your writing skills!

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

https://www.javacodegeeks.com/2018/03/aes‐encryption‐and‐decryption‐in‐javacbc‐mode.html 1/5
03/06/2019 AES Encryption and Decryption in Java﴾CBC Mode﴿ | Java Code Geeks ‐ 2019
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.

01 private static final String key = "aesEncryptionKey";
02 private static final String initVector = "encryptionIntVec";
03  
04 public static String encrypt(String value) {
05     try {
06         IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF‐8"));
07         SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF‐8"), "AES");
08  
09         Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
10         cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
11  
12         byte[] encrypted = cipher.doFinal(value.getBytes());
13         return Base64.encodeBase64String(encrypted);
14     } catch (Exception ex) {
15         ex.printStackTrace();
16     }
17     return null;
18 }

01 Other Interesting Posts
02 Spring Boot Security Password Encoding using Bcrypt Encoder
03 Spring Boot Security JWT Auth Example
04 Spring Boot Security OAuth2 Example
05 Spring Boot Security REST Basic Authentication
06 Spring Boot Actuator Complete Guide
07 Spring Boot Actuator  Rest Endpoints Example
08 Spring 5 Features and Enhancements
09 Spring Boot Thymeleaf Example
10 Spring Boot Security Hibernate Example with complete JavaConfig
11 Securing REST API with Spring Boot Security Basic Authentication
12 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.

01 public static String decrypt(String encrypted) {
02     try {
03         IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF‐8"));
04         SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF‐8"), "AES");
05  
06         Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
07         cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
08         byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted));
09  
10         return new String(original);
11     } catch (Exception ex) {
12         ex.printStackTrace();
13     }
14  
15     return null;
16 }

Testing AES Encryption and Decryption
Following is the main() implementation to test our AES implementation.

1 public static void main(String[] args) {
2     String originalString = "password";
3     System.out.println("Original String to encrypt ‐ " + originalString);
4     String encryptedString = encrypt(originalString);
5     System.out.println("Encrypted String ‐ " + encryptedString);
6     String decryptedString = decrypt(encryptedString);
7     System.out.println("After decryption ‐ " + decryptedString);
8 }

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.

https://www.javacodegeeks.com/2018/03/aes‐encryption‐and‐decryption‐in‐javacbc‐mode.html 2/5
03/06/2019 AES Encryption and Decryption in Java﴾CBC Mode﴿ | Java Code Geeks ‐ 2019
Tagged with:  AES ENCRYPTION

 (0 rating, 0 votes)
You need to be a registered member to rate this.  6 Comments  12030 Views   Tweet it!

Do you want to know how to develop your skillset to become a Java
Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
Enter your e­mail...

I agree to the Terms and Privacy Policy

Sign up

LIKE THIS ARTICLE? READ MORE FROM JAVA CODE GEEKS

Calculadora de Amor Microservice Design AES­256 Encryption Secure Password


Verdadeiro Patterns with Java and JCEKS Storage – Don’ts, dos
and a Java example
Ad Unitel javacodegeeks.com javacodegeeks.com javacodegeeks.com

Choosing Java AES Encryption in Signing SOAP Scaling to Thousands


Cryptographic Javascript and Messages ­ Generation of Threads
Algorithms Part 3 –... Decryption in Java of Enveloped XML...

javacodegeeks.com javacodegeeks.com javacodegeeks.com javacodegeeks.com

6  Leave a Reply

Join the discussion...

5  1  1      6

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

  Subscribe    newest  oldest  most voted

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

https://www.javacodegeeks.com/2018/03/aes‐encryption‐and‐decryption‐in‐javacbc‐mode.html 3/5
03/06/2019 AES Encryption and Decryption in Java﴾CBC Mode﴿ | Java Code Geeks ‐ 2019
Member
 0     Reply  1 year ago

HENIL CHOPRA 

Thank you very much;

Guest
 ­1      Reply  8 months ago

epson error code 0xf1 

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.
Guest

 ­1      Reply  6 months ago

Alok Singh 

Very nice
very helpfull
Guest

 ­1      Reply  5 months ago

Sumanth 

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.
Guest

 0     Reply  5 months ago 

Dhiraj Ray 

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

 0   Reply  5 months ago

Ganha Dados de Internet ABRIR


Joga 'Giga Unitel", responde às perguntas e habilita-te a Ganhar Muitos Prémios GIGA

KNOWLEDGE BASE HALL OF FAME ABOUT JAVA CODE GEEKS

JCGs (Java Code Geeks) is an independent online community focused on creating 
Courses “Android Full Application Tutorial” series
ultimate Java to Java developers resource center; targeted at the technical archite
technical team lead (senior developer), project manager and junior developers ali
Examples 11 Online Learning websites that you
JCGs serve the Java, SOA, Agile and Telecom communities with daily news written
should check out
domain experts, articles, tutorials, reviews, announcements, code snippets and op
Minibooks
source projects.
Advantages and Disadvantages of Cloud
Resources Computing – Cloud computing pros and
cons DISCLAIMER
Tutorials
Android Google Maps Tutorial All trademarks and registered trademarks appearing on Java Code Geeks are the
property of their respective owners. Java is a trademark or registered trademark 
PARTNERS Android JSON Parsing with Gson Tutorial Oracle Corporation in the United States and other countries. Examples Java Code 
is not connected to Oracle Corporation and is not sponsored by Oracle Corporation
Android Location Based Services
Mkyong Application – GPS location

Android Quick Preferences Tutorial
THE CODE GEEKS NETWORK
Difference between Comparator and
Comparable in Java
.NET Code Geeks
GWT 2 Spring 3 JPA 2 Hibernate 3.5
Java Code Geeks Tutorial

System Code Geeks Java Best Practices – Vector vs ArrayList
vs HashSet
Web Code Geeks

https://www.javacodegeeks.com/2018/03/aes‐encryption‐and‐decryption‐in‐javacbc‐mode.html 4/5
03/06/2019 AES Encryption and Decryption in Java﴾CBC Mode﴿ | Java Code Geeks ‐ 2019
 
Java Code Geeks and all content copyright © 2010­2019, Exelixis Media P.C. | Terms of Use | Privacy Policy | Contact

https://www.javacodegeeks.com/2018/03/aes‐encryption‐and‐decryption‐in‐javacbc‐mode.html 5/5

Вам также может понравиться