How do you create “good” random md5 hashes in php?

2019-01-29 07:56发布

问题:

For several cases I would need to create random md5 hashes. Do you know what the best / most secure ways of doing this are?

Some use cases

  • Verifying an email address
  • Resetting passwords
  • Some kind of session id used for authentication, instead of password (eg: when someone hits "remember me", I would not like to store the pass in a cookie)

Background

I know that rand() should not be used for security relevant applications. For that reason I went with:

md5( uniqid(mt_rand(),true) );

Now I read in the php manual about uniqid(), that it must not be used for security purposes. Which kind of makes sense because it usually just gives something like a timestamp.

But is it fine when combined with a random prefix - mt_rand() - like I do, or is there something better that should be used in this case?

Thx in advance!

回答1:

You don't need "MD5 hashes", you simply need a random string of characters. These need not have anything to do with MD5 at all. So all you need is a good PRNG. For instance:

$token = mcrypt_create_iv($rawLength, MCRYPT_DEV_URANDOM);
// or
$token = openssl_random_pseudo_bytes($rawLength);
// or
$token = file_get_contents('/dev/urandom', false, null, 0, $rawLength);

Then base64_encode or bin2hex the raw value to get an ASCII character string.



回答2:

I just finished devloping a fairly robust Bash script that generates decent quality md5sum's. You can find it https://code.google.com/p/gen-uniq-id/source/browse/gen_uniq_id.bsh

It has the following features:

A time stamp down to nanoseconds,

A user-modifiable amount of collected data from /dev/urandom (default is .25 seconds),

A user-modifiable amount of collected mouse-movement data (default is .25 seconds, just use xinput --list and run it once with -M<your_mouse_device_id>),

A dynamically modifiable text statement that may be set as a default or sent in dynamically with each call e.g. -s"$(history | tail -5)".

You can probably easily port over to PHP or just call it from PHP via shell_exec:
$random_md5sum = shell_exec('/path/to/gen_uniq_id.bsh -m1 -r1 -s"favorite quote$(history | tail -5)"');



回答3:

you can use md5(date()) to get unique keys.Very simple way.. Try it.