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

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.Security;
import java.util.logging.Level;
import java.util.logging.Logger;

public class AESUtil{
    private static final String KEY_ALGORITHM = "AES";
    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/CBC/PKCS7Padding";//默认的加密算法
    /**
     * mysql默认取秘钥的ascii编码前16位
     */
    public static String MYSQL_ENC_KEY = "jpsoft8121234888";


    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    /**
     * AES 加密操作，注意要先替换jre/lib/security/local_policy.jar和US_export_policy.jar，否则会报keysize不对
     * @param content 待加密内容
     * @param key 加密密钥
     * @return 返回Base64转码后的加密数据
     */
    public static String encrypt(String content, String key) {
        try {
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);// 创建密码器

            byte[] byteContent = content.getBytes("utf-8");
            IvParameterSpec ivParameterSpec = createIV(key);

            cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(key),ivParameterSpec);// 初始化为加密模式的密码器

            byte[] result = cipher.doFinal(byteContent);// 加密

            System.out.println(cipher.getBlockSize());

            return Base64.encode(result);//通过Base64转码返回

        } catch (Exception ex) {
            Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex);
        }

        return null;
    }

    /**
     * AES 解密操作
     *
     * @param content
     * @param key
     * @return
     */
    public static String decrypt(String content, String key) {

        try {
            //实例化
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            IvParameterSpec ivParameterSpec = createIV(key);

            //使用密钥初始化，设置为解密模式
            cipher.init(Cipher.DECRYPT_MODE, getSecretKey(key),ivParameterSpec);

            //执行操作
            byte[] result = cipher.doFinal(Base64.decode(content));

            return new String(result, "utf-8");
        } catch (Exception ex) {
            Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex);
        }

        return null;
    }

    // 创建初始化向量, 长度为16bytes, 向量的作用其实就是salt
    private static IvParameterSpec createIV(String key) throws UnsupportedEncodingException {
        byte[] src = key.getBytes("UTF-8");

        if (src.length < 16) {
            throw new RuntimeException("无法从Key中获取偏移量!");
        }

        byte[] bs = new byte[16];
        for (int i=0; i<16; i++){
            bs[i] = src[i];
        }

        return new IvParameterSpec(bs);
    }

    /**
     * 生成加密秘钥
     *
     * @return
     */
    private static SecretKeySpec getSecretKey(final String key) throws UnsupportedEncodingException {
        //返回生成指定算法密钥生成器的 KeyGenerator 对象
//        KeyGenerator kg = null;
//
//        try {
//            kg = KeyGenerator.getInstance(KEY_ALGORITHM);
//
//            //AES 要求密钥长度为 256
//            kg.init(256, new SecureRandom(key.getBytes("UTF-8")));
//
//            //生成一个密钥
//            SecretKey secretKey = kg.generateKey();
//
//            return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);// 转换为AES专用密钥
//        } catch (Exception ex) {
//            Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex);
//        }

        SecretKeySpec keySpec = new SecretKeySpec(key.getBytes("UTF-8"), KEY_ALGORITHM);

        return keySpec;
    }

    public static void main(String[] args) {
        String content = "421002198311131816";
        String key = "534a33e888b001a246b635b76e42d0dd";

        //g5mIt+8LgfpLWpPOXg1vyl7j1jv+wN3vwIb6wdpir5M=
        String enc = encrypt(content,key);

        System.out.println(enc);
    }
}