基于String生成唯一的哈希代码

som*_*ude 10 c#

我有以下两个字符串:

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";
Run Code Online (Sandbox Code Playgroud)

乍一看这两个字符串是不同的,但是它们的哈希码使用的是相同的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;
        }
Run Code Online (Sandbox Code Playgroud)

两个字符串的总计最终为620438779.还有另一种方法会返回更独特的哈希码吗?我需要基于字符串中的字符使哈希码唯一.虽然两个字符串都不同并且代码正常工作,但这两个字符串恰好相同.如何改进此代码以使其更加独特?

Ale*_*exD 28

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

警告

哈希码旨在用于在基于哈希表的集合中进行有效插入和查找.哈希码不是永久值.为此原因:

  • 不要序列化哈希码值或将它们存储在数据库中.
  • 不要使用哈希代码作为从密钥集合中检索对象的密钥.
  • 不要使用哈希代码而不是加密哈希函数返回的值.对于加密哈希,请使用从System.Security.Cryptography.HashAlgorithmSystem.Security.Cryptography.KeyedHashAlgorithm类派生的类.
  • 不要测试哈希码的相等性以确定两个对象是否相等.(不等的对象可以具有相同的哈希码.)要测试相等性,请调用ReferenceEqualsor Equals方法.

并且很有可能重复.

考虑HashAlgorithm.ComputeHash.@zaph建议:将样本略微更改为使用SHA256而不是MD5.

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();
}
Run Code Online (Sandbox Code Playgroud)

  • @SirajMansour 加密哈希确实是为了避免冲突而设计的。在我的 iPhone 上,我可以在 0.950 毫秒内计算 1MB 文件的 SHA-256 哈希值,这足够快吗?顺便说一句,在我的手机上,SHA-256 比 MD5 稍快。 (2认同)

lex*_*999 5

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;
}
Run Code Online (Sandbox Code Playgroud)

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

编辑:

那个哈希码的目的是什么?

hash(x) != hash(y)你可以得出x!=y,但是

hash(x) == hash(y)不能得出x==y一般!

  • 这会导致性能下降,安全散列并不意味着用于避免冲突。 (2认同)
  • @zaph 它们是为安全目的而设计的。尽管它可以达到避免碰撞的目的,但这并不意味着它是正确的工具。 (2认同)