package com.hai.common.security;

import java.nio.charset.Charset;
import java.security.Key;
import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

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

import org.apache.commons.codec.binary.Base64;
//import org.apache.commons.lang3.RandomStringUtils;


import com.thoughtworks.xstream.core.util.Base64Encoder;

public class DesUtil {

    public static final String ALGORITHM_DES = "DES/CBC/PKCS5Padding";

    /**
     * DES算法,加密
     *
     * @param data
     *            待加密字符串
     * @param key
     *            加密私钥,长度不能够小于8位
     * @return 加密后的字节数组,一般结合Base64编码使用
     * @throws CryptException
     *             异常
     */
    public static byte[] encode(String key, String data) throws Exception {
        return encode(key, data.getBytes());
    }

    /**
     * DES算法,加密
     *
     * @param data
     *            待加密字符串
     * @param key
     *            加密私钥,长度不能够小于8位
     * @return 加密后的字节数组,一般结合Base64编码使用
     * @throws CryptException
     *             异常
     */
    public static byte[] encode(String key, byte[] data) throws Exception {
        try {
            DESKeySpec dks = new DESKeySpec(key.getBytes());

            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            // key的长度不能够小于8位字节
            Key secretKey = keyFactory.generateSecret(dks);
            Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
            IvParameterSpec iv = new IvParameterSpec(key.getBytes());
            AlgorithmParameterSpec paramSpec = iv;
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);

            byte[] bytes = cipher.doFinal(data);
            return bytes;
            // return byte2HexStr(bytes);
            // return byte2hex(new String(bytes));
            // return new String(new BASE64Encoder().encode(bytes));
            // return new String(bytes);
        } catch (Exception e) {
            throw new Exception(e);
        }
    }

    /**
     * DES算法,解密
     *
     * @param data
     *            待解密字符串
     * @param key
     *            解密私钥,长度不能够小于8位
     * @return 解密后的字节数组
     * @throws Exception
     *             异常
     */
    public static byte[] decode(String key, byte[] data) throws Exception {
        try {
            // SecureRandom sr = new SecureRandom();
            DESKeySpec dks = new DESKeySpec(key.getBytes());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            // key的长度不能够小于8位字节
            Key secretKey = keyFactory.generateSecret(dks);
            Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
            IvParameterSpec iv = new IvParameterSpec(key.getBytes());
            AlgorithmParameterSpec paramSpec = iv;
            cipher.init(Cipher.DECRYPT_MODE, secretKey, paramSpec);
            return cipher.doFinal(data);
        } catch (Exception e) {
            throw new Exception(e);
        }
    }

    /**
     * 获取编码后的值
     *
     * @param key
     * @param data
     * @return
     * @throws Exception
     */
    public static String decode(String key, String data) {
        byte[] datas;
        String value = null;
        try {

            datas = decode(key, new Base64Encoder().decode(data));

            value = new String(datas);
        } catch (Exception e) {
            value = "";
        }
        return value;
    }

    public static String byte2HexStr(byte[] b) {
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1)
                hs = hs + "0" + stmp;
            else
                hs = hs + stmp;
            // if (n<b.length-1) hs=hs+":";
        }
        return hs;
    }

    public static String triDesEncrypt(String input, String desKey, String desIv) {
        Cipher cipher = null;
        try {
            SecureRandom sr = new SecureRandom();
            DESedeKeySpec dks = new DESedeKeySpec(desKey.getBytes("UTF-8"));
            SecretKeyFactory keyFactory = SecretKeyFactory
                    .getInstance("DESede");
            Key key = keyFactory.generateSecret(dks);
            IvParameterSpec iv = new IvParameterSpec(desIv.getBytes("UTF-8"));
            cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
            cipher.init(1, key, iv, sr);
            byte[] array = cipher.doFinal(input.getBytes("UTF-8"));

            return Base64.encodeBase64String(array);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String triDesDecrypt(String input, String desKey, String desIv) {
        Cipher cipher = null;
        try {
            SecureRandom sr = new SecureRandom();
            DESedeKeySpec dks = new DESedeKeySpec(desKey.getBytes("UTF-8"));
            SecretKeyFactory keyFactory = SecretKeyFactory
                    .getInstance("DESede");
            SecretKey key = keyFactory.generateSecret(dks);
            IvParameterSpec iv = new IvParameterSpec(desIv.getBytes("UTF-8"));
            cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
            cipher.init(2, key, iv, sr);
            byte[] decoded = Base64.decodeBase64(input);
            byte[] array = cipher.doFinal(decoded);
            return new String(array, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static byte[] encode(String key, String data, Charset charset)
            throws Exception {
        return encode(key, data.getBytes(charset));
    }

    public static String decode(String key, String data, Charset charset) {
        byte[] datas;
        String value = null;
        try {

            datas = decode(key, new Base64Encoder().decode(data));

            value = new String(datas, charset);
        } catch (Exception e) {
            value = "";
        }
        return value;
    }

    /**
     * des加密,返回string类型,指定编码集
     *
     * @time 2018-11-6 16:08:27
     * @author Lxm
     * @param data
     * @param charset
     * @param key
     * @return
     * @throws Exception
     */
    public static String encode(String data, Charset charset, String key)
            throws Exception {

        byte[] bt = encode(key, data.getBytes(charset));

        // return new String(bt, charset);
        String rs = new Base64Encoder().encode(bt);
        return rs;
    }

/*    public static String quickDecode(String key, String data) throws Exception {
        return quickDecode(key, data, "UTF-8");
    }

    public static String quickDecode(String key, String data, String charSet)
            throws Exception {
        return new String(DesUtil.decode(key, HexUtil.hexStr2Bytes(data)),
                charSet);
    }*/


    public static void main(String[] args) throws Exception {
        // String ke = RandomStringUtils
        // .random(8,
        // "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890!@#$%^&*");
        // System.out.println(ke);
        // String key = "abcdefgh";
        // String data =
        // "<?xml version=\"1.0\"?><RequestData><cardNo>8800030132003900701</cardNo><jourId>1231204573498573945</jourId><mercCode>000001</mercCode><terminalId>8800030165000100040</terminalId><terminalTime>2016-07-28 13:20:50</terminalTime><tranAmt>150</tranAmt></RequestData>";
        // String s = HexUtil.byte2HexStr(DesUtil.encode(key, data));
        // System.err.println(s);
        // System.err.println(DesUtil.encode(key, data.getBytes()).length);
        // String s2 = new String(DesUtil.decode(key, HexUtil.hexStr2Bytes(s)));
        // System.err.println(s2);

        // String s = encode("123", Charset.forName("GBK"), "d0fb65e5");
        // System.out.println(s);
        //
        // String e = decode("d0fb65e5", "258946d6143e30f9",
        // Charset.forName("UTF-8"));
        // System.out.println(e);

        /*String s = encode("中国", Charset.forName("UTF-8"),"12345678");
        System.out.println(s);*/
        //String data = "T3xbPEKEXV9+CbBw8D1B+N2jk8xwa55s0Bde48c49YDwYfnUdBVz6Kj4HS2oCA1TTiqJkCUIYa5ckMhJeByBCAMsqu21LmFjb/hdW0y1Tt0Wk5PqmO8FAg==";
        String data = "T3xbPEKEXV9+CbBw8D1B+N2jk8xwa55s0Bde48c49YBr4/b4yBwN2FIVZZn+Xg9KQTDoTCLu3YtByaWh7zPmdcpBr9FGARduhPrwSnYTFJ0VVVSK/UzPWdHN2YYd4yHGQRJ2HEr/1egt2JUHpWr0JA==";
/*        {
            "success": true,
                "message": "ok",
                "cards": [{
            "cardNo": "8800030115015107746"
        }, {
            "cardNo": "8800030115015119428"
        }, {
            "cardNo": "8800030128003170055"
        }, {
            "cardNo": "8800030132003656709"
        }, {
            "cardNo": "8800030132004014510"
        }, {
            "cardNo": "8800031104000000248"
        }]
        }*/

        String a = decode("F8E91A3C", data,Charset.forName("UTF-8"));
        System.out.println(a);
        System.out.println("完成");
    }
}