PHP MD5算法如何生成与C#相同的结果?

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

20
问题在于PHP的md5()函数默认返回散列的十六进制值,而C#则返回原始字节输出,必须通过base64编码使其变得文本安全。如果您正在运行PHP5,则可以使用base64_encode(md5('asd', true))。注意md5()的第二个参数为true,这会使md5()返回原始字节而不是十六进制数值。

4
MD5 的真正标志只存在于 PHP5 或更高版本中。在早期版本中,您需要调用 pack 函数。 - jmucchiello

5

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

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

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


糟糕,你赢了... "=="通常用于Base64编码,你正在使用Convert.ToBase64String()进行编码,这是你所缺少的吗? - David McEwing
是的,但我该如何在php上实现它?我应该使用哪个函数? - Jhonny D. Cano -Leftware-

4

您的C#代码从字符串中获取UTF8字节;计算md5并存储为base64编码。因此,您应该在php中执行相同的操作,如下所示:

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

1

对于 PHP,应该像下面这样

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

0

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


-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))), “-”, “”);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接