import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class SignatureUtil {
public SignatureUtil() {
}
public String createSignature(String method, String uri, Map<String, String> params, String secretKey) {
StringBuilder sb = new StringBuilder(1024);
sb.append(method.toUpperCase()).append('\n').append(uri).append('\n');
SortedMap<String, String> map = new TreeMap(params);//按照key自动排序
Iterator var7 = map.entrySet().iterator();
while(var7.hasNext()) {
Map.Entry<String, String> entry = (Map.Entry)var7.next();
String key = (String)entry.getKey();
String value = (String)entry.getValue();
sb.append(key).append('=').append(urlEncode(value)).append('&');
}
sb.deleteCharAt(sb.length() - 1);
return actualSignature(sb.toString(), secretKey);
}
public static String actualSignature(String inputStr, String secretKey) {
Mac hmacSha256 = null;
try {
hmacSha256 = Mac.getInstance("HmacSHA256");
SecretKeySpec secKey = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
hmacSha256.init(secKey);
} catch (NoSuchAlgorithmException var4) {
throw new RuntimeException("No such algorithm: " + var4.getMessage());
} catch (InvalidKeyException var5) {
throw new RuntimeException("Invalid key: " + var5.getMessage());
}
byte[] hash = hmacSha256.doFinal(inputStr.getBytes(StandardCharsets.UTF_8));
return byte2hex(hash);
}
private static String byte2hex(byte[] b) {
StringBuilder hs = new StringBuilder();
for(int n = 0; b != null && n < b.length; ++n) {
String temp = Integer.toHexString(b[n] & 255);
if (temp.length() == 1) {
hs.append('0');
}
hs.append(temp);
}
return hs.toString();
}
public static String urlEncode(String s) {
try {
return URLEncoder.encode(s, "UTF-8").replaceAll("\\+", "%20");
} catch (UnsupportedEncodingException var2) {
throw new IllegalArgumentException("UTF-8 encoding not supported!");
}
}
public static void main(String[] args) {
SignatureUtil signatureUtil = new SignatureUtil();
Map<String, String> params = new HashMap();
params.put("api_key", "xx");
long now = System.currentTimeMillis();
params.put("req_time", String.valueOf(now));
System.out.println("params = " + params);
String sign = signatureUtil.createSignature("GET", "xxx", params, "xx");
System.out.println("sign = " + sign);
}
}
HmacSHA256签名
最新推荐文章于 2024-04-23 18:52:22 发布