phpstringhashrandomunique

Hash of unique value = unique hash?


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.


Solution

  • In general, the answer is no. This is trivial to show: SHA-1 has 2^160 different outputs, but there are many more inputs than that. (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.