生成密码重置密码
我正在做一个允许用户重置密码的模块。我注意到大多数网站都提供了一个确认链接,其中包含具有唯一哈希值的查询字符串。
我的问题是:每次同一用户请求忘记密码时,如何生成这个唯一的哈希值?我应该将此哈希存储在数据库中并稍后使用它进行验证吗?会安全吗?或者我应该创建某种生成一次性密码的算法?如何生成 OTP?
I'm doing a module which allow users to reset password. I noticed how most websites they provide a confirmation link which contain query string that has a unique hash.
My question is: How can I generate this unique hash each time the same user request forgot password? Should I store this hash in database and use it for verification later on? Will it be safe? Or should I create some sort of algorithm which generate one-time password? How can I generate a OTP?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的,您应该
关于重置令牌(或任何你想称呼它的东西)的生成似乎有很多困惑。请阅读我链接到的答案,不要用哈希值和弱种子重新发明轮子。
Yes, you should
There seems to be a lot a confusion about the generation of the reset token (or whatever you want to call it). Please read the answer I've linked to and don't reinvent the wheel with hashes and weak seeds.
只需使用带有用户 ID、用户盐(对用户密码加盐,对吧?)和伪随机数据的哈希函数就可以了:
$pwd_reset_hash = hash ( 'sha256' , $user_id . $user_salt, uniqid( "",true));
将其存储在数据库中(与请求时间一起)作为该用户的重置密钥
当用户尝试使用它时,检查哈希是否与用户匹配以及时间是否正确最近的(例如“重置代码有效期为 3 小时”或类似的内容)
在使用或过期时将其从数据库中删除
Just using some hash function with user's ID, user's salt (you salt the user's password, right?) and pseudo-random data should be OK:
$pwd_reset_hash = hash ( 'sha256' , $user_id . $user_salt, uniqid("",true));
Store it in the DB (together with time of request) as the reset key for this user
When the user tries to use it, check that the hash matches the user and that the time is recent (e.g. "reset code is valid for 3 hours" or something like that)
delete it from DB when used or expired
正确的方法确实是生成某种随机的东西并将其存储在数据库中。密码更改后,您将从表中删除相关记录,以便该链接无法再次使用。
正如在其他响应中已经说过的,对用户 ID 进行 SHA1 或 MD5 结合 microtime 和一些盐字符串通常是一个安全的选择。
The way to go is indeed generate some kind of random thing and storing it in the database. As soon as the password is changed you remove the relevant record from the table so that the link cant be used again.
As said already in the other responses, doing a SHA1 or an MD5 of the userid, combined with microtime and some salt string is usually a safe bet.
1) 要生成唯一的哈希值,请混合当前时间、用户 ID 和一些盐(文本)。例如,如果您的网站是 mysite.com,则使用以下代码:
这将创建一个很好的哈希值。
2) 是的,将其存储在数据库中。
3)是的,只要您在固定时间段后使哈希过期,它就是安全的。
4) 不,生成一次性密码通常会惹恼用户。
1) To generate the unique hash, mix current-time, user-id and some salt (text). For example, if your website is mysite.com, then use this code:
This will create a nice hash.
2) Yes, store it in database.
3) Yes, as long as you expire the hash after a fixed period of time, it will be secure.
4) No, generating one-time password usually annoys users.