c# - 如何在 .net (c#) 中为可安全存储在数据库中的字符串创建 HashCode?

标签 c# .net database hashcode gethashcode

引自Guidelines and rules for GetHashCode埃里克·利珀特:

Rule: Consumers of GetHashCode cannot rely upon it being stable over time or across appdomains

Suppose you have a Customer object that has a bunch of fields like Name, Address, and so on. If you make two such objects with exactly the same data in two different processes, they do not have to return the same hash code. If you make such an object on Tuesday in one process, shut it down, and run the program again on Wednesday, the hash codes can be different.

This has bitten people in the past. The documentation for System.String.GetHashCode notes specifically that two identical strings can have different hash codes in different versions of the CLR, and in fact they do. Don't store string hashes in databases and expect them to be the same forever, because they won't be.

那么创建可以存储在数据库中的字符串的 HashCode 的正确方法是什么?

(请告诉我,我不是第一个在我编写的软件中留下这个错误的人!)

最佳答案

这取决于您希望散列具有的属性。例如,您可以只写这样的东西:

public int HashString(string text)
{
    // TODO: Determine nullity policy.

    unchecked
    {
        int hash = 23;
        foreach (char c in text)
        {
            hash = hash * 31 + c;
        }
        return hash;
    }
}

只要您记录散列是如何计算的,它就是有效的。它绝不是加密安全的或类似的东西,但你可以毫无问题地坚持下去。在序数意义上绝对相等的两个字符串(即没有应用文化平等等,完全逐个字符相同)将使用此代码生成相同的散列。

当您依赖未记录 哈希时,问题就来了 - 即遵循 GetHashCode() 但绝不能保证在不同版本之间保持相同的东西。 . 像 string.GetHashCode()

像这样编写和记录您自己的散列有点像在说“此敏感信息使用 MD5(或其他)进行散列”。只要它是一个定义明确的哈希,就可以了。

编辑:其他答案建议使用加密哈希,例如 SHA-1 或 MD5。我要说的是,在我们知道需要加密安全性而不仅仅是稳定性之前,没有必要经历将字符串转换为字节数组并对其进行散列的繁琐程序。当然,如果散列用于任何与安全相关的事情,那么行业标准散列正是您应该达到的目的。但是问题中的任何地方都没有提到这一点。

关于c# - 如何在 .net (c#) 中为可安全存储在数据库中的字符串创建 HashCode?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5154970/

相关文章:

c# - 对 0、1 和 2 的数组进行排序(进一步优化)

.net - 为什么将 IP 地址而不是域名传递给 System::Net::Mail::SmtpClient 会导致它抛出身份验证错误?

c# - 如何使用 Json.Net 序列化/反序列化带有自定义键的字典?

c# - 为什么 Response.Write 会破坏整个页面的对齐?

java - 以服务器模式运行h2数据库的优点

c# - 将数据表从 C# 动态传递到 Javascript

c# - 扩展方法对子类不起作用?

C# 显示所选文件夹中的所有文件

mysql - 从 .NET 在 MySQL 中存储数据的最佳方式

python - 将不同服务器上的 MySQL Server 数据库中的表复制到我的计算机