问题描述
我想生成忘记密码的标识符.我读到我可以通过在mt_rand()中使用时间戳来做到这一点,但是有人说时间戳记可能并非每次都是唯一的.所以我有点困惑.我可以通过使用时间戳来做到这一点吗?
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.
推荐答案
在PHP中,使用 random_bytes()
.原因:您正在寻找一种获取密码提醒令牌的方法,并且,如果它是一次性登录凭据,则实际上您有一个数据需要保护(即-整个用户帐户)
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)
因此,代码如下:
//$length = 78 etc
$token = bin2hex(random_bytes($length));
更新: 以前的答案指的是uniqid()
,如果存在安全性问题,而不仅仅是唯一性问题,那是不正确的. uniqid()
本质上只是具有某些编码的microtime()
.有一些简单的方法可以对服务器上的microtime()
进行准确的预测.攻击者可以发出密码重置请求,然后尝试几个可能的令牌.如果使用more_entropy,这也是可能的,因为附加熵同样很弱.感谢 @NikiC 和 @ScottArciszewski 指出这一点.
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
这篇关于生成随机令牌以忘记密码的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!