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?
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.
password_hashfunctions or similar?
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.
$bytes = random_bytes(10); var_dump(bin2hex($bytes));
id | their data -----|----- 10 | gedgfdgfdhfd 11 | dgdgfdhfdhf 15 | dfsgdfhdffdhf
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 ):
Also note that this graphic is from 2010 and so now, computers are even faster and more capable of breaking your hash ( Source ).