我在 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_解码
- utf8_encode
- base64_encode
- base64_解码
- url_解码
但我注意到 php md5 没有得到 == 最后...我错过了什么?
注意:我无法更改 C# 行为,因为它已经实现并且使用此算法将密码保存在我的数据库中。
最佳答案
问题是 PHP 的 md5()
函数默认返回哈希的十六进制变体,其中 C# 返回原始字节输出,然后必须使用 base64 编码使文本安全。如果您运行的是 PHP5,则可以使用 base64_encode(md5('asd', true))
。请注意 md5()
的第二个参数为真,这使得 md5()
返回原始字节而不是十六进制。
关于c# - 给出与 C# 相同结果的 php md5 算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/821817/