TimSparrow TimSparrow - 2 years ago 133
PHP Question

PHP: Hash function that generates a string with a given length

I need a function that creates a hash from an arbitrary parameter set (or a serialized string) with a fixed length (say 5), as I need these hashes to serve as keys in an external database with a limited key length (so md5 will not work).

Is there such a function? Or should I use md5 and then substring it?

Answer Source

Having a hash of a small fixed length is practically worthless, from both a security and a practicality point of view. Say you have a datablock string of 512 bytes (64 characters) length, how is that going to be hashed into a unique string of 5 characters (40 bytes)?

Say you do develop a "small" hash, it'll be something you'll have made yourself so it will be inherently insecure so you're going to all this trouble for not much return.

  • Why do you need a hash at all?
    • What security risk are you trying to mitigate?
  • Why are you not using more secured password_hash functions or similar?
  • Don't roll your own.

You could try and truncate your MD5() hash but really, it's a 32 character hash and you're cutting it down to five, that means you have a huge chance of collisions, where two source values make the same hash. This is already one of the issues of md5, and that's with 32 characters, with 5, you're trying to stop a sinking ocean liner by bailing out with a teacup.

Man the lifeboats instead.

You might as well set up a random bytes generator such as OpenSSL_random _pseudo_bytes or random_bytes, to give you random blocks, and then associated them with an Associative database table.

So a possible solution:

$bytes = random_bytes(10);

Their table:

 id  | their data
 10  |  gedgfdgfdhfd 
 11  |  dgdgfdhfdhf  
 15  |  dfsgdfhdffdhf

Your table:

  id  | key | random_hash
   1  | 10  | 7bc4cb77c27d8b0a49eb
   2  | 15  | a49ebc89b757bc4ccb4e

So the user knows the random_hash and you can equiate this to the id of the row from the external table that you need. This would take a bit of setup work and I make a lot of assumptions about your situation but it's a possible solution.

Anything you do with hashes of say 5 characters is going to not be worth the time you spend writing the code ( Source ):

enter image description here

Also note that this graphic is from 2010 and so now, computers are even faster and more capable of breaking your hash ( Source ).

Overall : Don't do it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download