I've written a code that should generate pseudo-random strings. I tried to improve the randomness by gathering entropy from user's mouse movements.
Here is my code :
// As described in the PHP documentation
function make_seed() {
list($usec, $sec) = explode(' ', microtime());
return (float) $sec + ((float) $usec * 100000);
}
function rand_string($entropy, $length, $chars) {
mt_srand($entropy . make_seed()); // Here is the important line
$return = '';
$charlen = strlen($chars);
for ($i=0;$i<$length;$i++) {
$rand = mt_rand(0, $charlen) - 1;
$return .= substr($chars, $rand, 1);
}
return $return;
}
$entropy = '18421828841384386426948169412548'; // Mouse movements, changes everytime
echo rand_string($entropy, 20, 'abcdefghijklmnopqrstuvwxz');
I ran the function a couple of times. Some values show up very frequently, so this is a very weak function. I can't understand why. Is there a limit on mt_srand's parameter ? Does it have to be a number ?
Edit : mt_srand() seed must be an INT.
mt_randis seeded randomly by default anyway, so one shouldn't need to seed it manually unless you have a specific need to override the default seeding. Also, are you resetting the seed repeatedly in the same program run? If so, that's also not necessary, and could reduce your randomness.improve the randomnessNicely spoken =p