【问题标题】:php md5 algorithm that gives same result as c#php md5 算法给出与 c# 相同的结果
【发布时间】:2012-03-22 23:42:19
【问题描述】:

我在 C# 中有一个哈希算法,简而言之,它是:

string input = "asd";

System.Security.Cryptography.MD5 alg = System.Security.Cryptography.MD5.Create();
System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();


byte[] hash = alg.ComputeHash(enc.GetBytes(input));
string output = Convert.ToBase64String(hash);

// outputs:   eBVpbsvxyW5olLd5RW0zDg==
Console.WriteLine(output);

现在我需要在 php 中复制这种行为,

$input = "asd";
$output = HashSomething($input);
echo $output;

我怎样才能实现它?

我检查了

  • md5
  • utf8_decode
  • utf8_encode
  • base64_encode
  • base64_decode
  • url_decode

但我注意到 php md5 最后没有得到 == ......我错过了什么?

注意:我无法更改 C# 行为,因为它已经实现并且密码已使用此算法保存在我的数据库中。

【问题讨论】:

    标签: c# php md5


    【解决方案1】:

    问题是 PHP 的 md5() 函数默认返回哈希的十六进制变体,其中 C# 返回原始字节输出,然后必须使用 base64 编码使其成为文本安全的。如果你正在运行 PHP5,你可以使用base64_encode(md5('asd', true))。注意md5() 的第二个参数为真,这使得md5() 返回原始字节而不是十六进制。

    【讨论】:

    • md5 的 true 标志只存在于 PHP5 或更高版本中。在早期版本中,您需要调用 pack 函数。
    【解决方案2】:

    你还记得在 php 中对 md5 哈希进行 base64 编码吗?

    $result = base64_encode(md5($password, true));

    第二个参数使 md5 返回原始输出,这与您在 C# 中使用的函数相同

    【讨论】:

    • 该死。你敢打赌... == 通常来自 Base64 编码,你正在用 Convert.ToBase64String() 做的是你所缺少的吗?
    • 是的,但是如何在 php 上实现呢?我应该使用什么功能?
    【解决方案3】:

    您的 C# 代码从字符串中获取 UTF8 字节;计算 md5 并存储为 base64 编码。所以你应该在php中做同样的事情,应该是:

    $hashValue = base64_encode(md5(utf8_decode($inputString)))
    

    【讨论】:

      【解决方案4】:

      php应该如下所示

       php -r "echo base64_encode(md5(utf8_encode('asd'),true));"
      

      【讨论】:

        【解决方案5】:

        我遇到了同样的问题……只使用 md5($myvar) 就可以了。我得到相同的结果 C# 和 PHP。

        【讨论】:

          【解决方案6】:

          Gavin Kendall 发布的帖子帮助了我。我希望这对其他人有所帮助。

          http://jachman.wordpress.com/2006/06/06/md5-hash-keys-with-c/

          public static string MD5Hash(string text)
          {
              System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
              return System.Text.RegularExpressions.Regex.Replace(BitConverter.ToString(md5.ComputeHash(ASCIIEncoding.Default.GetBytes(text))), “-”, “”);
          }
          

          【讨论】:

            猜你喜欢
            • 2012-07-17
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-12-10
            • 1970-01-01
            • 2016-05-13
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多