package com.jpsoft.shinestar.modules.common.utils;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.Key;

public class DES3 {
	public String encrypt(byte[] key, byte[] data)  throws Exception {

        Key deskey = null;
        DESedeKeySpec spec = new DESedeKeySpec(key);
        SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
        deskey = keyfactory.generateSecret(spec);
        Cipher cipher = Cipher.getInstance("desede" + "/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, deskey);
        byte[] bOut = cipher.doFinal(data);

        return Base64.encode(bOut);
    }
    
    public String encrypt(String key, String data)  throws Exception {
    	return encrypt(getKeyByte(key),data.getBytes("UTF-8"));
    }

    public String decrypt(byte[] key, byte[] data) throws Exception {
        Key deskey = null;
        DESedeKeySpec spec = new DESedeKeySpec(key);
        SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
        deskey = keyfactory.generateSecret(spec);

        Cipher cipher = Cipher.getInstance("desede" + "/ECB/PKCS5Padding");

        cipher.init(Cipher.DECRYPT_MODE, deskey);

        byte[] bOut = cipher.doFinal(data);

        return new String(bOut, "UTF-8");
    }
    
    public String decrypt(String key, String data)  throws Exception {
    	return decrypt(getKeyByte(key), Base64.decode(data));
    }

    public byte[] getKeyByte(String key) throws UnsupportedEncodingException {
        if (key == null) {
            return new byte[0];
        }

        int length = key.length();
        if (length >= 24) {
            return key.substring(0, 24).getBytes("UTF-8");
        } else {
            for (int i = 0; i < (24 - length); i++) {
                key += "0";
            }
            
            return key.getBytes("UTF-8");
        }
    }
    
    public static void main(String[] args) {
    	DES3 des3 = new DES3();
		String appKey = "8ZZAHLlTMeNRCP6X";
		
		try {
			System.out.println(des3.encrypt(appKey, "ac5c629f-068d-4b8d-8700-3c3d362337f0"));

			System.out.println(des3.decrypt(appKey, "Xkb9FDXbmw8tEybl2ItjvomEK0QrL+pn6wt9yO7/vA7G9jIUiDhFLg=="));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
