Хранить хешированную почту в словаре .Net - PullRequest
0 голосов
/ 16 мая 2019

Для целей приложения я хочу сохранить полный текст письма (строку) в словаре. [Я знаю, что это то, что предоставляет каждая хеш-функция, но хотел явно указать, что хеш для одной и той же строки всегда должен быть одинаковым]

Так как это не по криптографической причине, а только для хранения в словаре. Может ли кто-нибудь, пожалуйста, предложить хорошую функцию хеширования, которая доступна в .Net. Меня беспокоит, что строка электронной почты может быть довольно большой, и я хочу, чтобы моя хеш-функция поддерживала большую строку и не вызывала частых коллизий. Я ищу для хранения около 500 записей.

Обратите внимание, я не хочу писать свою собственную функцию хэширования, но использую имеющуюся доступную хэш-функцию в .Net

1 Ответ

2 голосов
/ 16 мая 2019

Вы можете рассмотреть возможность использования 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;
    }    
}

Я надеюсь, что это помогает ?

...