Sunday 2 August 2015

Paasord Encryption and Decryption in java.


//commons-codec-1.6.jar should be added to Build path.

package foo;

import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.junit.Test;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;


public class PasswordEncryption {

    private static final String ALGORITHM = "AES";
    private static final String KEY = "1Hbfh667adfDEJ78";
    String password = "Test";
    private static Key generateKey() throws Exception {
         Key key = new SecretKeySpec(PasswordEncryption.KEY.getBytes(),PasswordEncryption.ALGORITHM);
         return key;
     }
 
    public static String encrypt(String value) throws Exception {
        Key key = generateKey();
        Cipher cipher = Cipher.getInstance(PasswordEncryption.ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte [] encryptedByteValue = cipher.doFinal(value.getBytes("utf-8"));
        String encryptedValue64 = new BASE64Encoder().encode(encryptedByteValue);
        return encryptedValue64;
             
    }
  
      public static String decrypt(String value) throws Exception {
            Key key = generateKey();
            Cipher cipher = Cipher.getInstance(PasswordEncryption.ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte [] decryptedValue64 = new BASE64Decoder().decodeBuffer(value);
            byte [] decryptedByteValue = cipher.doFinal(decryptedValue64);
            String decryptedValue = new String(decryptedByteValue,"utf-8");
            return decryptedValue;
                  
        }
  
    @Test
    public void passowrdTest() throws Exception{
        System.out.println("encrypt : "+encrypt(password));
        System.out.println("decrypt : "+decrypt(encrypt(password)));
    }  
}//Class closed

No comments:

Post a Comment