SignatureUtil.java 2.54 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
package pwc.taxtech.atms.common.util;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.TreeMap;

public class SignatureUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(SignatureUtil.class);
    public static final String SIGN_NONCE_STR = "nonceStr"; //随机数
    public static final String SIGN_TIMESTAMP = "timestamp"; //时间戳
14
    public static final String SIGN_APP_Id = "appId"; //应用Id
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
    public static final String SIGN_SIGNATURE = "signature"; //生成的签名
    public static final String SIGN_API = "api"; //接口地址
    public static final String SIGN_API_TOKEN = "apiToken"; //密钥
    public static final String AND = "=";
    public static final String SPLIT = "&";
    public static final int TIME_RANGE = 120;//2分钟

    /**
     * 生成签名
     *
     * @param key       密钥
     * @param api       请求地址
     * @param nonceStr  随机字符串
     * @param timestamp 时间戳
     * @return string
     */
    public static String generate(String key, String api, String nonceStr, String timestamp) {
        TreeMap<String, String> paramMap = new TreeMap<>();
        paramMap.put(SIGN_API_TOKEN, key);
        paramMap.put(SIGN_API, api);
        paramMap.put(SIGN_NONCE_STR, nonceStr);
        paramMap.put(SIGN_TIMESTAMP, timestamp);
        StringBuilder sb = new StringBuilder();
        paramMap.forEach((k, v) -> {
            sb.append(k).append(AND).append(v).append(SPLIT);
        });
        String tmp = sb.substring(0, sb.length() - 1);
        return DigestUtils.sha1Hex(tmp);
    }

    /**
     * 校验签名
     *
     * @param key       密钥
     * @param api       请求地址
     * @param nonceStr  随机字符串
     * @param timestamp 时间戳
     * @param signature 接收的签名
     * @return boolean
     */
    public static boolean validate(String key, String api, String nonceStr, String timestamp, String signature) {
        try {
57 58 59
            if (StringUtils.isAnyBlank(key, api, nonceStr, timestamp, signature)) {
                return false;
            }
60 61 62 63 64 65 66 67 68 69 70 71
            int now = (int) (System.currentTimeMillis() / 1000);
            int time = Integer.valueOf(timestamp);
            if (now - time <= TIME_RANGE) {
                return StringUtils.equals(signature, generate(key, api, nonceStr, timestamp));
            }
        } catch (Exception e) {
            LOGGER.error("invalid signature.", e);
        }
        return false;
    }

}