gpt4 book ai didi

c# - 根据字符串生成唯一的哈希码

转载 作者:行者123 更新时间:2023-12-04 01:25:40 32 4
gpt4 key购买 nike

我有以下两个字符串:

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 确实不适合实际散列:

Warning

A hash code is intended for efficient insertion and lookup in collections that are based on a hash table. A hash code is not a permanent value. For this reason:

  • Do not serialize hash code values or store them in databases.
  • Do not use the hash code as the key to retrieve an object from a keyed collection.
  • Do not use the hash code instead of a value returned by a cryptographic hashing function. For cryptographic hashes, use a class derived from the System.Security.Cryptography.HashAlgorithm or System.Security.Cryptography.KeyedHashAlgorithm class.
  • Do not test for equality of hash codes to determine whether two objects are equal. (Unequal objects can have identical hash codes.) To test for equality, call the ReferenceEquals or Equals method.

且极有可能出现 duplicates
考虑 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();
}

关于c# - 根据字符串生成唯一的哈希码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38043954/

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