为什么我的MD5哈希计算产生错误的结果[已关闭]

问题描述 投票:0回答:1

我正在尝试计算该字典的 MD5 哈希值

Dictionary<string, string> data = new Dictionary<string, string>
  {
      { "PAYGATE_ID", companyInfo.PayGateId },
      { "REFERENCE", reference },
      { "AMOUNT", $"{pGPayReqDTO.Amount}" },
      { "CURRENCY",  $"{companyInfo.PayGateCurrency}" },
      { "RETURN_URL", "mydomain/api/Paygate/ReturnFromPaygate" },
      { "TRANSACTION_DATE", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") },
      { "LOCALE", "en" },
      { "COUNTRY", $"{companyInfo.PayGateCountryCode}" },
      { "EMAIL", $"{pGPayReqDTO.Email}" },
      { "NOTIFY_URL",  $"mydomain/api/Paygate/Notify" },
  };

以上样例作品 但下面的内容却没有,唯一的区别是 NOTIFY_URL 有参数

Dictionary<string, string> data = new Dictionary<string, string>
      {
          { "PAYGATE_ID", companyInfo.PayGateId },
          { "REFERENCE", reference },
          { "AMOUNT", $"{pGPayReqDTO.Amount}" },
          { "CURRENCY",  $"{companyInfo.PayGateCurrency}" },
          { "RETURN_URL", "mydomain/api/Paygate/ReturnFromPaygate" },
          { "TRANSACTION_DATE", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") },
          { "LOCALE", "en" },
          { "COUNTRY", $"{companyInfo.PayGateCountryCode}" },
          { "EMAIL", $"{pGPayReqDTO.Email}" },
          { "NOTIFY_URL",  $"mydomain/api/Paygate/Notify?domain={domain}&CustomerId={pGPayReqDTO.CustomerId}&CartId={pGPayReqDTO.CartId}&BranchId={pGPayReqDTO.BranchId}" },
      };
c# .net asp.net-core .net-core md5
1个回答
0
投票

在第二个网址中,您有查询参数

domain
CustomerId
CartId
BranchId
,并且值是动态的,因此它会在请求之间发生变化。因此它每次都会生成不同的 url。

您可以尝试以下代码:

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

public class Program
{
    public static void Main()
    {
        
        Dictionary<string, string> data = new Dictionary<string, string>
        {
            // actual dictionary contents...
        };

        string concatenatedString = string.Join("", data.OrderBy(kvp => kvp.Key).Select(kvp => kvp.Value));
        string md5Hash = CalculateMD5Hash(concatenatedString);

        Console.WriteLine(md5Hash);
    }

    public static string CalculateMD5Hash(string input)
    {
        using (MD5 md5 = MD5.Create())
        {
            byte[] inputBytes = Encoding.ASCII.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();
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.