package com.fs.baidu.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.TreeMap;

@Service
public class SignService {
    private static final String AES_OFFSET = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";

    @SneakyThrows
    public String paramsSign(String secretKey, TreeMap<String, Object> map) {

        // 拼接成 json 字符串, 保证生成的json串字段顺序和Map中的顺序一致即可
        String json = JSONObject.toJSONString(map);
        // base64编码
        byte[] bytes = Base64.getEncoder()
                .encodeToString(json.getBytes(StandardCharsets.UTF_8))
                .getBytes(StandardCharsets.UTF_8);
        // AES加密 密钥为 应用sk 的前16位字符
        SecretKey keyAES = AESUtils.loadKeyAES(secretKey.substring(0, 16));
        return AESUtils.encryptAES(bytes, keyAES, AES_OFFSET);
    }
}