出于应用目的,我想将电子邮件(字符串)的完整内容存储在字典中。 [我知道这是每个哈希函数提供的,但要明确声明相同字符串的哈希应该始终相同]
因为它不是出于加密原因,而是仅用于存储在字典中。任何人都可以建议.Net中提供一个好的哈希函数吗?我担心的是,电子邮件字符串可能很大,我希望我的哈希函数支持大字符串,而不会引起频繁的冲突。我要存储大约500个条目。
请注意,我不想编写自己的哈希函数,而是利用.Net中现有的可用哈希函数
答案 0 :(得分:2)
您可以考虑使用HashAlgorithm.ComputeHash。
以下是此功能提供的示例:
using System;
using System.Security.Cryptography;
using System.Text;
public class Program
{
public static void Main()
{
string source = "Hello World!";
using (SHA256 sha256Hash = SHA256.Create())
{
string hash = GetHash(sha256Hash, source);
Console.WriteLine($"The SHA256 hash of {source} is: {hash}.");
Console.WriteLine("Verifying the hash...");
if (VerifyHash(sha256Hash, source, hash))
{
Console.WriteLine("The hashes are the same.");
}
else
{
Console.WriteLine("The hashes are not same.");
}
}
}
private static string GetHash(HashAlgorithm hashAlgorithm, string input)
{
// Convert the input string to a byte array and compute the hash.
byte[] data = hashAlgorithm.ComputeHash(Encoding.UTF8.GetBytes(input));
// Create a new Stringbuilder to collect the bytes
// and create a string.
var sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
// Return the hexadecimal string.
return sBuilder.ToString();
}
// Verify a hash against a string.
private static bool VerifyHash(HashAlgorithm hashAlgorithm, string input, string hash)
{
// Hash the input.
var hashOfInput = GetHash(hashAlgorithm, input);
// Create a StringComparer an compare the hashes.
StringComparer comparer = StringComparer.OrdinalIgnoreCase;
return comparer.Compare(hashOfInput, hash) == 0;
}
}
我希望对您有帮助