这里有两个哈希生成器:
现在,我的问题是: 为什么哈希值在尝试对字符“€”(0x80) 进行哈希处理时会有所不同? 我认为这是因为“€”不是普通的 ASCII 字符。 这两个哈希值中的哪一个是“正确的”?
我正在尝试使用 C# 计算哈希生成器 1 返回的哈希。 此哈希函数不返回它。
private string GetMD5Hash(string TextToHash)
{
if ((TextToHash == null) || (TextToHash.Length == 0))
{
return string.Empty;
}
MD5 md5 = new MD5CryptoServiceProvider();
byte[] textToHash = Encoding.Default.GetBytes(TextToHash);
byte[] result = md5.ComputeHash(textToHash);
return BitConverter.ToString(result).Replace("-", "").ToLower();
}
我如何更改它以便它返回我想要的哈希值?
附加信息: 我做了一个小的 AutoIt 脚本:
#include <Crypt.au3>
ConsoleWrite(StringLower(StringMid(_Crypt_HashData(Chr(128), $CALG_MD5),3)) & @CRLF)
它返回我想要的哈希值! 但是我需要一个 C# 代码 :)
最佳答案
归结为你使用哪种编码将 string
转换为 byte[]
(因此我建议尝试使用 UTF-8,因为它很漂亮这里的常见选择;但是,只要您知道使用哪个,任何完整的 unicode 编码都可以工作);例如,根据字符串 "abc€"
,我们可以推断第一个站点可能使用以下任何一种:
874: Thai (Windows)
936: Chinese Simplified (GB2312)
1250: Central European (Windows)
1252: Western European (Windows)
1253: Greek (Windows)
1254: Turkish (Windows)
1255: Hebrew (Windows)
1256: Arabic (Windows)
1257: Baltic (Windows)
1258: Vietnamese (Windows)
50227: Chinese Simplified (ISO-2022)
51936: Chinese Simplified (EUC)
52936: Chinese Simplified (HZ)
就我个人而言,我会使用 UTF-8!
这是我用来查找候选编码的代码:
MD5 md5 = new MD5CryptoServiceProvider();
foreach (var enc in Encoding.GetEncodings())
{
byte[] textToHash = enc.GetEncoding().GetBytes("abc€");
byte[] result = md5.ComputeHash(textToHash);
var output = BitConverter.ToString(result).Replace("-", "").ToLower();
if(output == "7a66042043b2cc38ba16a13c596d740e")
{ // result from http://www.md5hashgenerator.com/index.php
Console.WriteLine(enc.CodePage + ": " + enc.DisplayName);
}
}
此外,使用字符串 "dnos ʇǝqɐɥdʃɐ"
进行测试表明,第二个站点肯定使用 UTF-8;第一个站点找不到匹配项,所以我猜它使用的是基于代码页的编码,简而言之,不能可靠地工作所有的 unicode。
关于c# - 散列非 ascii 字符 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8892395/