package com.thinkunion.park.service.common.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Arrays;
import java.util.Base64;
import java.util.Map;
import java.util.Set;
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";
    public static final String DEFAULT_DEVICE_SECRET = "152vkd43!@#cdsg3";
    /**
     * 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);
    }


    /**
     *
     * @param data 待签名数据
     * @return 待签名的字符串
     */
    public static String getSignatureContent(final Map<String, String> data) {
        Set<String> keySet = data.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        for (String k : keyArray) {
            // 参数key为 sign 则跳过，（sign 不参与签名）
            if ("sign".equals(k)) {
                continue;
            }
            if (sb.length() > 0) {
                sb.append("&");
            }
            sb.append(k).append("=").append(data.get(k).trim());
        }
        return sb.toString();
    }
}