r/PHPhelp • • May 14 '20

Creating a 2 factor authentication system

I'm trying to build a very simple authentication system by sending a temporary code via e-mail. I would like to know if you see any major flaws with this workflow:

  1. user logs in with username and password

  2. a temporary code gets generated, hashed and stored in the database row for that user

  3. an e-mail with the unhashed code gets sent

  4. the user enters the code and it is compared to the de-hashed code from the database

  5. the user gets access and everyone lived happily ever after

10 Upvotes

8 comments sorted by

2

u/[deleted] May 14 '20

Step 4 is wrong. You dont dehash anything. Hashing is one way. So what you do is hash the code the user typed in and compare that to the hash in the database

1

u/Yakuwari May 14 '20

Yeah, you're right. I meant to use password_verify

1

u/[deleted] May 14 '20

cool yeah in that case it looks good

4

u/[deleted] May 14 '20

Adding code expiration makes it more secure.

2

u/[deleted] May 14 '20

4) What do you mean de-hashed? Hashing is a one-way operation. You may be talking about encryption, which can be en/de-crypted.

You can read about the differences here: https://gcn.com/articles/2013/12/02/hashing-vs-encryption.aspx

You should use hashing, not encrypting. Albeit it might not matter as much if the password is hashed and it's only the OTP that's not encrypted.

Otherwise, it seems fine.

2

u/VerifiablyMrWonka May 14 '20

I'd set the stored hash as a concatenation of the random value and a second random value you set in the users session. That way the code will only work for the currently logged in browser/device

1

u/wh33t May 14 '20

Seems legit.

0

u/[deleted] May 14 '20

[deleted]

1

u/Yakuwari May 15 '20 edited May 15 '20

How would you go about in order to make the code expire after 15 minutes with PHP even if the user closes the site?

EDIT: Would it work to use sleep() ?