package com.bonus.sgzb.common.security.utils;

import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;
import com.alibaba.fastjson2.JSONObject;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class GetTokenByAppKey {
//    public static void main(String[] args) {
//        String appKey = "abc123";
//        String aesKey = "abcdefghijklmnop";
//        String token = getToken(appKey, aesKey);
//        System.err.println(token);
//    }

    /**
     * 获取Token
     * @return Token
     * appKey、aesKey联系智慧工程系统提供
     */
    public static String getToken(String appKey, String aesKey) {
        Map<String, Object> signatureMap = new HashMap<String, Object>();
        signatureMap.put("appKey", appKey);
        signatureMap.put("timestamp", String.valueOf(System.currentTimeMillis()));
        Iterator<String> iterator = signatureMap.keySet().iterator();
        //Map 转成  JSONObject 字符串
        JSONObject jsonObj = new JSONObject(signatureMap);
        String jsonStr = jsonObj.toJSONString();

        AES aes = new AES(Mode.ECB, Padding.PKCS5Padding, aesKey.getBytes());
        byte[] aesByte = aes.encrypt(jsonStr.getBytes(StandardCharsets.UTF_8));
        String token = byteToHex(aesByte);
        return token;
    }

    public static String byteToHex(byte[] bytes) {
        String strHex = "";
        StringBuilder sb = new StringBuilder("");
        for (int n = 0; n < bytes.length; n++) {
            strHex = Integer.toHexString(bytes[n] & 0xFF);
            sb.append((strHex.length() == 1) ? "0" + strHex : strHex); // 每个字节由两个字符表示，位数不够，高位补0
        }
        return sb.toString().trim();
    }
}