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.

package nomad;

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.

package nomad;

public class Checker {

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

        String password = "mypassword";
        String passwordEnc = AESencrp.encrypt(password);
        String passwordDec = AESencrp.decrypt(passwordEnc);

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


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. awesome...thanks dude

  2. good one.......quite helpful

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

  4. @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

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

    Ldap authentication using Spring with Example

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

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

  8. 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.
    For more info: http://java.sun.com/products/jdk/faq/faq-sun-packages.html

  9. 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"

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

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

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

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

  14. 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()

  15. very good.. works with eclipse

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

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

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