package com.offcn.TestUnti;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Date;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * AES加密解密工具类
 *
 * @author yupeng
 */
public class AESUtils {

    //private static final Logger logger = LoggerFactory.getLogger(AESUtils.class);

    // 参数加密密码
    public static final String AES_PASSWORD_TEXT = "puhui888888";
    // token加密密码
    public static final String AES_PASSWORD_TOKEN = "puhui888888";
    public static final String FLAG = "!@#";

    /**
     * 生成当前时间点的加密token
     * Token的格式为uid加上时间
     * @param uid
     * @return
     */
    public static String generateToken(String uid) {
        StringBuffer tokenStr = new StringBuffer();
        long time = new Date().getTime();
        tokenStr.append(uid).append(FLAG).append(time);// 生成token
        String encrypTokenStr = encrypt(tokenStr.toString(), AES_PASSWORD_TOKEN); // token加密
        return encrypTokenStr;
    }

    /**
     * 通过加密token获取UID
     *
     * @author xiaobowen
     * @param encryptToken
     * @return uid
     */
    public static String getUID(String encryptToken) {
        String token = decrypt(encryptToken, AES_PASSWORD_TOKEN);
        return getUIDByToken(token);
    }

    /**
     * 通过加密token获取token时间
     *
     * @author gaozhenbao
     * @param encryptToken
     * @return time
     */
    public static String getTiime(String encryptToken) {
        String token = decrypt(encryptToken, AES_PASSWORD_TOKEN);
        return getTimeByToken(token);
    }

    public static String getUIDByToken(String token) {
        if (token == null)
            return null;
        String[] params = token.split(FLAG);
        if (params == null || params.length != 2) {
            return null;
        } else {
//        	logger.info("token为{}，解析为{}",token,params[0]);
            return params[0];
        }
    }

    public static String getTimeByToken(String token) {
        if (token == null)
            return null;
        String[] params = token.split(FLAG);
        if (params == null || params.length != 2) {
            return null;
        } else {
            return params[1];
        }
    }

    /**
     * 获取解密token
     *
     * @param decryTokenStr
     * @return
     */
    public static String analyzeToken(String decryTokenStr) {
        return decrypt(decryTokenStr, AES_PASSWORD_TOKEN);
    }
    /**
     * AES加密
     *
     * @author wangyaowei
     * @param userpassword    需要加密的密码
     * @return enpassword 	  AES加密后的密码
     */
    public static String encrypt(String userpassword){
        return encrypt(userpassword, AES_PASSWORD_TOKEN);
    }
    /**
     * AES加密
     *
     * @author yupeng
     * @param content
     *            需要加密的内容
     * @param password
     *            加密密码
     * @return
     */
    public static String encrypt(String content, String password) {
        if (content == null) {
            return null;
        }
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");// 提供AES密钥算法的（对称）密钥生成器
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(password.getBytes());
            kgen.init(128, secureRandom);
            SecretKey secretKey = kgen.generateKey();// 生成一个密钥

            // byte[] enCodeFormat = secretKey.getEncoded();//基本编码格式的密钥

            // SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
            byte[] byteContent = content.getBytes("utf-8");
            // System.out.println("key：" +
            // CommonUtils.parseByte2HexStr(key.getEncoded()));
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);// 初始化 加密模式
            byte[] result = cipher.doFinal(byteContent);
            String encryptResultStr = parseByte2HexStr(result);
            return encryptResultStr; // 加密 后的16进制
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * AES解密
     *
     * @author yupeng
     * @param content
     *            待解密内容（十六进制）
     * @param password
     *            解密密钥
     * @return
     */
    public static String decrypt(String content, String password) {
        return decrypt(parseHexStr2Byte(content), password);
    }

    /**
     * AES解密
     *
     * @author yupeng
     * @param content
     *            待解密内容
     * @param password
     *            解密密钥
     * @return
     */
    public static String decrypt(byte[] content, String password) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");// 提供AES密钥算法的（对称）密钥生成器
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(password.getBytes());
            kgen.init(128, secureRandom);
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
            cipher.init(Cipher.DECRYPT_MODE, key);// 初始化 解密模式
            byte[] result = cipher.doFinal(content);// 解密为16进制
            String resultStr = new String(result);// 将16进制转化为字符串
            return resultStr; // 解密
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将二进制转换成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;
    }
}

