Java
<pre>
<code>package com.pingan.palcoud.test;
import com.pingan.pacloud.common.utils.IdUtil;
import org.apache.commons.codec.binary.Base64;
import org.junit.Test;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
public class ApiSignatureDemo {
@Test
public void apiSignatureDemo() {
// 请求的url
String url = "https://api.ocftcloud.com/api/v1";
// 配置AccessKey,替换此处即可
String accessKeyId = "用户的AccessKeyId";
String accessKeySecret = "用户的AccessKeySecret";
// 构造请求参数
Map<String, String> paramMap = new HashMap<>();
//公共参数,这部分参数取值基本固定,只需替换accessKeyId
paramMap.put("version", "2017-01-01");
paramMap.put("signatureMethod", "HMAC-SHA256");
paramMap.put("signatureVersion", "1.0");
paramMap.put("timestamp", Long.toString(System.currentTimeMillis()));
paramMap.put("signatureNonce", Long.toString(IdUtil.randomLong()));
paramMap.put("accessKeyId", accessKeyId);
// 业务参数,以获取操作审计记录为例
paramMap.put("Action", "ListBizLogs");
paramMap.put("PageNumber", "1");
paramMap.put("PageSize", "10");
paramMap.put("startTime", "2019-01-13 00:00:00");
// 获取要被签名的参数串,参数要做特殊处理
String paramStrToSign = prepareParamStrToSign(paramMap);
// 对参数进行签名
String signature = getParamSignature(accessKeySecret, paramStrToSign);
paramMap.put("signature", signature);
// 拼接完整的请求参数串
String requestParamStr = getRequestParamStr(paramMap);
// 拼接完整的请求url
String finalRequestUrl = url + "?" + requestParamStr;
System.out.println(finalRequestUrl);
// TODO 使用各类请求工具发起请求,具体实现略
//建议使用RestTemplete进行请求时,使用URI uri = URI.create(url)替代String类型的url;避免RestTemplate url中包含“%”被转义成“ %25”
}
private String getRequestParamStr(Map<String, String> paramMap) {
Iterator<Map.Entry<String, String>> iterator = paramMap.entrySet().iterator();
StringBuilder paramStrBuilder = new StringBuilder();
while(iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
String paramName = entry.getKey();
String paramValue = entry.getValue();
paramStrBuilder.append(paramName).append("=").append(paramValue).append("&");
}
return paramStrBuilder.toString().substring(0, paramStrBuilder.length() - 1);
}
private String prepareParamStrToSign(Map<String, String> paramMap) {
List<String> paramToSignList = new ArrayList<>();
Iterator<Map.Entry<String, String>> iterator = paramMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
String paramName = entry.getKey();
String paramValue = entry.getValue();
try {
String encodedParamValue = URLEncoder.encode(paramValue, "UTF-8").replace("+", "%20")
.replace("*", "%2A")
.replace("%7E", "~")
.replace(":", "%3A")
.replace(",", "%2C");
paramToSignList.add(paramName.toLowerCase() + "=" + encodedParamValue.toLowerCase());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
Collections.sort(paramToSignList);
StringBuilder paramStrToSignBuilder = new StringBuilder();
for (int i = 0; i < paramToSignList.size(); ++i) {
paramStrToSignBuilder.append(paramToSignList.get(i));
if (i != paramToSignList.size() - 1) {
paramStrToSignBuilder.append("&");
}
}
return paramStrToSignBuilder.toString();
}
private String getParamSignature(String accessKeySecret, String paramStrToSign) {
Mac mac = null;
try {
mac = Mac.getInstance("HmacSHA256");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
SecretKeySpec keySpec = new SecretKeySpec(accessKeySecret.getBytes(), "HmacSHA256");
try {
mac.init(keySpec);
} catch (InvalidKeyException e) {
e.printStackTrace();
}
mac.update(paramStrToSign.getBytes());
byte[] encryptedBytes = mac.doFinal();
return Base64.encodeBase64String(encryptedBytes).replace("+", "%2B").replace("\r\n", "");
}
}
</code></pre>
<p> </p>
提交成功!非常感谢您的反馈,我们会继续努力做到更好!