package com.cyksj.common.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;
import java.util.Map;

@Slf4j
public class SignatureUtils {
	// 生成HMAC-SHA256签名
	public static String generateSignature(Map<String, String> map, String secret) throws Exception {
		// 将map的key按ASCii升序排列
		String[] keys = map.keySet().toArray(new String[0]);
		Arrays.sort(keys);

		// 将参数有序排列
		StringBuilder str = new StringBuilder();
		for (int i = 0; i < keys.length; i++) {
			if (StringUtils.equals(keys[i], "sign")) {
				continue;
			}
			if (StringUtils.isBlank(map.get(keys[i]))) {
				continue;
			}
			str.append(keys[i]).append("=").append(map.get(keys[i])).append("&");
		}
		str.append("key=").append(secret);
		log.info("签名验证, 排列好的有序字符串: {}", str.toString());

		String sign = Codec.DoDigest.custom().setAlgorithm(Codec.DoDigest.Algorithm.MD5).setStringData(str.toString()).toHexString().toUpperCase();
		return sign;
	}
}