Tuesday, January 10, 2012

String Encryption

package com.nmmc.collection.utils;

import java.security.Key;

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import sun.misc.BASE64Encoder;

public class SimpleEncryptor {

    private static Log log = LogFactory.getLog(SimpleEncryptor.class);

    private static final String ALGORITHM = "AES";

    private static final byte[] keyValue = new byte[] { '1', '2', '3', '4', 'I', '$', '%', 'z', 'e', 'F', 'r', 'e', 'C', 's', 'e', 'a' };

    public static String encrypt(String valueToEnc) {
        String encryptedValue = null;
        try {
            Key key = generateKey();
            Cipher c = Cipher.getInstance(ALGORITHM);
            c.init(Cipher.ENCRYPT_MODE, key);
            byte[] encValue = c.doFinal(valueToEnc.getBytes());
            encryptedValue = new BASE64Encoder().encode(encValue);
        } catch (Exception exception) {
            log.error(exception);
        }
        return encryptedValue;
    }

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