0

Possible Duplicate:
Generate a unique value for a combination of two numbers

Is there a way to hash two user ids (integers), and to always get a unique hash for a given pair of user ids?

For example:

a = hash( x , y );

and

b = hash( y , x );

In the above example, a and b must always be equivalent for any given pair of ids in the range of an INT(11) (MySQL).

Plain PHP is the programming environment.

Any suggestions welcome guys...

Community
  • 1
  • 1
Donal.Lynch.Msc
  • 3,365
  • 12
  • 48
  • 78
  • 1
    An INT(11) does not exist. The (11) is just the display width, and since the max value of an (unsigned) int is 10 characters wide, and it might be zerofilled (when specified) to 11 characters. More [here](http://dev.mysql.com/doc/refman/5.0/en/numeric-types.html). But that's offtopic. ;) – CodeCaster Sep 01 '11 at 09:59

2 Answers2

4

Summing the numbers doesn't make a unique hash. For instance, 1+3 == 2+2. This does:

function myHash( $id1, $id2 ) {
    $ids = array( $id1, $id2 ); // or func_get_args() to support variable number
    sort( $ids );
    return md5( implode( '-', $ids ); // md5() == any other hashing function
}

myHash( x, y ) == myHash( y, x );
Rijk
  • 11,032
  • 3
  • 30
  • 45
  • 1
    This is really unlikely to have a collision, but it's not guaranteed. (But if you do find a collision, please publish your result in a cryptography journal - people would be very interested in it). – user9876 Sep 01 '11 at 10:05
  • 1
    @user9876 You can "easily" check that function for collisions, since the input set is known (-2147483648 to 2147483647 for an int, 0 to 4294967295 for unsigned int). You could run a test that checks all combinations and see whether collisions occur. But then again, you don't have to hash, you can simply store "N1 + separator + N2", and since (at least an MD5) hash would take up 32 characters, storage shouldn't be a problem there. – CodeCaster Sep 01 '11 at 10:16
0

use http://php.net/manual/en/function.md5.php

like this: $hash = md5(sprintf("%05d/%05d", $id1, $id2));

Quamis
  • 10,924
  • 12
  • 50
  • 66