package vip.xiaonuo.biz.core.sign.utils;

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

/**
 * MD5 sign签名校验宇生成工具
 */
public class GenerateSignatureUtil {

    public static final String FIELD_SIGN = "sign";

    /**
     * 判断签名是否正确，必须包含sign字段，否则返回false。
     *
     * @param data Map类型数据
     * @param key  API密钥
     * @return 签名是否正确
     * @throws Exception
     */
    public static boolean isSignatureValid(Map<String, String> data, String key) {
        if (!data.containsKey(FIELD_SIGN)) {
            return false;
        }
        String sign = data.get(FIELD_SIGN);
        return generateSignature(data, key).equals(sign);
    }

    public static String generateSignature(final Map<String, String> data, String key) {
        try {
            Set<String> keySet = data.keySet();
            String[] keyArray = keySet.toArray(new String[keySet.size()]);
            Arrays.sort(keyArray);
            StringBuilder sb = new StringBuilder();
            for (String k : keyArray) {
                if (k.equals(FIELD_SIGN)) {
                    continue;
                }
                // 参数值为空，则不参与签名
                if (data.get(k).trim().length() > 0)  {
                    sb.append(k).append("=").append(data.get(k).trim()).append("&");
                }
            }
            return MD5.md5(sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
