package com.yuchen.saas.torch.api.util;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.logging.Level;
import java.util.logging.Logger;

public class AES {

    private static final String KEY_ALGORITHM = "AES";

    // 加密算法
    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";

    /**
     * AES 加密操作
     */
    public static String encrypt(String data, String deviceSecret) {
        try {
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);// 创建密码器
            byte[] byteContent = data.getBytes("utf-8");
            cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(deviceSecret));// 初始化为加密模式的密码器
            byte[] result = cipher.doFinal(byteContent);// 加密
            return Base64.getEncoder().encodeToString(result);// 通过Base64转码返回
        } catch (Exception ex) {
            Logger.getLogger(AES.class.getName()).log(Level.SEVERE, null, ex);
        }

        return null;
    }

    /**
     * AES 加密操作
     */
    public static String encrypt(byte[] data, String deviceSecretKey) {
        try {
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);// 创建密码器
            cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(deviceSecretKey));// 初始化为加密模式的密码器
            byte[] result = cipher.doFinal(data);// 加密
            return Base64.getEncoder().encodeToString(result);// 通过Base64转码返回
        } catch (Exception ex) {
            Logger.getLogger(AES.class.getName()).log(Level.SEVERE, null, ex);
        }

        return null;
    }

    /**
     * AES 解密操作
     */
    public static String decrypt(String data, String deviceSecretKey) {

        try {

            // 实例化
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);

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

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

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

        return null;
    }

    /**
     * 获取加密秘钥
     */
    private static SecretKeySpec getSecretKey(final String deviceSecretKey) {
        byte[] enCodeFormat = deviceSecretKey.getBytes();
        return new SecretKeySpec(enCodeFormat, KEY_ALGORITHM);
    }

    public static void main(String[] args) {
        System.out.println(encrypt("1668795245653372929", "yuchenkeji258369"));
        System.out.println(decrypt("FdPWhMplo1/EycuZpnBgCrGGNzNeNvQrRLU1838adyU=", "yuchenkeji369258"));
    }
}