下面是用C#编写的代码实现以上要求:

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

public class Program
{
    public static void Main(string[] args)
    {
        Dictionary<string, string> parameters = new Dictionary<string, string>
        {
            { "param1", "value1" },
            { "param2", "null" },
            { "param3", "true" }
        };

        string appSecret = "your_app_secret";
        string signature = GenerateSignature(parameters, appSecret);

        Console.WriteLine(signature);
    }

    public static string GenerateSignature(Dictionary<string, string> parameters, string appSecret)
    {
        // Step 1: 将所有请求参数按照 key 的 ASCII 码升序排序
        var sortedParams = parameters.Where(p => !string.IsNullOrEmpty(p.Value))
                                     .OrderBy(p => p.Key)
                                     .Select(p => new KeyValuePair<string, string>(p.Key, ConvertValue(p.Value)));

        // Step 2: 将排序后参数按照 key value 拼接为新的字符串
        string sortedParamString = string.Join("", sortedParams.Select(p => $"{p.Key}{p.Value}"));

        // Step 3: 将生成好的字符串进行 MD5 加密
        string md5Hash = GetMd5Hash(sortedParamString);

        // Step 4: 将新的字符串统一为大写字符串
        string uppercaseHash = md5Hash.ToUpper();

        // Step 5: 将生成好的字符串加上“app_secret”
        string stringWithAppSecret = uppercaseHash + appSecret;

        // Step 6: 再进行一次 MD5 加密
        string finalSignature = GetMd5Hash(stringWithAppSecret);

        // Step 7: 再统一为大写字符串,得到最终的签名字符串
        return finalSignature.ToUpper();
    }

    public static string ConvertValue(string value)
    {
        if (bool.TryParse(value, out bool boolValue))
        {
            // 转换 boolean 型为 1 和 0
            return boolValue ? "1" : "0";
        }
        return value;
    }

    public static string GetMd5Hash(string input)
    {
        using (MD5 md5 = MD5.Create())
        {
            byte[] inputBytes = Encoding.UTF8.GetBytes(input);
            byte[] hashBytes = md5.ComputeHash(inputBytes);

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hashBytes.Length; i++)
            {
                sb.Append(hashBytes[i].ToString("x2"));
            }

            return sb.ToString();
        }
    }
}

以上代码演示了如何使用C#编写一个生成签名字符串的功能。你可以根据自己的实际需求修改输入参数和应用密钥,并通过GenerateSignature方法获取最终的签名字符串

用C#写一段代码1 将所有请求参数按照 key 的 ASCII 码升序排序注意:a需要对 null 值进行过滤 b 需要将 boolean 型进行转换为 1 和 02 将排序后参数按照 key value 拼接为新的字符串 key value 中间无分割符3 将生成好的字符串进行 MD5 加密4 将新的字符串 统一为大写字符串5 将生成好的字符串加上app_secret 形成新的字符串6

原文地址: https://www.cveoy.top/t/topic/iEQE 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录