独特价值哈希值=独特哈希值? [英] Hash of unique value = unique hash?

查看:156
本文介绍了独特价值哈希值=独特哈希值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

理论上,散列唯一值会产生一个唯一的值吗?假设我有一个包含2列的数据库表:id和code。 id是一个自动递增的int,代码是一个varchar。如果我这样做...
$ b $

  $ code = sha1($ id); 

...然后将$ code存储到与$ id相同的行中。我的代码栏也是唯一的吗?



如果我追加当前时间,那么该怎么办?例如:

  $ code = sha1($ id。time()); 

谢谢。

解决方案

一般来说,答案是否定的。这很简单:SHA-1具有2 ^ 160个不同的输出 - 160位,但还有更多的输入(例如,有2 ^ 320个不同的40字节字符串,并且它们不能全部映射到唯一的输出)。

给定足够的值子集,答案可能是。它取决于确切的算法和子集的大小:如果可能的输入数量小于可能的输出数量,则可能(但不能保证)。在考虑这一点时,记住生日悖论可能会有所帮助:碰撞不会随输入数量线性增加。


Theoretically does hashing a unique value yield a unique value?

Let's say I have a DB table with 2 columns: id and code. id is an auto-incrementing int and code is a varchar. If I do ...

$code = sha1($id);

... and then store $code into the same row as $id. Will my code column be unique as well?

What about if I append the current time? eg:

$code = sha1($id . time());

Thanks.

解决方案

In general, the answer is no. This is trivial to show: SHA-1 has 2^160 different outputs - 160 bits, but there are many more inputs that that (e.g., there are 2^320 different 40-byte strings, and they can't all map to a unique output).

Given a sufficient subset of values, the answer is maybe. It depends on the exact algorithm and the size of the subset: if the number of possible inputs is smaller than the number of possible outputs, then it is possible (but NOT guaranteed). When thinking about this, it may be helpful to keep the birthday paradox in mind: the probability of a collision does not increase linearly with the number of inputs.

这篇关于独特价值哈希值=独特哈希值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆