public static void main(String[] args) throws Exception { String url ="Timestamp=2016-02-23T12%3A46:24Z&Format=XML&AccessKeyId=testid&Action=CreateIntent&SignatureMethod=HMAC-SHA1&SignatureNonce=3ee8c1b8-83d3-44af-a94f-4e0ad82fd6cf&Version=2019-12-26&SignatureVersion=1.0"; String[] split = url.split("&");
Map<String, String> map = new HashMap<>();
for (String str : split) {
System.out.println("str:"+str);
String[] splitkeyValue = str.split("=");
map.put(splitkeyValue[0],splitkeyValue[1]);
}
String getStringToSign = getStringToSign(map, "GET");
String sign = getSign(getStringToSign,AccessKeySecret);
System.out.println("sign:"+sign);
//OLeaidS1JvxuMvnyHOwuJ+uX5qY= }
/** * [Hmac-SHA1 签名算法] * 签名方法 * * @return [签名值] * @String encryptText [加密字符源串] * @String encryptKey [加密密钥] */ public static String getSign(String encryptText, String accessKeySecret) throws Exception { byte[] data = accessKeySecret.getBytes(ENCODING); SecretKey secretKey = new SecretKeySpec(data, MAC_NAME); Mac mac = Mac.getInstance(MAC_NAME); mac.init(secretKey); byte[] text = encryptText.getBytes(ENCODING); byte[] digest = mac.doFinal(text); return new String(Base64.encodeBase64(digest),"UTF-8"); }
/**
* 待签名字符串
* @param map
* @return
*/
public static String getStringToSign(Map<String, String> map,String hTTPMethod) throws UnsupportedEncodingException {
LOG.info("start*******************************************getStringToSign()");
//构造规范化字符串
List<String> list = new ArrayList<>(map.keySet());
//按字符串自然大小排序
Collections.sort(list);
//拼接字符串
StringBuilder stringBuilder = new StringBuilder();
for (String p : list) {
stringBuilder.append(percentEncode(p))
.append("=")
.append(percentEncode(map.get(p)))
.append("&");
}
System.out.println("stringBuilder.toString():"+stringBuilder.toString());
String stringToSign=
hTTPMethod + "&" +
percentEncode("/") + "&" +
percentEncode(stringBuilder.toString());
System.out.println("stringToSign:"+stringToSign);
LOG.info("end*******************************************getStringToSign()");
return stringToSign;
}
/**
* 待签名字符串参数的名称和值分别用UTF-8字符集进行URL编码
*/
private static String percentEncode(String value) throws UnsupportedEncodingException {
return value != null ? URLEncoder.encode(value, ENCODING).replace("+", "%20").replace("*", "%2A").replace("%7E", "~").replace("/", "%2F") : null; }
}
官方有java语言的sdk,建议有限使用java core sdk,sdk底层已经做好了签名,避免签名错误导致请求异常,使用参考:https://developer.aliyun.com/article/704556 正常构造commonrequest即可。
如果一定要自签名,参考地址:https://help.aliyun.com/document_detail/144904.html
注意替换action&api-Version和加入该挨批请求的必要参数。
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。