题
我有一散列算法中,一言以蔽之,就是:
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#行为,因为它已经实现和密码保存在我的数据库用这种算法。
解决方案
问题是PHP的 md5()
功能默认情况下返回六变化的哈里C#是归还原字节的输出,然后必须制成文的安全与base64编码。如果你正在运行PHP5可以使用 base64_encode(md5('asd', true))
.注意第二次参数 md5()
是真的,这使得 md5()
返回原字节,而不是六角。
其他提示
你记得base64encode md5hash在php?
$result = base64_encode(md5($password, true));
第二个参数使md5返回原出,这是相同的功能,你使用在C#
你C#代码需要的UTF8字节串;计算md5和储存作为base64编码。所以你应该这样做在php,这应该是:
$hashValue = base64_encode(md5(utf8_decode($inputString)))
它应该是这样的如下php
php -r "echo base64_encode(md5(utf8_encode('asd'),true));"
我有同样的问题...只用md5($myvar:)它的工作。我得到同样的结果C#PHP.
加文*肯德尔发布帮助了我。我希望这可以帮助他人。
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))), “-”, “”);
}
不隶属于 StackOverflow