1

假设我正在使用此代码生成哈希:

static void Main(string[] args) {

    string id = Guid.Parse("8681941A-76C2-4120-BC34-F800B5AAB5A5".ToLower()).ToString();
    string date = DateTime.Today.ToString("yyyy-MM-dd");

    Console.WriteLine(id);
    Console.WriteLine(date);

    using (System.Security.Cryptography.SHA512Managed hashTool = 
        new System.Security.Cryptography.SHA512Managed()) {

        Byte[] PasswordAsByte = System.Text.Encoding.UTF8.GetBytes(string.Concat(id, date));
        Byte[] EncryptedBytes = hashTool.ComputeHash(PasswordAsByte);
        hashTool.Clear();

        Console.WriteLine(Convert.ToBase64String(EncryptedBytes));

    }
    Console.ReadLine();
}

在一个真实世界的示例中,我将生成带有 GUID 和日期的哈希,正如您在示例中看到的那样。我将从数据库中获取这些值。

使用这种方法是否有可能获得具有不同值的相同哈希结果?

编辑:

正如我所指出的,我将从数据库中提取值。如您所料,Guid 是唯一的 id 键(如果我没有遇到奇迹并且 sql server 多次为我生成相同的 Guid)。datetime 值将作为记录的付款到期日。我在这里演示过,DateTime.Today但我绝对不会在产品上使用它。

4

3 回答 3

1

对于在同一天多次提取的给定 GUID,您肯定会遇到哈希冲突。例如,如果您为特定 GUID 生成哈希g,那么g在 2012-02-20 在 12:00 拉动会产生与您在 18:00 拉动相同的哈希,因为您只考虑日期,而不是时间。

对于不相关的 GUID,仍有可能发生哈希冲突。可能的哈希空间为 64 位,小于无穷大,这意味着根据鸽巢原理,必然存在重复。但是,这极不可能——事实上,您不太可能将其视为零。

于 2012-02-20T22:32:48.223 回答
0

I don't understand all those discussions? even if you have 10 million entries in your db the chance of a collision is like

0.000000000003% (looked that up for sha256, so the chances for sha512 are even less)

even if you have 100 million entries you shouldn't worry about it, and if you really want to be sure, put something in between the text and then hash it.

$newtext= wordwrap("mytexttexttext", 8, "myspliter", true);
于 2012-05-30T13:57:49.823 回答
0

就像在任何哈希函数中一样,它可能会非常非常罕见地发生。

一个好的散列函数会从两个相邻输入中产生不同的结果。SHA512 被认为是一种很好的哈希算法,因此在您的情况下应该不是问题。

于 2012-02-20T21:01:03.137 回答