该代码参考网上资料。
/// <summary>
/// 阿里云签名
/// </summary>
public class SignatureHelper
{
private const string ISO8601_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
private const string ENCODING_UTF8 = "UTF-8";
public string CreateSignatureUrl(string accessKeyId, string accessKeySecret, string endPoint, Dictionary<string, string> paramsDic)
{
var apiParams = new Dictionary<string, string>
{
{ "SignatureMethod", "HMAC-SHA1" },
{ "SignatureNonce", Guid.NewGuid().ToString() },
{ "SignatureVersion", "1.0" },
{ "AccessKeyId", accessKeyId },
{ "Timestamp", Iso8601DateTimeFormater(DateTime.Now) },
{ "Format", "JSON" }
};
foreach (var param in paramsDic)
{
if (!apiParams.ContainsKey(param.Key))
{
apiParams.Add(param.Key, param.Value);
}
}
var sortedDictionary = SignatureDicSorted(apiParams);
var queryStringAppend = new StringBuilder();
foreach (var param in sortedDictionary)
{
queryStringAppend.AppendFormat("&{0}={1}", PercentEncode(param.Key), PercentEncode(param.Value));
}
var sortedQueryString = queryStringAppend.ToString();
string stringToSign = "GET&%2F&" + PercentEncode(sortedQueryString.Substring(1));
string sign = Signature(stringToSign, accessKeySecret + "&");
string signature = PercentEncode(sign);
return $"{endPoint.TrimEnd('/')}/?Signature={signature}{sortedQueryString}";
}
public string Signature(string input, string accessSecret)
{
using (var algorithm = new HMACSHA1())
{
algorithm.Key = Encoding.UTF8.GetBytes(accessSecret.ToCharArray());
return Convert.ToBase64String(algorithm.ComputeHash(Encoding.UTF8.GetBytes(input.ToCharArray())));
}
}
public string PercentEncode(string value)
{
var stringBuilder = new StringBuilder();
string text = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";
byte[] bytes = Encoding.GetEncoding(ENCODING_UTF8).GetBytes(value);
foreach (char c in bytes)
{
if (text.IndexOf(c) >= 0)
{
stringBuilder.Append(c);
}
else
{
stringBuilder.Append("%").AppendFormat(CultureInfo.InvariantCulture, "{0:X2}", (int)c);
}
}
return stringBuilder.ToString();
}
public string Iso8601DateTimeFormater(DateTime dateTime)
{
return dateTime.ToUniversalTime().ToString(ISO8601_DATE_FORMAT, CultureInfo.CreateSpecificCulture("en-US"));
}
public IDictionary<string, string> SignatureDicSorted(Dictionary<string, string> dic)
{
return new SortedDictionary<string, string>(dic, StringComparer.Ordinal);
}
}
调用入口:CreateSignatureUrl(...)