签名算法的URL

有的厂商接口的Url是需要进行算法加密和参数按照字母排序

演示加密算法:
http://cctv/open/service?
method=method2
&timestamp=2015-04-26%2000:00:07
&format=xml
&app_key=testerp_appkey
&v=2.0
&sign=D06D88CB34B2EC0E5C9BAB396C9542B6
&sign_method=md5
&customerId=Tom

5.1.1.  输入参数为
method= method2
timestamp=2015-04-26 00:00:07
format=xml
app_key= testerp_appkey
v=2.0
sign_method=md5
customerId =test
5.1.2.  按首字母升序排列
app_key= testerp_appkey
customerId = Tom
format=xml
method= method2
sign_method=md5
timestamp=2015-04-26 00:00:07
v=2.0
5.1.3.  连接字符串
连接参数名与参数值,并在首尾加上 secret,此处假设 secret=test,如下:
testapp_keytesterp_appkeycustomerIdTomformatxmlmethodmethod2sign_methodmd5timestamp2015-04-26 00:00:07v2.0 body test
其中: body 用请求中的 body 数据代替
5.1.4.  生成签名 sign
32 位大写 MD5 值-> D06D88CB34B2EC0E5C9BAB396C9542B6
5.1.5.  拼装 URL 请求
将所有参数值转换为 UTF-8 编码,然后拼装,并作 URL ENCODING 如下:
http://cctv/open/service?
method=method2
&timestamp=2015-04-26%2000:00:07
&format=xml
&app_key=testerp_appkey
&v=2.0
&sign=D06D88CB34B2EC0E5C9BAB396C9542B6
&sign_method=md5
&customerId=Tom

1:按照首字母排序:

var values = new Dictionary<string, string>
            {
                { "method", method },
                { "timestamp", timestamp.ToString("yyyy-MM-dd HH:mm:ss") },
                { "format", "xml"},
                { "app_key", appkey },
                { "v", "2.0" },
                { "sign_method", "md5" },
                { "customerId", customerid}
            };           
//OrderBy(pair=>pair.Key) 按照参数进行排序升序,再取出所对应的key/value
var signContent = string.Join("", values.OrderBy(pair => pair.Key).Select(pair => $"{pair.Key}{pair.Value}"));

2:连接字符串

signContent = secret + signContent + data + secret;

3:生成签名算法

 string sign = BitConverter.ToString(MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(signContent))).Replace("-", "");

4:拼装 URL 请求

 var para = string.Join("&", values.OrderBy(pair => pair.Key).Select(pair => $"{pair.Key}={HttpUtility.UrlEncode(pair.Value)}"));

//返回URL

return $"{url}?{para}&sign={sign}";

 

posted @ 2020-04-27 10:15  ProZkb  阅读(391)  评论(0编辑  收藏  举报