a36d2b57ff7b4c1dfd07e3b4b8db54c817f509fe.svn-base 1.9 KB
package com.thinkgem.jeesite.common.utils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

public class ApiUtil {

    /**
     * 获取签名
     *
     * @param params 参数集合不含 secretkey
     * @param rTime 验证接口的 时间戳
     * @param secret 验证接口的 secretkey
     * @return String
     */
    public static String getSign(Map<String, String> params, String rTime, String secret) {
        String sign = "";
        StringBuilder sb = new StringBuilder();
        Set<String> keySet = params.keySet();
        TreeSet<String> sortSet = new TreeSet<>(keySet);
        for (String key : sortSet) {
            sb.append(key).append(params.get(key));
        }
        sb.append(secret);
        try {
            // 得到Md5加密得到sign
            sign = byte2hex(getMd5Digest(sb.toString() + rTime));
        } catch (IOException e) {
            System.err.println("生成签名错误");
        }
        return sign;
    }

    /** md5生成字节对象转字符串 */
    private static String byte2hex(byte[] bytes) {
        StringBuilder sign = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(b & 0xFF);
            if (hex.length() == 1) {
                sign.append("0");
            }
            sign.append(hex.toUpperCase());
        }
        return sign.toString();
    }

    /** md5加密*/
    private static byte[] getMd5Digest(String data) throws IOException {
        byte[] bytes;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            bytes = md.digest(data.getBytes(StandardCharsets.UTF_8));
        } catch (GeneralSecurityException gse) {
            throw new IOException(gse);
        }
        return bytes;
    }

}