阿里云openapi签名实现代码(基于C#)

阿里云openapi签名实现代码(基于C#)

代码正文如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;

namespace openapiSignature
{
    class MainClass
    {
        private String Format = "JSON";
        private String Version = "2017-03-21";
        private String AccessKeyId = "yourAccessKeyID";
        private String SignatureMethod = "HMAC-SHA1";
        private String SignatureVersion = "1.0";
        private Dictionary<string, string> publicParams;

        public void setPublicParams(Dictionary<string,string>dic)
        {
            publicParams = dic;
        }
        public Dictionary<string, string> getPublicParams()
        {
            return publicParams;
        }
        public String getFormat()
        {
            return Format;
        }
        public String getVersion()
        {
            return Version;
        }
        public String getAccessKeyId()
        {
            return AccessKeyId;
        }
        public String getSignatureMethod()
        {
            return SignatureMethod;
        }
        public String getSignatureVersion()
        {
            return SignatureVersion;
        }
        public String getTimestamp()
        {
            String now = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ");
            return now;
        }
        public String getSignatureNonce()
        {
            return System.Guid.NewGuid().ToString();
        }
        public String getAccessKeySecret()
        {
            return "yourAccessKeySecret";
        }
        /**
         * URL编码
         */
        public static string UrlEncode(string temp)
        {
            Encoding encoding = System.Text.Encoding.UTF8;
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < temp.Length; i++)
            {
                string t = temp[i].ToString();
                string k = HttpUtility.UrlEncode(t, encoding);
                if (t == k)
                {
                    stringBuilder.Append(t);
                }
                else
                {
                    stringBuilder.Append(k.ToUpper());
                }
            }
            return stringBuilder.ToString();
        }
        /**
         * 对urlencode之后的字符串进行特殊字符检测和替换
         */
        public static string checkParam(string str)
        {
            
            if(str.Contains("+"))
            {
                str.Replace("+","%20");
            }else if(str.Contains("*"))
            {
                str.Replace("*", "%2A");
            }
            else if (str.Contains("%7E"))
            {
                str.Replace("%7E","~");
            }
            return str;
        }
        /**
         * 计算Hmacsha1
         */
        public static string HmacSha1Sign(string text, string key)
        {
            HMACSHA1 hmacsha1 = new HMACSHA1();
            byte[] byteData = Encoding.UTF8.GetBytes(text);
            hmacsha1.Key = Encoding.UTF8.GetBytes(key);
            byte[] dataBuffer = System.Text.Encoding.UTF8.GetBytes(text);
            byte[] hashBytes = hmacsha1.ComputeHash(dataBuffer);
            return Convert.ToBase64String(hashBytes);
        }

        /**
         * base64 编码
         */
        public static string EncodeBase64(string code_type, string code)
        {
            string encode = "";
            byte[] bytes = Encoding.GetEncoding(code_type).GetBytes(code);
            try
            {
                encode = Convert.ToBase64String(bytes);
            }
            catch
            {
                encode = code;
            }
            return encode;
        }


        public static void Main(string[] args)
        {
            MainClass ss = new MainClass();
            //添加公共参数
            Dictionary<String, String> publicParam = new Dictionary<string, string>();
            publicParam.Add("Format", ss.getFormat());
            publicParam.Add("Version", ss.getVersion());
            publicParam.Add("SignatureMethod", ss.getSignatureMethod());
            publicParam.Add("SignatureNonce", ss.getSignatureNonce());
            publicParam.Add("Timestamp", ss.getTimestamp());
            publicParam.Add("AccessKeyId", ss.getAccessKeyId());
            publicParam.Add("SignatureVersion", ss.getSignatureVersion());

            //添加API接口以及接口参数
            publicParam.Add("Action", "GetVideoPlayAuth");
            publicParam.Add("VideoId", "f6a21eade82f4cf6b45669fa34b35b76");


            //将参数名和参数值用“=”链接起来之后,按照整体字符串的字典序排序;
            Dictionary<String, String> sortedParams = publicParam.OrderBy(o => o.Key + "=" + o.Value).ToDictionary(o => o.Key, p => p.Value);
            //对连接之后的字符串进行urlencode
            Dictionary<String, String> urlEncoderParam = sortedParams.ToDictionary(k => MainClass.UrlEncode(k.Key), v => MainClass.UrlEncode(v.Value));
            //对urlencode之后的字符串进行特殊字符判断并转换
            Dictionary<String, String> parseEncoderParam = urlEncoderParam.ToDictionary(k => MainClass.checkParam(k.Key), v => MainClass.checkParam(v.Value));


            //对字符串进行拼接,获取strToSign
            string strToSign = "";
            foreach (KeyValuePair<String, String> k in parseEncoderParam)
            {
                strToSign += k.Key + "=" + k.Value + "&";
            }
            
            strToSign = "GET&%2F&" + MainClass.UrlEncode(strToSign.Substring(0, strToSign.Length - 1));
            string signature = HmacSha1Sign(strToSign, ss.getAccessKeySecret() + "&");

            if (signature.Contains("+"))
            {
                signature.Replace("+", "%2B");
            }
            publicParam.Add("Signature", signature);
            string url = "http://vod.cn-shanghai.aliyuncs.com?";
            foreach (KeyValuePair<string, string> pair in publicParam)
            {
                url += pair.Key + "=" + pair.Value + "&";
            }
            url = url.Substring(0, url.Length - 1);

            Console.WriteLine(url);
        }
    }
}
上一篇:C#代码实现矢量画图


下一篇:100 行代码实现的 JavaScript MVC 样式框架