我必須將C#哈希從下面的代碼複製到PHP中。我一直在尋找,但到目前爲止還沒有找到解決方案。將C#MD5哈希複製到PHP
從this article on creating an md5 hash string:
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」,上面的代碼給了我
我曾嘗試下面的PHP代碼,但它沒有給出相同的輸出 「5FA285E1BEBE0A6623E33AFC04A1FBD5」。
從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仍然不會給我相同的結果。
任何人都可以幫忙嗎?
MD5是一個散列算法。除非他們改變了算法(他們爲什麼會這麼做?),它們計算的散列應該在兩個實現中都是相同的。 – 2013-02-17 03:56:02
你的c#使用utf-16LE,你的php utf-32 – CodesInChaos 2013-02-17 03:57:29
如果可以的話,兩邊都使用utf-8 – CodesInChaos 2013-02-17 04:01:36