我必须将 C# 哈希从下面的代码复制到 PHP 中。我一直在寻找,但到目前为止还没有找到解决方案。
using System;
using System.Text;
using System.Security.Cryptography;
// Create an md5 sum string of this string
static public string GetMd5Sum(string str)
{
// First we need to convert the string into bytes, which
// means using a text encoder.
Encoder enc = System.Text.Encoding.Unicode.GetEncoder();
// Create a buffer large enough to hold the string
byte[] unicodeText = new byte[str.Length * 2];
enc.GetBytes(str.ToCharArray(), 0, str.Length, unicodeText, 0, true);
// Now that we have a byte array we can ask the CSP to hash it
MD5 md5 = new MD5CryptoServiceProvider();
byte[] result = md5.ComputeHash(unicodeText);
// Build the final string by converting each byte
// into hex and appending it to a StringBuilder
StringBuilder sb = new StringBuilder();
for (int i=0;i<result.Length;i++)
{
sb.Append(result[i].ToString("X2"));
}
// And return it
return sb.ToString();
}
对于输入=“123”,上面的代码给了我“5FA285E1BEBE0A6623E33AFC04A1FBD5”
我尝试了以下 PHP 代码,但它没有给出相同的输出。
从 SO 问题PHP MD5 not matching C# MD5:
$str = "123";
$strUtf32 = mb_convert_encoding($str, "UTF-32LE");
echo md5($strUtf32);
此代码的结果为 =“a0d5c8a4d386f15284ec25fe1eeeb426”。顺便说一句,将 UTF-32LE 更改为 utf-8 或 utf-16 仍然不会给我相同的结果。
任何人都可以帮忙吗?