Files
juipnet/Infrastructure/Hncore.Infrastructure/AliYun/Util.cs
“wanyongkang” ed3b2c653e 接口文件
2024-04-10 13:55:27 +08:00

82 lines
2.8 KiB
C#

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<string, string> 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<string, string> SortDictionary(Dictionary<string, string> dic)
{
IDictionary<string, string> sortedDictionary =
new SortedDictionary<string, string>(dic, StringComparer.Ordinal);
return sortedDictionary;
}
public static Dictionary<string, string> BuildCommonParam()
{
Dictionary<string, string> dic = new Dictionary<string, string>();
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;
}
}
}