在使用c#调用百度地图Web服务api遇到的签名(sn校验)问题,在此记录一下,(ip白名单校验的请忽略

1.首先获取ak与sk,这个两个东西可以从控制台中获取到

2.在这个地址:sn签名算法,里面提供了java,php,c#,python2.7的参考代码

在百度提供的参考代码中,其中c#的代码中MD5加密方法是有问题的,(在笔者写随笔时,代码还是有问题的,之后希望百度官方修复此问题)

c# 百度地图api APP SN校验失败

 

把百度的MD5方法修改一下,签名就正确了,api正常调用了,开心!!

这里是完整的签名代码

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Web;
 6 
 7 namespace IpService.Code
 8 {
 9     public class BaiduAKSNCaculater
10     {
11         private static string MD5(string password)
12         {
13             try
14             {
15                 System.Security.Cryptography.HashAlgorithm hash = System.Security.Cryptography.MD5.Create();
16                 byte[] hash_out = hash.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
17 
18                 var md5_str=BitConverter.ToString(hash_out).Replace("-", "");
19                 return md5_str.ToLower();
20 
21             }
22             catch
23             {
24                 
25                 throw;
26             }
27         }
28 
29         private static string UrlEncode(string str)
30         {
31             str = System.Web.HttpUtility.UrlEncode(str);
32             byte[] buf = Encoding.ASCII.GetBytes(str);//等同于Encoding.ASCII.GetBytes(str)
33             for (int i = 0; i < buf.Length; i++)
34                 if (buf[i] == '%')
35                 {
36                     if (buf[i + 1] >= 'a') buf[i + 1] -= 32;
37                     if (buf[i + 2] >= 'a') buf[i + 2] -= 32;
38                     i += 2;
39                 }
40             return Encoding.ASCII.GetString(buf);//同上,等同于Encoding.ASCII.GetString(buf)
41         }
42 
43         private static string HttpBuildQuery(IDictionary<string, string> querystring_arrays)
44         {
45 
46             StringBuilder sb = new StringBuilder();
47             foreach (var item in querystring_arrays)
48             {
49                 sb.Append(UrlEncode(item.Key));
50                 sb.Append("=");
51                 sb.Append(UrlEncode(item.Value));
52                 sb.Append("&");
53             }
54             sb.Remove(sb.Length - 1, 1);
55             return sb.ToString();
56         }
57 
58         public static string CaculateAKSN(string ak, string sk, string url, IDictionary<string, string> querystring_arrays)
59         {
60             var queryString = HttpBuildQuery(querystring_arrays);
61 
62             var str = UrlEncode(url + "?" + queryString + sk);
63            
64             return MD5(str);
65         }
66     }
67 }
View Code

相关文章: