Implementing OTP

I want to implement a one-time password system for one of my sites to allow the very occasional visitor to bypass the payment system.

The steps I have so far are:

  • generate otp
  • store in db
  • email otp to user


  • user enters otp
  • retrieve from db
  • check it’s valid
  • if valid, delete from db and redirect page
  • if not deny access

I can’t help thinking I’ve missed something.

Do they only get one shot at it? Or how many attempts to get it right? How long do you retain it following failure?

1 Like

Hmm, yes. One of the things I’ve not thought through.

I guess I would give them 3 tries and delete the entry after the 3rd failure.

And not just failure, it may never get used, but you would keep it available for so long, then delete.

I’m now wondering if I even need to / should store the password as the password generation algo will create the same password if generated within the specified time period.

??? That would be bad. If this occurs, people are going to figure out the algorithm (or how to break it) and you’ve now opened a back door.

I would think a OTP would:

  • have the same basic restrictions as a normal password (3 tries before locked out, whatever)
  • would only be good for a limited time (say 1/2 an hour) to allow for email delays.
  • would force a password change immediately.
1 Like

I’ve used split tokens in the past for OTP. Slightly harder to implement than just a random string, but a lot better security wise.

1 Like

Thanks guys. I was thinking of using the algorithm here:

It seems secure enough but I’m having trouble with my brain, figuring out how to implement it.

My application doesn’t require users to log in which is where it differs from most use cases.

I do not see any problem also.

Create a token (the proposed function looks good for me), store it in the database and enable a login with this token.
After login delete the token.
The token should have an expiring date of whatever you want.

Of course this token is not user connected. So the user can share it to others if he wants.
Also it’s pretty easy to create as many token as I want for myself, if I only need to provide an new email address to get a new token. So maybe it’s not really a one time thing in that case.