Java : Encryption and Decryption of Data using AES algorithm with example code

There are many problems when you try encrypting a string such password, credit card nos, phone no. etc ie
1. which algorithm to use.
2. how to store the generated Key in the database.
3. should i use MD5, AES etc.

Here is the question to all your answers. After spending sometime on this i finally got the best algorithm that a person can use to encrypt and decrypt data while he/she also wants to store those encrypted strings and later on want to decrypt it while retrieving the data.

Many people face problem while decrypting the encrypted data as the KEY used for encryption if stored as String in database then it becomes very tough to use that string as the KEY. So below is the code where you only need to store the encrypted code and not the  key. The decryption will take place as an when wanted.

For encryption we must use a secret key along with an algorithm. In the following example we use an algorithm called AES 128 and the bytes of the word "TheBestSecretKey" as the secret key (the best secret key we found in this world). AES algorithm can use a key of 128 bits (16 bytes * 8); so we selected that key.

import java.security.*;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.*;
import sun.misc.*;

public class AESencrp {

private static final String ALGO = "AES";
private static final byte[] keyValue =
new byte[] { 'T', 'h', 'e', 'B', 'e', 's', 't',
'S', 'e', 'c', 'r','e', 't', 'K', 'e', 'y' };

public static String encrypt(String Data) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.ENCRYPT_MODE, key);
byte[] encVal = c.doFinal(Data.getBytes());
String encryptedValue = new BASE64Encoder().encode(encVal);
return encryptedValue;
}

public static String decrypt(String encryptedData) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.DECRYPT_MODE, key);
byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedData);
byte[] decValue = c.doFinal(decordedValue);
String decryptedValue = new String(decValue);
return decryptedValue;
}
private static Key generateKey() throws Exception {
Key key = new SecretKeySpec(keyValue, ALGO);
return key;
}

}

We use "generateKey()" method to generate a secret key for AES algorithm with a given key.

Below is the code how you can use the above encryption algorithm.

public class Checker {

public static void main(String[] args) throws Exception {

System.out.println("Plain Text : " + password);
System.out.println("Encrypted Text : " + passwordEnc);
System.out.println("Decrypted Text : " + passwordDec);
}
}

NOTE :

I have got emails from user saying that the above code gives error when using in ECLIPSE. Error like :

Access restriction: The type BASE64Decoder is not accessible due to restriction on required library C:\Program Files\Java\jre6\lib\rt.jar

So to avoid this do the following :

Go to Window-->Preferences-->Java-->Compiler-->Error/Warnings.
Select Deprecated and Restricted API. Change it to warning.
Change forbidden and Discouraged Reference and change it to warning. (or as your need.)

Note: 12-12-2013

One of our readers (Saurabh Moghel), has given a solution about some issue:

Issue: Issue Of Access Restriction
Solution: Removing JRE system Library then adding it back from Build Path settings in the project properties.

1. what a great post

thanks

2. awesome...thanks dude

3. good one.......quite helpful

4. @Anonymous thank you dear..

5. The above code is still really basic its not the best we can do with AES.

byte[] key = null; // TODO
byte[] input = null; // TODO
byte[] output = null;
SecretKeySpec keySpec = null;
keySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
output = cipher.doFinal(input)

an you can pad the password to 256 and not 128

6. @JasonYes its a basic code. I never said its the best Code using AES. I just posted the Basic structure of how to use AES in java

7. Nice post farhan, spring security also provides way to encrypt password outofbox using MD5 and other encryption algorithm. Though this can be used a nice utility.

Thanks
Javin
Ldap authentication using Spring with Example

8. Hello
i have an error with this code.. could you help me ?
the error is class, interface, or enum expected;

9. @StudentMake sure the class name and the file name both are the exact same..

I made this program in ECLIPSE IDE.. in that i make a project and then in that i made a package named 'nomad' and inside it i had these two classes.

Here is the link on Java programming with eclipse : Basic

10. Thanks!

Small improvement to the code is to change the usage of sun.misc.BASE64 to Apache Commons Codec which provides Base64 http://commons.apache.org/codec/api-release/org/apache/commons/codec/binary/Base64.html

You should be using java.sun.misc.base64 even in Java 6, because it's not part of the API of java.

11. @Unknown Thank you for the information..

12. Split Sort Java Code SVP?

13. is there any method for steganography like this??????????

1. Well I don't have any experience on Steganography. But yeah there are blog posts available.

2. hey there could you please help me out i have an error with this code posted above and it says"Base64.decode cannot be resolved to a type"

14. hey there could you please help me out i've an error that says"Base64.decode cannot be resolved to a type"

15. This comment has been removed by a blog administrator.

16. how to make it with with password i.e

we pass the data and the password to encrypt with...

??

i tried creating a function which takes the password ,converts it to byte and then store it in keyValue

but it gives a error of "Invalid AES key length: 10 bytes"

plz reply ..i need it for my project

17. What is the correct way to save the keyValue? (java keystore?)

18. Thanks, that was exactly wath I was looking for. But since Base64 is now in Java8, it's better to use Base64.getEncoder() (import java.util.Base64;) rather than new BASE64Encoder().encode()

19. very good.. works with eclipse

20. hello...can u give me MATLAB code of AES for images

21. Thank you for writing this. It was very useful for me.

22. useful for me, many thanks!

23. You have really save me from a very big challenge that gave me sleepless nite.
I was just looking for something like this to know my way forward and all i could get from Stackoverflow was the first class AESencrp but how to checkout was another brain dump.

1. I believe you have got this code working. I'm getting this error when i run the file!
AESencrp.java:21: warning: BASE64Encoder is internal proprietary API and may be removed in a future release
String encryptedValue = new BASE64Encoder().encode(encVal);
^
AESencrp.java:29: warning: BASE64Decoder is internal proprietary API and may be removed in a future release
byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedData);
^
AESencrp.java:35: error: cannot find symbol
Key key = new SecretKeySpec(keyValue, ALGO);
^
symbol: class SecretKeySpec
location: class AESencrp
1 error
2 warnings

2. I have the same error.
Anyone know how to fix it?

24. Very Useful .. Thanks a lot

25. Very useful. Thank you.

26. It's very useful for me........Thanks you

27. Hey there my encrypted string breaks after 77 characters and rest of the encrypted string goes to 2nd line. I want whole string in a single line. Can you help me in that ?
Regards.

28. Hey my encrypted string breaks after 77 characters and rest of the encrypted string goes to 2nd line. I want whole encrypted code in single line. Can you help in that ?
Regards.

29. Спасибо )

30. AESencrp.java:21: warning: BASE64Encoder is internal proprietary API and may be removed in a future release
String encryptedValue = new BASE64Encoder().encode(encVal);
^
AESencrp.java:29: warning: BASE64Decoder is internal proprietary API and may be removed in a future release
byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedData);
^
AESencrp.java:35: error: cannot find symbol
Key key = new SecretKeySpec(keyValue, ALGO);
^
symbol: class SecretKeySpec
location: class AESencrp
1 error
2 warnings

31. Hi, Thank a lot, it is working and very clear about it.

32. very useful ........ But a question.Why this program don't use many characters for its output? after encrypting ,i can see only +=/0-9A-Za-z chars,its for AES algorithm or its programming

33. what is that packege nomad which you have used is it made by u or it is already given

34. excuse me please..
How can I use this codes with cloud computing?
I need to encrypt the text before upload it to cloud.
regards;
Farah

35. It is a great help. Thank you for the post

36. Awesome article. After day having sex with AES, I found working code. Thanx a lot and kudos to you!

37. error parsing file. how to resolve?

38. This is a great article. It gave me a lot of useful information. thank you very much. web data extraction services

39. Really helped me. Thank You

40. thank you relly helped me

1. can anyone help me how to decrypt cerber3 files?

41. is this code possible to securing files such as .doc .txt etc ?

42. hello sir iam srikanth. iam doing project on encryption algorithm which can be implemented in a sensor platform. can we do this? is this feasible? can u help me out. please help me at srikanthmadireddy44@gmail.com

43. if i compile this then it can occur error can't find symbol and its propritary for future release

44. Key key = generateKey();
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.ENCRYPT_MODE, key);
byte[] encVal = c.doFinal(Data.getBytes());
String encryptedValue = new BASE64Encoder().encode(encVal);
return encryptedValue;

how it will works explain please

45. Key key = generateKey();
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.ENCRYPT_MODE, key);
byte[] encVal = c.doFinal(Data.getBytes());
String encryptedValue = new BASE64Encoder().encode(encVal);
return encryptedValue;

this code how it will works ? explain in detail

46. i m getting exception javax.crypto.BadPaddingException: Given final block not properly padded

47. hey there I am having a trouble with package nomads please help me resolve it

48. Will this code work in netbeans?

49. hey I am getting error for Key key = generateKey(); saying that non-static method generateKey() cannot be referenced from a static context. please help.I am doing it on netbeans