6/28/11

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);
    }
}


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.


SHARE THIS POST:

57 comments:

  1. good one.......quite helpful

    ReplyDelete
  2. 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

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

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

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

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

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

    ReplyDelete
  8. is there any method for steganography like this??????????

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

      Delete
    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"

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

    ReplyDelete
  10. This comment has been removed by a blog administrator.

    ReplyDelete
  11. 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

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

    ReplyDelete
  13. 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()

    ReplyDelete
  14. very good.. works with eclipse

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

    ReplyDelete
  16. Thank you for writing this. It was very useful for me.

    ReplyDelete
  17. 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.

    ReplyDelete
    Replies
    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

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

      Delete
  18. It's very useful for me........Thanks you

    ReplyDelete
  19. 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.

    ReplyDelete
  20. 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.

    ReplyDelete
  21. 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

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

    ReplyDelete
  23. 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

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

    ReplyDelete
  25. 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

    ReplyDelete
  26. It is a great help. Thank you for the post

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

    ReplyDelete
  28. error parsing file. how to resolve?

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

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

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

    ReplyDelete
  32. 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

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

    ReplyDelete
  34. 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

    ReplyDelete
  35. 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

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

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

    ReplyDelete
  38. Will this code work in netbeans?

    ReplyDelete
  39. 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

    ReplyDelete