基于字符串生成唯一哈希代码

本文关键字:唯一 哈希 代码 字符串 | 更新日期: 2023-09-27 17:49:23

我有以下两个字符串:

var string1 = "MHH2016-05-20MASTECH HOLDINGS, INC. Financialshttp://finance.yahoo.com/q/is?s=mhhEDGAR Online FinancialsHeadlines";
var string2 = "CVEO2016-06-22Civeo upgraded by Scotia Howard Weilhttp://finance.yahoo.com/q/ud?s=CVEOBriefing.comHeadlines";

乍一看,这两个字符串是不同的,但使用GetHashCode method时它们的哈希代码是相同的。

var hash = 0;
var total = 0;
foreach (var x in string1) //string2
{
    //hash = x * 7;
    hash = x.GetHashCode();
    Console.WriteLine("Char: " +  x + " hash: " + hash + " hashed: " + (int) x);
    total += hash;
}

两个字符串的总计为620438779。是否有其他方法可以返回更独特的哈希代码?我需要基于字符串中的字符的哈希代码是唯一的。尽管这两个字符串不同,代码也能正常工作,但这两个串加起来是相同的。如何改进此代码以使其更加独特?

基于字符串生成唯一哈希代码

string.GetHashCode确实不适合真正的哈希:

警告

哈希代码用于在基于哈希表的集合中进行有效的插入和查找。哈希代码不是一个永久值。因此:

  • 不要序列化哈希代码值或将其存储在数据库中
  • 不要将哈希代码用作从带键集合中检索对象的键
  • 不要使用哈希代码代替加密哈希函数返回的值。对于加密散列,请使用从System.Security.Cryptography.HashAlgorithmSystem.Security.Cryptography.KeyedHashAlgorithm类派生的类
  • 不要通过测试哈希代码的相等性来确定两个对象是否相等。(不相等的对象可以具有相同的哈希代码。(若要测试相等性,请调用ReferenceEqualsEquals方法

并且具有高的重复可能性。

考虑HashAlgorithm.ComputeHash。样本略有更改,使用SHA256而不是MD5,正如@zaph建议的那样:

static string GetSha256Hash(SHA256 shaHash, string input)
{
    // Convert the input string to a byte array and compute the hash.
    byte[] data = shaHash.ComputeHash(Encoding.UTF8.GetBytes(input));
    // Create a new Stringbuilder to collect the bytes
    // and create a string.
    StringBuilder 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();
}
using System.Security.Cryptography;
string data="test";
byte[] hash;
using (MD5 md5 = MD5.Create())
{
    md5.Initialize();
    md5.ComputeHash(Encoding.UTF8.GetBytes(data));
    hash = md5.Hash;
}

hash是一个16字节的数组,反过来您可以将其转换为一些十六进制字符串或base64编码的字符串进行存储。

编辑:

那个散列码的用途是什么?

hash(x) != hash(y)可以导出x!=y,但

hash(x) == hash(y),您通常不能导出x==y