首页 > 解决方案 > 将散列的电子邮件存储在字典 .Net 中

问题描述

出于应用目的,我想将电子邮件(字符串)的完整内容存储在字典中。[我知道这是每个散列函数都提供的,但我想明确声明同一字符串的散列应该始终相同]

因为它不是出于加密原因,仅用于存储在字典中。任何人都可以建议.Net中可用的良好散列函数。我担心的是电子邮件字符串可能非常大,我希望我的哈希函数支持大字符串并且不会导致频繁的冲突。我正在寻找存储大约 500 个条目。

请注意,我不想编写自己的哈希函数,而是利用 .Net 中现有的可用哈希函数

标签: c#.nethashhashcode

解决方案


您可以考虑使用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;
    }    
}

我希望它有帮助


推荐阅读