服务签名验证使用

(1)headers中要含有appId、sign、ts

header部分参数
备注
appId 向crm团队申请appId和secretKey
sign

sign由appId+secretKey+ts+参数顺序化字符串拼接成源串signOrigin,源串通过

ApiSecuritySHA.sha256(secretKey,signOrigin)进行加密得到sign

ts 时间戳,单位秒


(2)ApiSecuritySHA.sha256加密算法

import java.nio.charset.StandardCharsets;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;

public class ApiSecuritySHA {
    private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
    private static final String HMAC_SHA256_ALGORITHM = "HmacSHA256";

    public ApiSecuritySHA() {
    }

    public static String sha256(String key, String msg) {
        try {
            Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
            SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
            sha256_HMAC.init(secret_key);
            byte[] array = sha256_HMAC.doFinal(msg.getBytes());
            StringBuilder sb = new StringBuilder();
            byte[] var6 = array;
            int var7 = array.length;

            for(int var8 = 0; var8 < var7; ++var8) {
                byte item = var6[var8];
                sb.append(Integer.toHexString(item & 255 | 256), 1, 3);
            }

            return sb.toString().toUpperCase();
        } catch (Exception var10) {
            throw new RuntimeException(var10);
        }
    }

    public static String sha1(String key, String data) {
        try {
            SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA1");
            Mac sha1_HMAC = Mac.getInstance("HmacSHA1");
            sha1_HMAC.init(secret_key);
            byte[] array = sha1_HMAC.doFinal(data.getBytes());
            String hash = Base64.encodeBase64String(array);
            return hash;
        } catch (Exception var6) {
            throw new RuntimeException(var6);
        }
    }
}

 

posted @ 2022-06-16 10:55  姚春辉  阅读(82)  评论(0编辑  收藏  举报