老是报签名字符串与阿里计算后的不匹配~,有点晕了,实在找不出在那个计算中出问题了。请大家帮忙看看吧。
下面为核心代码:
public string HTTP_METHOD = "GET";
public string SEPARATOR = "&";
//参数集合
public SortedDictionary<string, string> parameters = new SortedDictionary<string, string>(StringComparer.Ordinal);
private void Form2_Load(object sender, EventArgs e)
{
//初始化http url 参数
parameters.Add("Format", "json");
parameters.Add("Version", "2015-01-09");
parameters.Add("AccessKeyId", "testid");
parameters.Add("SignatureMethod", "HMAC-SHA1");
parameters.Add("Timestamp", CreateTimestamp());
parameters.Add("SignatureVersion", "1.0");
parameters.Add("SignatureNonce",CreateSignatureNonce());
parameters.Add("Action", "DescribeDomainRecords");
parameters.Add("DomainName","test.com");
//构造出规范化请求字符串CanonicalizedQueryString
string CanonicalizedQueryString = "";
foreach (var item in parameters)
{
if (CanonicalizedQueryString != "") CanonicalizedQueryString += SEPARATOR;
CanonicalizedQueryString += string.Format("{0}{1}{2}", percentEncode(item.Key),("="), percentEncode(item.Value));
}
//构造出用于签名的字符串StringToSign
string StringToSign = HTTP_METHOD + SEPARATOR + percentEncode("/") + SEPARATOR + percentEncode(CanonicalizedQueryString);
//计算签名
string ALGORITHM = "HmacSHA1";
string ENCODING = "UTF-8";
string key = "testsecret" + SEPARATOR;
string signature = HmacSha1Sign(StringToSign,key);
CanonicalizedQueryString += string.Format("{0}{1}={2}", SEPARATOR, "Signature",percentEncode(signature));
httpitem = new HttpItem() { URL = url + CanonicalizedQueryString };
httpresult = httphelper.GetHtml(httpitem);
}
/// <summary>
/// 根据阿里云的要求进行编码
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public string percentEncode(string value)
{
return value!=null?HttpHelper.URLEncode(value,UTF8Encoding.UTF8).Replace("+","%20").Replace("*","%2A").Replace("%7E","~"):null;
}
/// <summary>
/// 生成时间戳UTC时间ISO8601规范
/// </summary>
/// <returns>字符串</returns>
public string CreateTimestamp()
{
var dt = DateTime.UtcNow;
return (dt.ToString(@"yyyy-MM-dd\THH:mm:ss\Z"));
}
/// <summary>
/// 创建唯一标示
/// </summary>
/// <returns>字符串</returns>
public string CreateSignatureNonce()
{
return Guid.NewGuid().ToString();
}
/// <summary>
/// HmacSha1算法
/// </summary>
/// <param name="text"></param>
/// <param name="key"></param>
/// <returns></returns>
private string HmacSha1Sign(string text, string key)
{
Encoding encode = Encoding.UTF8;
byte[] byteData = encode.GetBytes(text);
byte[] byteKey = encode.GetBytes(key);
HMACSHA1 hmac = new HMACSHA1(byteKey);
CryptoStream cs = new CryptoStream(Stream.Null, hmac, CryptoStreamMode.Write);
cs.Write(byteData, 0, byteData.Length);
cs.Close();
return Convert.ToBase64String(hmac.Hash);
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。