package com.sptg.common.core.util;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;

/**
 * title: AesEncryptionUtil
 * package: com.sptg.common.core.util
 * description: Aes对称加密工具类
 *
 *                  
 *               
 */
public final class AesEncryptionUtil {

    private static final BASE64Encoder BASE_64_ENCODER = new BASE64Encoder();

    /**
     * 功能描述: Aes对称加密
     * @param secretKey 密钥
     * @param content 加密内容,明文
     * @return 密文
     *                  
     *                     
     */
    public static String aesEncryption(String secretKey,String content)throws Exception{
        Cipher cipher = AesEncryptionUtil.generateCipher(secretKey,Cipher.ENCRYPT_MODE);
        //  获取加密内容的字节数组
        byte [] byteEncode = content.getBytes(StandardCharsets.UTF_8);
        //  将数据进行加密
        byte [] byteAES = cipher.doFinal(byteEncode);
        //  将加密内容进行base64编码
        return BASE_64_ENCODER.encode(byteAES);
    }

    private static final BASE64Decoder BASE_64_DECODER = new BASE64Decoder();

    /**
     * 功能描述: Aes解密
     * @param secretKey 密钥
     * @param content 揭秘内容,密文
     * @return 明文
     *                  
     *                     
     */
    public static String aesDecrypt(String secretKey,String content)throws Exception{
        //  构建密码器
        Cipher cipher = AesEncryptionUtil.generateCipher(secretKey,Cipher.DECRYPT_MODE);
        //  将编码后的数据解码为字节数组
        byte [] byteAES = BASE_64_DECODER.decodeBuffer(content);
        //  解密
        byte[] byteEncode = cipher.doFinal(byteAES);
        return new String(byteEncode, StandardCharsets.UTF_8);
    }

    /**
     * Aes 算法
     */
    private static final String AES = "AES";

    /**
     * 功能描述: 构建密码器,指定为AES算法
     * @param encodeRule 密钥
     * @param isEncryption 1:加密,2:解密
     * @return Cipher
     *                  
     *                     
     */
    private static Cipher generateCipher(String encodeRule,int isEncryption)throws Exception{
        //  构造密钥生成器,指定为AES算法
        KeyGenerator keyGenerator = KeyGenerator.getInstance(AES);
        //  根据加密规则初始化密钥生成器
        keyGenerator.init(128,new SecureRandom(encodeRule.getBytes()));
        //  产生原始对称密钥
        SecretKey secretKey = keyGenerator.generateKey();
        //  获取密钥的字节数组
        byte[] encoded = secretKey.getEncoded();
        //  根据字节数组生成AES密钥
        SecretKey key = new SecretKeySpec(encoded, AES);
        //  构建密码器,指定为AES算法
        Cipher cipher = Cipher.getInstance(AES);
        //  初始化密码器
        cipher.init(isEncryption, key);
        return cipher;
    }

}
