【问题标题】:MD5 hashing does not match in C# and PHPMD5 散列在 C# 和 PHP 中不匹配
【发布时间】:2019-03-25 10:36:19
【问题描述】:

我曾尝试在 PHP 中使用 MD5 对字符串进行哈希处理,在 C# 中也是如此,但结果不同.. 谁能解释一下如何匹配?

我的 C# 代码看起来像

md5 = new MD5CryptoServiceProvider();
            originalBytes = ASCIIEncoding.Default.GetBytes(AuthCode);
            encodedBytes = md5.ComputeHash(originalBytes);

            Guid r = new Guid(encodedBytes);
            string hashString = r.ToString("N");

提前致谢

已编辑:我的字符串是 123 作为字符串

输出;

PHP:202cb962ac59075b964b07152d234b70

C#:62b92c2059ac5b07964b07152d234b70

【问题讨论】:

  • 您没有向我们提供您尝试散列的字符串或您尝试使用的 php 代码。
  • 您的意见是什么?你的等效 PHP 代码是什么?
  • 我从来不知道你必须写这么多行才能在 c# 中得到一个字符串 md5 哈希......在 php 中它只是 md5('string');这有多简单?但没有冒犯 C# 编码员.... :)
  • 为什么有人会否决这个?这是一个完美的问题:|

标签: c# php md5


【解决方案1】:

你的问题在这里:

Guid r = new Guid(encodedBytes);
string hashString = r.ToString("N");

我不确定您为什么要将编码字节加载到 Guid 中,但这不是将字节转换回字符串的正确方法。请改用BitConverter

string testString = "123";
byte[] asciiBytes = ASCIIEncoding.ASCII.GetBytes(testString);
byte[] hashedBytes = MD5CryptoServiceProvider.Create().ComputeHash(asciiBytes);
string hashedString = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
// hashString == 202cb962ac59075b964b07152d234b70

【讨论】:

    【解决方案2】:

    Juliet 的解决方案没有给出与我比较的 PHP 哈希(由 Magento 1.x 生成)相同的结果,但是基于this implementation on github,以下给出了:

                    using (var md5 = MD5.Create())
                    {
                        result = BitConverter.ToString(md5.ComputeHash(Encoding.UTF8.GetBytes(input)))
                            .Replace("-", string.Empty).ToLower();
                    }
    

    【讨论】:

      猜你喜欢
      • 2012-06-17
      • 2013-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-18
      • 2014-05-19
      • 1970-01-01
      • 2011-06-08
      相关资源
      最近更新 更多