293
阿里云
签名算法参考__OpenAPI使用手册_云监控-阿里云
以下是Java版签名算法参考和C++版签名算法参考
Java签名算法参考
签名代码:UrlUtil.java
import java.net.URLEncoder;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
public class UrlUtil {
private static Logger logger = Logger.getLogger(UrlUtil.class);
private final static String CHARSET_UTF8 = "utf8";
/**
*
* @param url
* @return
*/
public static String urlEncode(String url) {
if (!StringUtils.isEmpty(url)) {
try {
url = URLEncoder.encode(url, "UTF-8");
} catch (Exception e) {
logger.warn("Url encode error:" + e.getMessage());
}
}
return url;
}
public static String generateQueryString(Map<String, String> params, boolean isEncodeKV) {
StringBuilder canonicalizedQueryString = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
if (isEncodeKV)
canonicalizedQueryString.append(percentEncode(entry.getKey())).append("=")
.append(percentEncode(entry.getValue())).append("&");
else
canonicalizedQueryString.append(entry.getKey()).append("=")
.append(entry.getValue()).append("&");
}
if (canonicalizedQueryString.length() > 1) {
canonicalizedQueryString.setLength(canonicalizedQueryString.length() - 1);
}
return canonicalizedQueryString.toString();
}
public static String percentEncode(String value) {
try {
// 使用URLEncoder.encode编码后,将"+","*","%7E"做替换即满足 API规定的编码规范
return value == null ? null : URLEncoder.encode(value, CHARSET_UTF8)
.replace("+", "%20").replace("*", "%2A").replace("%7E", "~");
} catch (Exception e) {
//不可能发生的异常
}
return "";
}
}
SignatureUtils.java
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Map;
import java.util.TreeMap;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
public class SignatureUtils {
private final static String CHARSET_UTF8 = "utf8";
private final static String ALGORITHM = "UTF-8";
private final static String SEPARATOR = "&";
public static Map<String, String> splitQueryString(String url)
throws URISyntaxException, UnsupportedEncodingException {
URI uri = new URI(url);
String query = uri.getQuery();
final String[] pairs = query.split("&");
TreeMap<String, String> queryMap = new TreeMap<String, String>();
for (String pair : pairs) {
final int idx = pair.indexOf("=");
final String key = idx > 0 ? pair.substring(0, idx) : pair;
if (!queryMap.containsKey(key)) {
queryMap.put(key, URLDecoder.decode(pair.substring(idx + 1), CHARSET_UTF8));
}
}
return queryMap;
}
public static String generate(String method, Map<String, String> parameter,
String accessKeySecret) throws Exception {
String signString = generateSignString(method, parameter);
System.out.println("signString---"+signString);
byte[] signBytes = hmacSHA1Signature(accessKeySecret + "&", signString);
String signature = newStringByBase64(signBytes);
System.out.println("signature---"+signature);
if ("POST".equals(method))
return signature;
return URLEncoder.encode(signature, "UTF-8");
}
public static String generateSignString(String httpMethod, Map<String, String> parameter)
throws IOException {
TreeMap<String, String> sortParameter = new TreeMap<String, String>();
sortParameter.putAll(parameter);
String canonicalizedQueryString = UrlUtil.generateQueryString(sortParameter, true);
if (null == httpMethod) {
throw new RuntimeException("httpMethod can not be empty");
}
StringBuilder stringToSign = new StringBuilder();
stringToSign.append(httpMethod).append(SEPARATOR);
stringToSign.append(percentEncode("/")).append(SEPARATOR);
stringToSign.append(percentEncode(canonicalizedQueryString));
return stringToSign.toString();
}
public static String percentEncode(String value) {
try {
return value == null ? null : URLEncoder.encode(value, CHARSET_UTF8)
.replace("+", "%20").replace("*", "%2A").replace("%7E", "~");
} catch (Exception e) {
}
return "";
}
public static byte[] hmacSHA1Signature(String secret, String baseString)
throws Exception {
if (StringUtils.isEmpty(secret)) {
throw new IOException("secret can not be empty");
}
if (StringUtils.isEmpty(baseString)) {
return null;
}
Mac mac = Mac.getInstance("HmacSHA1");
SecretKeySpec keySpec = new SecretKeySpec(secret.getBytes(CHARSET_UTF8), ALGORITHM);
mac.init(keySpec);
return mac.doFinal(baseString.getBytes(CHARSET_UTF8));
}
public static String newStringByBase64(byte[] bytes)
throws UnsupportedEncodingException {
if (bytes == null || bytes.length == 0) {
return null;
}
return new String(Base64.encodeBase64(bytes, false), CHARSET_UTF8);
}
public static void main(String[] args) {
String str = "GET&%2F&AccessKeyId%3DCdwKFNmXeHJuMOrT%26Action%3DDescribeInstances%26Format%3DJSON%26RegionId%3Dcn-hangzhou%26SignatureMethod%3DHMAC-SHA1%26SignatureNonce%3D9fdf20f2-9a32-4872-bcd4-c6036082ebef%26SignatureVersion%3D1.0%26Timestamp%3D2015-12-21T09%253A05%253A44Z%26Version%3D2014-05-26";
byte[] signBytes;
try {
signBytes = SignatureUtils.hmacSHA1Signature("byczfpx4PKBzUNjjL4261cE3s6HQmH" + "&", str.toString());
String signature = SignatureUtils.newStringByBase64(signBytes);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
C++ 签名算法参考
#include "ali_rpc_request.h"
#include "ali_string_utils.h"
#include "ali_encode_utils.h"
#include "ali_urlencode.h"
#include "ali_log.h"
#include <stdio.h>
#include <time.h>
static std::string get_utc_string() {
time_t now;
struct tm *timenow;
now = time(&now);
timenow = gmtime(&now);
std::string res= get_format_string("%d-%02d-%02dT%02d:%02d:%02dZ", timenow->tm_year + 1900,
timenow->tm_mon + 1,
timenow->tm_mday,
timenow->tm_hour,
timenow->tm_min,
timenow->tm_sec);
return res;
}
AliRpcRequest::AliRpcRequest(std::string version,
std::string appid,
std::string secret,
std::string url)
: AliHttpRequest(url),
version_(version),
appid_(appid),
secret_(secret),
url_(url) {
}
std::string AliRpcRequest::GetSignUrl() {
std::string encoded;
std::map<std::string, std::string> mapWithPublicArgs;
time_t now;
time(&now);
this->sign_nounce = get_format_string("%ld", now);
this->utc_time_ = get_utc_string();
if(this->query_.size()) {
std::vector<std::string> vec_queries;
strsplit(this->query_, vec_queries, "&");
for(int i = 0; i < vec_queries.size(); i++) {
std::string& item = vec_queries[i];
int pos = item.find("=");
mapWithPublicArgs[item.substr(0, pos)] = item.substr(pos + 1, item.size() - pos - 1);
}
}
mapWithPublicArgs["Format"] = "JSON";
mapWithPublicArgs["Version"] = this->version_;
mapWithPublicArgs["AccessKeyId"] = this->appid_;
mapWithPublicArgs["SignatureMethod"] = "HMAC-SHA1";
mapWithPublicArgs["TimeStamp"] = utc_time_;
mapWithPublicArgs["SignatureVersion"] = "1.0";
mapWithPublicArgs["SignatureNonce"] = sign_nounce;//
for(std::map<std::string, std::string>::iterator it = mapWithPublicArgs.begin();
it != mapWithPublicArgs.end(); it++) {
if(!encoded.empty()) {
encoded.append("&");
}
append_format_string(encoded, "%s=%s", urlencode(it->first).c_str(), urlencode(it->second).c_str());
}
encoded = this->method_ + "&" + urlencode("/") + "&" + urlencode(encoded);
ALI_LOG("sign str=%sn", encoded.c_str());
return encoded;
}
int AliRpcRequest::CommitRequest() {
std::string sign_url = GetSignUrl();
std::string sign = encode_compute_hmac_sha1(this->secret_ + "&",
(char*)sign_url.c_str(),
sign_url.size());
AddRequestQuery("TimeStamp", utc_time_);
AddRequestQuery("Format", "JSON");
AddRequestQuery("Version", this->version_);
AddRequestQuery("AccessKeyId", this->appid_);
AddRequestQuery("SignatureMethod", "HMAC-SHA1");
AddRequestQuery("SignatureVersion", "1.0");
AddRequestQuery("SignatureNonce", this->sign_nounce);
AddRequestQuery("Signature", sign);
return AliHttpRequest::CommitRequest();
}
最后更新:2016-11-23 16:04:01
上一篇:
接口简介__OpenAPI使用手册_云监控-阿里云
下一篇:
预设监控项参考__OpenAPI使用手册_云监控-阿里云
ALIYUN::ECS::InstanceGroup__资源列表_资源编排-阿里云
查询模板信息__模板相关接口_API 文档_资源编排-阿里云
产品发行版本说明__产品简介_E-MapReduce-阿里云
阿里云大数据学院落户青岛西海岸新区!中国北方第一所!
子账号访问__授权管理_阿里云物联网套件-阿里云
了解视频点播流程__开发人员指南_视频点播-阿里云
阿里云大数据平台服务协议__相关协议_平台介绍_数加平台介绍-阿里云
子用户登录常见问题__常见问题_产品使用问题_访问控制-阿里云
原地扩容裸盘 (Linux)__扩容磁盘概览_磁盘_用户指南_云服务器 ECS-阿里云
ZoneType__数据类型_API 参考_云服务器 ECS-阿里云
相关内容
常见错误说明__附录_大数据计算服务-阿里云
发送短信接口__API使用手册_短信服务-阿里云
接口文档__Android_安全组件教程_移动安全-阿里云
运营商错误码(联通)__常见问题_短信服务-阿里云
设置短信模板__使用手册_短信服务-阿里云
OSS 权限问题及排查__常见错误及排除_最佳实践_对象存储 OSS-阿里云
消息通知__操作指南_批量计算-阿里云
设备端快速接入(MQTT)__快速开始_阿里云物联网套件-阿里云
查询API调用流量数据__API管理相关接口_API_API 网关-阿里云
使用STS访问__JavaScript-SDK_SDK 参考_对象存储 OSS-阿里云