c# - 字符串的持久哈希码

标签 c# string hash hashcode gethashcode

<分区>

我想为字符串生成一个整数哈希码,它将永远保持不变;即相同的字符串应该总是产生相同的哈希码。

散列不必是加密安全的,它不会用于密码或敏感数据。

我的第一次尝试是使用 .net 框架的 string.GetHashCode() 函数。 然而,在阅读资料后,我发现了以下评论:

// We want to ensure we can change our hash function daily. 
// This is perfectly fine as long as you don't persist the
// value from GetHashCode to disk or count on String A 
// hashing before string B.  Those are bugs in your code.
hash1 ^= ThisAssembly.DailyBuildNumber;

这似乎表明哈希码不会保持不变。

如果是这样,框架是否有另一种方法来生成可重复的哈希码?还是 GetHashCode 中的代码是实现我自己的代码的合理起点?

我正在寻找尽可能轻便和快速的东西。
我找到了 System.Security.Cryptography.MD5 ,但对于一个简单的 int32 哈希码来说,这似乎有点过分了,我担心开销。至少它需要从字符串到字节数组的转换,从字节数组到 int 的转换,或者为每个散列创建一个新的 MD5() 对象,或者管理一些静态共享 MD5 对象().

最佳答案

没有内置的、跨版本稳定的方法来获取字符串的哈希码。

您可以只复制现有的 GetHashCode() 代码,但排除将内部版本号添加为种子的部分,并且不要使用不安全的调用来保护自己免受实现细节更改的影响。

这是 64bit GetHashCode() 的完全托管版本它不使用任何随机化,并且将为所有 future 版本的 .NET 返回相同的值(只要 int ^ char 的行为永远不会改变)。

public static class StringExtensionMethods
{
    public static int GetStableHashCode(this string str)
    {
        unchecked
        {
            int hash1 = 5381;
            int hash2 = hash1;

            for(int i = 0; i < str.Length && str[i] != '\0'; i += 2)
            {
                hash1 = ((hash1 << 5) + hash1) ^ str[i];
                if (i == str.Length - 1 || str[i+1] == '\0')
                    break;
                hash2 = ((hash2 << 5) + hash2) ^ str[i+1];
            }

            return hash1 + (hash2*1566083941);
        }
    }
}

关于c# - 字符串的持久哈希码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36845430/

相关文章:

C# Windows 桌面应用程序

c# - 在 ASP.NET MVC 中显示文本区域的新行

php - 相同的盐或不同的盐

c# - 更新匿名方法中的 ref 参数

c# - 了解多线程 C#

c++ - 在 std::string 上执行正则表达式搜索和替换

encryption - 使用 AES 进行文件完整性检查,替换 MD5

javascript - 检测导航至 <a name ="latest-topics"></a>

c# - `Add-Type` C# 6+ 功能抛出错误

ios - 在 iOS 中将字符串转换为十六进制?