更新时间:2022-07-29 GMT+08:00
分享

签名生成方法

Jwt测试工具:https://jwt.io/

Java代码参考样例:

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class TokenSignature {
    private static String ACCESS_KEY = "*********************************WmXW2UKSU0=";
 
    /***
     * 生成入会token
     *
     * @param accessKey accessKey
     * @param paramsMap paramsMap
     * @return token
     */
    public static String getToken(String accessKey, Map<String, ?> paramsMap) throws Exception {
        String signature = generateResponseBodySignature(accessKey, paramsMap);
        String bodyStr = getBody(paramsMap);
        String token = bodyStr + "@#@" + signature;
        return Base64.getEncoder().encodeToString(token.getBytes());
    }
    private static String getBody(Map<String, ?> paramsMap) {
        String result = "{\"timeStamp\":" + paramsMap.get("timeStamp") + ",\"role\":\"" + paramsMap.get("role")
                + "\",\"port\":\"" + paramsMap.get("port") + "\",\"appId\":\"" + paramsMap.get("appId")
                + "\",\"host\":\"" + paramsMap.get("host") + "\",\"tenantId\":\"" + paramsMap.get("tenantId")
                + "\",\"userId\":\"" + paramsMap.get("userId") + "\",\"channelId\":\"" + paramsMap.get("channelId")
                + "\"}";
        return result;
    }
    /**
     * 参数验签
     *
     * @param accessKey accessKey
     * @param paramsMap paramsMap
     * @return String
     * @throws NoSuchAlgorithmException NoSuchAlgorithmException
     * @throws InvalidKeyException      InvalidKeyException
     */
    public static String generateResponseBodySignature(String accessKey, Map<String, ?> paramsMap)
            throws NoSuchAlgorithmException, InvalidKeyException {
        Map<String, Object> sortedMap = new TreeMap<>(paramsMap);
        sortedMap.remove("authToken");
        String timeStamp = getMapValue(paramsMap, "timeStamp");
        StringBuilder strBuffer = new StringBuilder();
        Set<String> keySet = sortedMap.keySet();
        for (String key : keySet) {
            String value = getMapValue(sortedMap, key);
            strBuffer.append("&").append(key).append("=").append(value);
        }
        // 修正消息体,去除第一个参数前面的&
        String reqParams = strBuffer.toString().substring(1);
        String key = accessKey + timeStamp;
        return generateResponseBodySignature(key, reqParams);
    }
    private static String generateResponseBodySignature(String key, String body)
            throws InvalidKeyException, NoSuchAlgorithmException, IllegalStateException {
        return Base64.getEncoder().encodeToString(hmacSHA256(key, body));
    }
    private static byte[] hmacSHA256(String macKey, String macData)
            throws NoSuchAlgorithmException, InvalidKeyException, IllegalStateException {
        SecretKeySpec secret = new SecretKeySpec(macKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(secret);
        return mac.doFinal(macData.getBytes(StandardCharsets.UTF_8));
    }
    private static String getMapValue(Map<String, ?> paramsMap, String key) {
        Object value = paramsMap.get(key);
        if (value instanceof List) {
            if (((List) value).size() > 0) {
                return ((List) value).get(0).toString();
            }
        }
        return value != null ? value.toString() : null;
    }
    public static void main(String[] args) throws Exception {
        String userId = "12123123123123";
        String channelId = "222507302531141";
        String host = "11.22.33.44";
        String port = "443";
        String role = "1";
        String tenantId = "2012";
        String appId = "****************iEjCfpGtMzlZPM0T";
        Long timeStamp = System.currentTimeMillis();
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("userId", userId);
        paramsMap.put("channelId", channelId);
        paramsMap.put("host", host);
        paramsMap.put("port", port);
        paramsMap.put("role", role);
        paramsMap.put("tenantId", tenantId);
        paramsMap.put("appId", appId);
        paramsMap.put("timeStamp", timeStamp);
        String token = getToken(ACCESS_KEY, paramsMap);
        System.out.println("token:\n" + token);
    }
}

相关文档