二. 签名认证机制
API密钥
| 名称 |
描述 |
| apiKey |
商户分配的apiKey |
| apiSecret |
商户分配的apiSecret,该密钥非常重要,请妥善保存,请勿泄漏,只用于生成签名,不需要作为参数传递 |
请求头
| 名称 |
必填 |
描述 |
| API-KEY |
Y |
商户分配的apiKey |
| API-SIGNATURE |
Y |
根据下述签名算法生成的签名 |
| API-TIMESTAMP |
Y |
发起请求时的UNIX毫秒级时间戳 |
| Content-Type |
N |
所有非GET请求都必须,且值为application/json |
签名算法
API-SIGNATURE 的值是对request_content +"&" + timestamp,通过密钥apiSecret,应用HMAC-SHA256签名算法而得到的。
其中:
- 对于GET请求:
所有非空请求参数按照参数名进行字典序排序,将排序后的参数按照参数名和参数值的格式拼接成一个字符串request_content。
如:request_content =
"param1=value1¶m2=value2¶m3=value3"
- 对于POST请求:
将请求体body转换成json字符串 得到request_content。
如:request_content = "{"fiatAmt":20,"fiatCurrency":"USD"}"
- timestamp的值与API-TIMESTAMP请求头相同,为毫秒级时间戳。
- 待签名字符串:resource = request_content + "&" + timestamp
代码示例
GET请求生成签名示例:
public static void main(String[] args) {
Map<String, String> map = new LinkedHashMap<>();
map.put("content", "12345");
map.put("name", "test");
long timestamp = LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli();
String sign = String.join("&", getSignContentForGET(map), String.valueOf(timestamp));
System.out.println(EncryptionUtils.HMACSHA256(sign, "apiSecret"));
}
private static String getSignContentForGET(Map<String, String> queryParams) {
StringBuilder sb = new StringBuilder();
TreeMap<String, String> treeMap = new TreeMap<>();
treeMap.putAll(queryParams);
for (Map.Entry<String, String> entry : treeMap.entrySet()) {
if (entry.getValue() != null) {
sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
}
}
String signStr = sb.toString();
signStr = signStr.subString(0, signStr.length() - 1);
return signStr;
}
POST请求生成签名示例:
public static void main(String[] args) {
Map<String, String> map = new LinkedHashMap<>();
map.put("content", "12345");
map.put("name", "test");
long timestamp = System.currentTimeMillis();
String sign = String.join("&", getSignContentForPost(map), String.valueOf(timestamp));
System.out.println(EncryptionUtils.HMACSHA256(sign, "apiSecret"));
}
private static String getSignContentForPost(Map<String, String> body) {
return JSON.toJSONString(body);
}
签名算法工具类:
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class EncryptionUtils {
public static String HMACSHA256(String data, String secretKey) {
try {
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(secretKey.getBytes("UTF-8"), "HmacSHA256");
sha256_HMAC.init(secret_key);
byte[] array = sha256_HMAC.doFinal(data.getBytes("UTF-8"));
StringBuilder sb = new StringBuilder();
for (byte item : array) {
sb.append(Integer.toHexString((item & 0xFF) | 0x100).subString(1, 3));
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}