Friday, 23 August 2013

Encrypt and decrypt a password in Java using Advanced Encryption Standard (AES).

One of the best and secured way to Encrypt and Decrypt Advanced Encryption Standard (AES).

 The standard comprises three block ciphers, AES-128, AES-192 and AES-256, Each of these ciphers has a 128-bit block size, with key sizes of 128, 192 and 256 bits, respectively. The AES ciphers have been analyzed extensively and are now used worldwide.

AES algorithm can use a key of 128 bits (16 bytes * 8); so we selected that key.

Simple Data Encryption/Decryption Example with AES:

package com.pswd;
import java.security.Key;
import java.security.spec.InvalidKeySpecException;

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

import sun.misc.*;

/**
 * This class is used for encrypt and decrypt the  password field.
 *
 */
public class PswdEnc {

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

    /*--Used to encrypt the string and returns 24 bit
 and based on string length--*/
    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;
    }
    /*--Used to decrypt the encrypted string and returns 
actual plain string--*/
    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;
    }
       public static void main(String[] args) throws Exception {
  
    String enc= encrypt("Alekhya");
    System.out.println("Encrption: "+enc);
 }
    
    private static Key generateKey() throws Exception {
        Key key = new SecretKeySpec(keyValue, ALGO);
        return key;
    }
     
}

OUTPUT:

Encrption: TKpzxJDDXob7UKWlkYG4Vw==

 

No comments: