Thursday, November 22, 2012

Encrypt and decrypt string using AES algorithm using Java

Encrypt and decrypt string or bytes using AES algorithm performed by Java code. below is the code snippet. 

package com.pkm;

import java.security.Key;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class EncryptUtils {
    private static String algorithm = "AES";
    private static byte[] keyValue = "1111111111111111".getBytes();
    private static SecureRandom iv = new SecureRandom("192837465UTYELBN".getBytes());
    
    public static void main(String[] args) throws Exception {
        String valueToEncrypt = "Some value";
        String encryptedValue = encrypt(valueToEncrypt);
        System.out.println("Encrypted=" + encryptedValue);
        
        String afterDecrypt = decrypt(encryptedValue);
        System.out.println("Decrypted=" + afterDecrypt);
    }

    static String encrypt(String value) throws Exception {
        Key key = generateKey();
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, key, iv);
        byte [] encByte = cipher.doFinal(value.getBytes());
        String encString = new BASE64Encoder().encode(encByte);
        return encString;
    }

    static String decrypt(String value) throws Exception {
        Key key = generateKey();
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte [] decByte64 = new BASE64Decoder().decodeBuffer(value);
        byte [] decByte = cipher.doFinal(decByte64);
        String decString = new String(decByte);
        return decString;
    }

    static private Key generateKey() throws Exception {
        return new SecretKeySpec(keyValue, algorithm);
    }
}


Below is output:

Original=Some value
Encrypted=i4he5mR49eRkWmQRVh12yg==
Decrypted=Some value



No comments:

Post a Comment