8

我在 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# 行为,因为它已经实现并且使用此算法将密码保存在我的数据库中。

4

6 回答 6

20

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

于 2009-05-04T20:19:24.837 回答
5

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

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

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

于 2009-05-04T20:16:37.790 回答
4

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

$hashValue = base64_encode(md5(utf8_decode($inputString)))
于 2009-05-04T20:18:36.413 回答
1

对于php,它应该如下所示

 php -r "echo base64_encode(md5(utf8_encode('asd'),true));"
于 2012-03-22T15:25:40.030 回答
0

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

于 2010-03-09T10:04:43.837 回答
-1

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-02-09T17:06:38.687 回答