gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 03:54:39 27 4
gpt4 key购买 nike

引自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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com