package com.muchinfo.mtp3common.utils;


import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.util.Base64;
import java.util.List;

;

public class EncryptUtilForSearch {
	
	private static final String PRIVATE_KEY = "Ub$kl^P3";
	
	public static <T> T decodeObject(T t){
		try {
			EncryptUtilForSearch.doEncryptionAndDecode(t,false);
		} catch (NullPointerException e) {
			throw new RuntimeException("Object为Null，无法解密！");
		} catch (Exception e) {
			throw new RuntimeException("(" + t.getClass() + "：" + t.toString() + ")解密失败！");
		}
		return t;
	}
	
	public static <T> T encryptObject(T t){
		try {
			EncryptUtilForSearch.doEncryptionAndDecode(t,true);
		} catch (NullPointerException e) {
			throw new RuntimeException("Object为Null，无法加密！");
		} catch (Exception e) {
			throw new RuntimeException("(" + t.getClass() + "：" + t.toString() + ")加密失败！");
		}
		return t;
	}
	
	public static void doEncryptionAndDecode(Object o, boolean flag)throws Exception{
		doEncryptionAndDecode((List<?>) o, flag, PRIVATE_KEY);
	}
	
	public static void doEncryptionAndDecode(List<?> list, boolean flag)throws Exception{
		doEncryptionAndDecode(list, flag, PRIVATE_KEY);
	}
	
	public static String decrypt(String message){
		try {
			return decrypt(message, PRIVATE_KEY);
		} catch (Exception e) {
			throw new RuntimeException("解密失败：" + message);
		}
	}
	
	public static String encrypt(String message){
		try {
			return encrypt(message, PRIVATE_KEY);
		} catch (Exception e) {
			throw new RuntimeException("加密失败：" + message);
		}
	}
	
	/**
	 * 终端传来的是2次加密的，所以要进行二次解密（如123123加密为MTIzMTIz, MTIzMTIz再加密为 TVRJek1USXo=）
	 * @param base64 
	 * @return
	 */
	public static String Base64ToString(String base64){
		try {
			byte[] decoded = Base64.getDecoder().decode(base64);
	    	String encoder = new String(Base64.getDecoder().decode(new String(decoded)));
	    	return encoder;
		} catch (Exception e) {
			throw new RuntimeException("解密失败：" + base64);
		}
		
	}
	
	/**
	 * 
	* <b>Summary: </b>
	*     doEncryptionAndDecode(根据注解进行集合对象属性加解密)
	* @param list
	* @param flag true加密 false解密
	* @param securityKey
	* @throws Exception 
	* @return void
	 */
	private static void doEncryptionAndDecode(List<?> list, boolean flag, String securityKey)throws Exception{
		for (Object o : list) {
			doEncryptionAndDecode(o, flag);
		}
	}
	
	private static String encrypt(String message, String key) throws Exception {
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");

        DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));

        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);

//        printHexString("", secretKey.toString().getBytes());
        IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);

        return encodeBase64(cipher.doFinal(message.getBytes("UTF-8")));
    }

	private static String decrypt(String message, String key) throws Exception {
        byte[] bytesrc = decodeBase64(message);//convertHexString(message);
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);

        IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
        cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);

        byte[] retByte = cipher.doFinal(bytesrc);
        return new String(retByte);
    }
    
	private static String encodeBase64(byte[] b) {
        return Base64.getEncoder().encodeToString(b);
    }

	private static byte[] decodeBase64(String base64String) {
        return Base64.getDecoder().decode(base64String);
    }
	
	public static String toHexString(byte b[]) {
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            String plainText = Integer.toHexString(0xff & b[i]);
            if (plainText.length() < 2)
                plainText = "0" + plainText;
            hexString.append(plainText);
        }
        return hexString.toString();
    }
}
