c# - 将散列的电子邮件存储在字典 .Net 中
问题描述
出于应用目的,我想将电子邮件(字符串)的完整内容存储在字典中。[我知道这是每个散列函数都提供的,但我想明确声明同一字符串的散列应该始终相同]
因为它不是出于加密原因,仅用于存储在字典中。任何人都可以建议.Net中可用的良好散列函数。我担心的是电子邮件字符串可能非常大,我希望我的哈希函数支持大字符串并且不会导致频繁的冲突。我正在寻找存储大约 500 个条目。
请注意,我不想编写自己的哈希函数,而是利用 .Net 中现有的可用哈希函数
解决方案
您可以考虑使用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;
}
}
我希望它有帮助
推荐阅读
- java - 同一主机上的应用程序之间的组播
- c++ - C++中的数组有很多错误
- java - 如何使用 100 多个输入值插入忽略
- asp.net-core - Bootstrap Accordion 3.3.7 在 foreach 循环中崩溃 asp.net core 1.1 无法正常工作
- rust - 构造 Rust 特征的惯用方法
- javascript - JavaScript 提升:函数可以引用在它下面声明的另一个函数吗?
- usb - DirectShow 需要哪些 USB 描述符字段才能识别 UVC 相机?
- django - 相关字段查找无效:icontains - Django 2.1
- javascript - 在 this.state 中使用嵌套对象的最佳方法是什么?
- javascript - N-API C++ 插件导致 Electron GUI 阻塞