package com.e6yun.project.sdk.api.utils;

import org.apache.commons.codec.digest.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.TreeMap;

/**
 * 计算签名工具类
 * @author Xue Xiang <xuexiang@e6yun.com>
 */
public final class SignUtils {

    /**
     * 计算签名
     * @param appKey
     * @param secretKey
     * @param param
     * @return
     */
    public static String sign(String appKey, String secretKey, Map<String, String> param) {
        // TreeMap默认根据key从小到大排序
        TreeMap<String, String> treeMap = new TreeMap(param);
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(secretKey);
        for(Map.Entry<String, String> entry : treeMap.entrySet()){
            stringBuilder.append(entry.getKey());
            stringBuilder.append(entry.getValue());
        }
        stringBuilder.append(secretKey);
        // 计算MD5摘要的原始字符串
        String rawStr = stringBuilder.toString();
        // 以UTF-8编码获取字符串的字节数组
        return DigestUtils.md5Hex(rawStr.getBytes(StandardCharsets.UTF_8));

    }
}
