Pages Navigation Menu

Coding is much easier than you think

Encryption and Decryption of Data using AES-128 algorithm in Java

 
Encryption and Decryption
 
Encryption and Decryption of Data using AES-128 algorithm in Java
 

package com.simplecode.action;

import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.*;

public class AES 
{
private static String algorithm = "AES";
private static byte[] keyValue=new byte[] 
{ 'A', 'S', 'e', 'c', 'u', 'r', 'e', 'S', 'e', 'c', 'r', 'e', 't', 'K', 'e', 'y' };

        // Performs Encryption
        public static String encrypt(String plainText) throws Exception 
        {
                Key key = generateKey();
                Cipher chiper = Cipher.getInstance(algorithm);
                chiper.init(Cipher.ENCRYPT_MODE, key);
                byte[] encVal = chiper.doFinal(plainText.getBytes());
                String encryptedValue = new BASE64Encoder().encode(encVal);
                return encryptedValue;
        }

        // Performs decryption
        public static String decrypt(String encryptedText) throws Exception 
        {
                // generate key 
                Key key = generateKey();
                Cipher chiper = Cipher.getInstance(algorithm);
                chiper.init(Cipher.DECRYPT_MODE, key);
                byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedText);
                byte[] decValue = chiper.doFinal(decordedValue);
                String decryptedValue = new String(decValue);
                return decryptedValue;
        }

//generateKey() is used to generate a secret key for AES algorithm
        private static Key generateKey() throws Exception 
        {
                Key key = new SecretKeySpec(keyValue, algorithm);
                return key;
        }

        // performs encryption & decryption 
        public static void main(String[] args) throws Exception 
        {

                String plainText = "Password";
                String encryptedText = AES.encrypt(plainText);
                String decryptedText = AES.decrypt(encryptedText);

                System.out.println("Plain Text : " + plainText);
                System.out.println("Encrypted Text : " + encryptedText);
                System.out.println("Decrypted Text : " + decryptedText);
        }
}

 

About Mohaideen Jamil


Am currently working as a Struts 2 Developer in a reputed IT Organisations. I can help you with teaching Core java and Struts 2. Follow me on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.

12 Comments

  1. Hello, I had a question. Can you Create this Java AES in a GUI? e. g. a Textfield which is decrypted: “Hello …..” and another Textfield which encrypt these Text “Hello….” and with Encrypt/Decrypt Buttons?

    • Yes you can

      • whether the original source code of AES 128 ???

  2. Can you solve an encryption and decryption of aes using OFB mode?

  3. Thanks for posting the example. I managed to produce a version that did not use the base64 sun library so compiler did not complain about using restricted routines.

    Here is my modified version, note encode() and decode() methods::


    import java.security.Key;
    import javax.crypto.Cipher;
    import javax.crypto.spec.SecretKeySpec;

    public class AES {
    private static String algorithm = "AES";
    private static byte[] keyValue =
    new byte[] { 'A', 'S', 'e', 'c', 'u', 'r', 'e',
    'S', 'e', 'c', 'r', 'e', 't', 'K', 'e', 'y' };

    // Performs Encryption
    public static String encrypt(String plainText) throws Exception {
    Key key = generateKey();
    Cipher chiper = Cipher.getInstance(algorithm);
    chiper.init(Cipher.ENCRYPT_MODE, key);
    byte[] encVal = chiper.doFinal(plainText.getBytes());
    String encryptedValue = encode(encVal);
    return encryptedValue;
    }

    // Performs decryption
    public static String decrypt(String encryptedText) throws Exception {
    // generate key
    Key key = generateKey();
    Cipher chiper = Cipher.getInstance(algorithm);
    chiper.init(Cipher.DECRYPT_MODE, key);
    byte[] decordedValue = decode(encryptedText);
    byte[] decValue = chiper.doFinal(decordedValue);
    String decryptedValue = new String(decValue);
    return decryptedValue;
    }

    // generateKey() is used to generate a secret key for AES algorithm
    private static Key generateKey() throws Exception {
    Key key = new SecretKeySpec(keyValue, algorithm);
    return key;
    }

    // performs encryption & decryption
    public static void main(String[] args) throws Exception {

    String plainText = "Password";
    String encryptedText = AES.encrypt(plainText);
    String decryptedText = AES.decrypt(encryptedText);

    System.out.println("Plain Text : " + plainText);
    System.out.println("Encrypted Text : " + encryptedText);
    System.out.println("Decrypted Text : " + decryptedText);
    }

    private static String encode(byte[] byteArray) {
    StringBuilder buf = new StringBuilder();
    int intVal = 0;
    String frag = "";
    for (byte b : byteArray) {
    intVal = (int) (0xff & b);
    frag = Integer.toHexString(intVal);
    if (1 == frag.length()) {
    frag = "0" + frag;
    }
    buf.append(frag);
    }
    return buf.toString();
    }

    private static byte[] decode(String textString) {
    byte[] byteArray = new byte[(textString.length() / 2)];
    int intVal = 0;
    String frag = "";
    int c1 = 0;
    for (int i = 0; i < byteArray.length; i++) {
    c1 = (i * 2);
    frag = textString.substring(c1, (c1 + 2));
    intVal = Integer.parseInt(frag, 16);
    byteArray[i] = (byte) (0xff &#038; intVal);
    }
    return byteArray;
    }
    }

  4. Thanks for your sharing but I would like to give some feedback whcih I read from stackoverflow.
    http://stackoverflow.com/questions/469695/decode-base64-data-in-java/2054226#2054226

    sun.misc.BASE64Decoder() is internal Sun code, is NOT part of J2SE (it, not portable), and may disappear at any time — Sun explicitly says to NOT use their internal libraries in user code

    • Hi,

      Yes I agree , using sun.misc.BASE64Decoder() was a bad practice of course, but I was using the above code for my 10 year old project :( :P, hence this code suits my requirement.

      If you have any better approach , please share it..
      Thanks :)

  5. How abt AES 192 logic??

  6. hai thank for your post…..but i need how to encrypt and decrypt List or ArrayList….

  7. I would like this!!!

  8. Thanks for sharing you save my lost of time. And that program really help me in my project.
    Thanks again

Leave a Reply Note To post source code in comment, use [code] [/code] tag