using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Web; using Microsoft.AspNetCore.Routing; namespace Hncore.Infrastructure.AliYun { public class Util { const string QUERY_SEPARATOR = "&"; const string HEADER_SEPARATOR = "\n"; const string AccessSecret = "r8FfRmoeWcCJyZSqqkQP2G3dKPPl2N "; private const string AccessKeyId = "LTAI4FmSkDSwFuXeLxsDB3jB"; public static string CreateSign(Dictionary data, string method = "GET") { var dic = new RouteValueDictionary(data); string[] array = dic.OrderBy(a => a.Key, StringComparer.Ordinal) .Select(a => PercentEncode(a.Key) + "=" + PercentEncode(a.Value.ToString())).ToArray(); string dataStr = string.Join("&", array); string signStr = method + "&" + PercentEncode("/") + "&" + PercentEncode(dataStr); HMACSHA1 myhmacsha1 = new HMACSHA1(Encoding.UTF8.GetBytes(AccessSecret + "&")); byte[] byteArray = Encoding.UTF8.GetBytes(signStr); MemoryStream stream = new MemoryStream(byteArray); string signature = Convert.ToBase64String(myhmacsha1.ComputeHash(stream)); return signature; } private static string PercentEncode(string value) { return UpperCaseUrlEncode(value) .Replace("+", "%20") .Replace("*", "%2A") .Replace("%7E", "~"); } private static string UpperCaseUrlEncode(string s) { char[] temp = HttpUtility.UrlEncode(s).ToCharArray(); for (int i = 0; i < temp.Length - 2; i++) { if (temp[i] == '%') { temp[i + 1] = char.ToUpper(temp[i + 1]); temp[i + 2] = char.ToUpper(temp[i + 2]); } } return new string(temp); } public static IDictionary SortDictionary(Dictionary dic) { IDictionary sortedDictionary = new SortedDictionary(dic, StringComparer.Ordinal); return sortedDictionary; } public static Dictionary BuildCommonParam() { Dictionary dic = new Dictionary(); dic.Add("AccessKeyId", AccessKeyId); dic.Add("Timestamp", DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ")); dic.Add("SignatureMethod", "HMAC-SHA1"); dic.Add("SignatureVersion", "1.0"); dic.Add("SignatureNonce", Guid.NewGuid().ToString()); return dic; } } }