Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

best practice to generate random token for forgot password

I want to generate identifier for forgot password . I read i can do it by using timestamp with mt_rand(), but some people are saying that time stamp might not be unique every time. So i am bit of confused here. Can i do it with using time stamp with this ?

Question
What's best practice to generate random/unique tokens of custom length?

I know there are lot of questions asked around here but i am getting more confused after reading different opinion from the different people.

like image 230
keen Avatar asked Sep 20 '13 07:09

keen


People also ask

How long should a password reset token be?

A minimum length of 8 characters. A not-too-low maximum length to discourage users from creating longer passphrases.

What is a password reset token?

For security reasons, passwords are never sent out across the Internet. Instead a token will be sent to your email instead. A token is a one-time generated link that contains numbers and letters that'll allow you to reset your password. It cannot be reused and is only valid for seven days.


2 Answers

In PHP, use random_bytes(). Reason: your are seeking the way to get a password reminder token, and, if it is a one-time login credentials, then you actually have a data to protect (which is - whole user account)

So, the code will be as follows:

//$length = 78 etc $token = bin2hex(random_bytes($length)); 

Update: previous versions of this answer was referring to uniqid() and that is incorrect if there is a matter of security and not only uniqueness. uniqid() is essentially just microtime() with some encoding. There are simple ways to get accurate predictions of the microtime() on your server. An attacker can issue a password reset request and then try through a couple of likely tokens. This is also possible if more_entropy is used, as the additional entropy is similarly weak. Thanks to @NikiC and @ScottArciszewski for pointing this out.

For more details see

  • http://phpsecurity.readthedocs.org/en/latest/Insufficient-Entropy-For-Random-Values.html
like image 83
Alma Do Avatar answered Sep 19 '22 16:09

Alma Do


This answers the 'best random' request:

Adi's answer1 from Security.StackExchange has a solution for this:

Make sure you have OpenSSL support, and you'll never go wrong with this one-liner

$token = bin2hex(openssl_random_pseudo_bytes(16)); 

1. Adi, Mon Nov 12 2018, Celeritas, "Generating an unguessable token for confirmation e-mails", Sep 20 '13 at 7:06, https://security.stackexchange.com/a/40314/

like image 22
YesItsMe Avatar answered Sep 20 '22 16:09

YesItsMe