I wrote a function in PHP
to generate a random password (only 0-9a-zA-Z) for my app. The resulting password must be cryptography secure, and as random as possible. I.E. the passwords are sensitive.
The big trick I do is shuffle $possible
characters everytime, so even if mt_rand()
is not truely random, it should not be predictable.
Any recommended changes or security issues in my function? Is using openssl_random_pseudo_bytes()
instead of mt_rand()
really going to make the algorithm stronger and more secure?
public function generate_random($length = 15) {
$random = "";
$possible = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$possible = str_shuffle($possible);
$maxlength = strlen($possible);
if ($length > $maxlength) {
$length = $maxlength;
}
$i = 0;
while ($i < $length) {
$random .= substr($possible, mt_rand(0, $maxlength-1), 1);
$i++;
}
return $random;
}
Thanks.