package com.zehong.web.controller.tool;

import java.io.UnsupportedEncodingException;

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




public class DESEncoder {

	/**
	 * 加密向量不要动(8位)
	 */
	private static String IV = "12345678";
	/**
	 * 加密
	 * @param value 加密内容
	 * @param KEY 加密密钥（8位）
	 * @return
	 */
	public static String encrypt(String value,String KEY) {
		byte[] key = null, iv = null;
		try {
			key = KEY.getBytes("utf-8");
			iv = IV.getBytes("utf-8");
		} catch (UnsupportedEncodingException e1) {

		}
		String result = null;
		byte[] tmpOriginalStr = null;
		try {
			if (!isEmpty(value)) {
				tmpOriginalStr = value.getBytes("utf-8");
				SecretKeyFactory keyFactory = SecretKeyFactory
						.getInstance("DES");
				DESKeySpec dks = new DESKeySpec(key);
				SecretKey secretKey = keyFactory.generateSecret(dks);
				IvParameterSpec param = new IvParameterSpec(iv);
				Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
				cipher.init(Cipher.ENCRYPT_MODE, secretKey, param);
				byte[] tmpEncypt = cipher.doFinal(tmpOriginalStr);
				if (tmpEncypt != null) {
					// BASE64Encoder bse=new BASE64Encoder();
					// result=bse.encode(tmpEncypt);
					byte[] b = com.main.util.Base64_2.encode(tmpEncypt, 0);
					result = parseByte2HexStr(b);
				}
			}
		} catch (Exception e) {
		}
		return result;
	}



	/**
	 * 解密
	 * @param value 要解密的字符串
	 * @param KEY 解密密钥
	 * @return
	 */
	public static java.lang.String decrypt(String value,String KEY) {
		byte[] decrypt = parseHexStr2Byte(value);
		byte[] key = null, iv = null;
		try {
			key = KEY.getBytes("utf-8");
			iv = IV.getBytes("utf-8");
		} catch (UnsupportedEncodingException e1) {

		}
		String result = null;
		byte[] tmpEncrypStr = null;
		try {

				// BASE64Decoder bd=new BASE64Decoder();
				// tmpEncrypStr =bd.decodeBuffer(encrypStr);
				tmpEncrypStr = com.main.util.Base64_2.decode(decrypt, 0);
				SecretKeyFactory keyFactory = SecretKeyFactory
						.getInstance("DES");
				DESKeySpec dks = new DESKeySpec(key);
				SecretKey secretKey = keyFactory.generateSecret(dks);
				IvParameterSpec param = new IvParameterSpec(iv);
				Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
				cipher.init(Cipher.DECRYPT_MODE, secretKey, param);
				byte[] tmpDecrypt = cipher.doFinal(tmpEncrypStr);
				if (tmpDecrypt != null) {
					result = new String(tmpDecrypt, "utf-8");
				}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}


    /**将二进制转换成16进制
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte buf[]) {
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < buf.length; i++) {
                    String hex = Integer.toHexString(buf[i] & 0xFF);
                    if (hex.length() == 1) {
                            hex = '0' + hex;
                    }
                    sb.append(hex.toUpperCase());
            }
            return sb.toString();
    }


    /**将16进制转换为二进制
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
            if (hexStr.length() < 1)
                    return null;
            byte[] result = new byte[hexStr.length()/2];
            for (int i = 0;i< hexStr.length()/2; i++) {
                    int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
                    int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
                    result[i] = (byte) (high * 16 + low);
            }
            return result;
    }

	/**
	 * 字符串是否为空
	 *
	 * @param
	 * @return 是或否
	 */
	public static boolean isEmpty(String str) {
		if (str == null) {
			return true;
		} else if (str.equals("") || str.equals("null")) {
			return true;
		} else {
			return false;
		}
	}


	public static void main(String args[]){
		System.out.println("start test");

		String skcs1 = "{\"username\":\"skcs1\",\"password\":\"czyj@123\",\"timestamp\":\"2020-07-28 16:22:00\"}";
		System.out.println(DESEncoder.encrypt(skcs1,"23546324"));

	}

}
