编辑代码


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
  
   
public class AKSNCaculater
{
    private static string MD5(string password)
    {
        byte[] textBytes = System.Text.Encoding.UTF8.GetBytes(password);
        try
        {
            System.Security.Cryptography.MD5CryptoServiceProvider cryptHandler;
            cryptHandler = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] hash = cryptHandler.ComputeHash(textBytes);
            string ret = "";
            foreach (byte a in hash)
            {
                ret += a.ToString("x2");
            }
            return ret;
        }
        catch
        {
            throw;
        }
    }

    private static string UrlEncode(string str)
    {
        // 等同于Encoding.ASCII.GetBytes(str)
        str = System.Web.HttpUtility.UrlEncode(str);
        byte[] buf = Encoding.ASCII.GetBytes(str);
        for (int i = 0; i < buf.Length; i++)
            if (buf[i] == '%')
            {
                if (buf[i + 1] >= 'a') buf[i + 1] -= 32;
                if (buf[i + 2] >= 'a') buf[i + 2] -= 32;
                i += 2;
            }
        // 同上,等同于Encoding.ASCII.GetString(buf)
        return Encoding.ASCII.GetString(buf);
    }

    private static string HttpBuildQuery(IDictionary<string, string> querystring_arrays)
    {

        StringBuilder sb = new StringBuilder();
        foreach (var item in querystring_arrays)
        {
            sb.Append(UrlEncode(item.Key));
            sb.Append("=");
            sb.Append(UrlEncode(item.Value));
            sb.Append("&");
        }
        sb.Remove(sb.Length - 1, 1);
        return sb.ToString();
    }

    public static string CaculateAKSN(string ak, string sk, string url, IDictionary<string, string> querystring_arrays)
    { 
        var queryString = HttpBuildQuery(querystring_arrays);

        var str = UrlEncode(url + "?" + queryString + sk); 

        return MD5(str);
    }
} 


class Program
{
    static void Main()
    {
        string ak = "bKuLhtcYF86I9J1zqFCgSQuDkMhkcoi7";
        string sk = "WcMiEB4GMk5cl9gZPVwCWIlIGfxPqkyM";
        string url = "/place/v2/suggestion";

        var queryParameters = new Dictionary<string, string>
        {
            { "query", "陕西省西安市" },
            { "region", "陕西省西安市" },
            { "city_limit", "false" },
            { "output", "json" },
            { "ak", ak }
        };

        string aksn = AKSNCaculater.CaculateAKSN(ak, sk, url, queryParameters);

        Console.WriteLine($"Calculated AKSN: {aksn}");
    }
}

// a28383b028e25608037828e977f9b78b
// https://api.map.baidu.com/place/v2/suggestion?query=陕西省西安市&region=陕西省西安市&city_limit=false&output=json&ak=bKuLhtcYF86I9J1zqFCgSQuDkMhkcoi7