package com.eactive.eai.transformer.function.crypto;

import java.security.GeneralSecurityException;

import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;


public class DesCodec {
	Cipher ecipher;
	Cipher dcipher;

	public DesCodec(byte[] keyData) throws GeneralSecurityException {
		try {
        	//SecretKey key = KeyGenerator.getInstance("DES").generateKey();
			
        	DESKeySpec desKeySpec = new DESKeySpec(keyData);
        	SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        	SecretKey key = keyFactory.generateSecret(desKeySpec);

        	ecipher = Cipher.getInstance("DES");
			dcipher = Cipher.getInstance("DES");
			ecipher.init(Cipher.ENCRYPT_MODE, key);
			dcipher.init(Cipher.DECRYPT_MODE, key);
		} catch (javax.crypto.NoSuchPaddingException e) {
			throw e;
		} catch (java.security.NoSuchAlgorithmException e) {
			throw e;
		} catch (java.security.InvalidKeyException e) {
			throw e;
		}
	}

	public byte[] encrypt(byte[] utf8) throws Exception {
		try {
			// Encode the string into bytes using utf-8
			//byte[] utf8 = str.getBytes("UTF8");

			// Encrypt
			byte[] enc = ecipher.doFinal(utf8);

			// Encode bytes to base64 to get a string				
			//return new sun.misc.BASE64Encoder().encode(enc);
			return enc;
		} catch (javax.crypto.BadPaddingException e) {
			throw e;
		} catch (IllegalBlockSizeException e) {
			throw e;
		}
	}

	public byte[] decrypt(byte[] dec) throws Exception {
		try {
			// Decode base64 to get bytes
			//byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);

			// Decrypt
			byte[] utf8 = dcipher.doFinal(dec);

			// Decode using utf-8
			//return new String(utf8, "UTF8");
			
			return utf8;
		} catch (javax.crypto.BadPaddingException e) {
			throw e;
		} catch (IllegalBlockSizeException e) {
			throw e;
		}
	}
}
