when the user want to reset his password , I send to his email a 6 digits code, then I check if the user enter the matched code !
I am generating the code using rand function :
$code = rand ( 100000, 999999 );
is it safe to do that ?
when the user want to reset his password , I send to his email a 6 digits code, then I check if the user enter the matched code !
I am generating the code using rand function :
$code = rand ( 100000, 999999 );
is it safe to do that ?
No. Let's say you want to reset a privileged user's password. All an attacker has to do is issue a bunch of resets for an unprivileged account (or multiple accounts) that they control to predict the next random value. Which means they can then request a password reset for the privileged user (e.g. "Admin") and then take over the account.
More information:
If you really want unpredictable random numbers for any sort of security feature, feel free to use this library that I wrote and maintain:
https://github.com/resonantcore/lib/blob/master/src/Secure.php
$iRandom = \Resonantcore\Lib\Secure::random(100000, 999999);
Note that this is soon going to be adopted/refactored into this repository in the near future (and the functions offered may even make it into the PHP 7 core): https://github.com/SammyK/php-src-csprng
$iRandom = random_int(100000, 999999);
It's not there yet, though. My code works today.
If you don't trust me, you can also check out Anthony Ferrara's wonderful RandomLib project: https://github.com/ircmaxell/RandomLib
$factory = new RandomLib\Factory;
$generator = $factory->getGenerator(new SecurityLib\Strength(SecurityLib\Strength::MEDIUM));
$iRandom = $generator->generateInt(100000, 999999);
Don't use rand()
or mt_rand()
for any authentication (or authentication bypass) purpose. Ever.
Also, you may want to use something with a larger brute-force space than a 6 digit number. A hex-encoded 32-byte string should be sufficient for stopping both practical and all known theoretical attacks.