接口加密原理
通过签名的方式,去做接口校验。
校验方式:上游提供密钥,下游通过密钥、请求对象和时间戳生成对应的签名(sign),将此时生成的sign放入到请求对象中传给上游,上游也通过以上方式获取到相同的sign进行比对。
方法一
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.apache.logging.log4j.util.Strings;
public final class SignUtil {
public SignUtil() {
}
public static String sign(final Map<String, Object> signMap, List<String> ignoredParamNames, String secret) throws NoSuchAlgorithmException {
try {
StringBuilder sb = new StringBuilder();
List<String> paramKeys = new ArrayList(signMap.size());
paramKeys.addAll(signMap.keySet());
Iterator var5;
String k;
if (ignoredParamNames != null && ignoredParamNames.size() > 0) {
var5 = ignoredParamNames.iterator();
while(var5.hasNext()) {
k = (String)var5.next();
paramKeys.remove(k);
}
}
paramKeys.sort(Comparator.comparing(String::toLowerCase));
sb.append(secret);
Object v;
for(var5 = paramKeys.iterator(); var5.hasNext(); sb.append(k.toLowerCase()).append(v)) {
k = (String)var5.next();
v = signMap.get(k);
if (v instanceof JSONObject || v instanceof JSONArray) {
v = o2SortedString(v);
}
if (v == null) {
v = "";
}
}
sb.append(secret);
MessageDigest md = MessageDigest.getInstance("SHA-1");
return byte2hex(md.digest(sb.toString().getBytes(StandardCharsets.UTF_8)));
} catch (Throwable var9) {