PyOTP: One Time Password Library

Vaibhav Mishra
2 min readJan 16, 2023

I always curious to know that how 2 factor authentication can be implement. So, After so many google search and blogs, I got to know PyOTP. PyOTP is a python library which can generate and verify one time password. It can be used to implement Two Factor or MFA authentication.

As a developer we make sure to follow below checklist which is mentioned in PyOTP documentation as well.

  • Ensure transport confidentiality by using HTTPS
  • Ensure HOTP/TOTP secret confidentiality by storing secrets in a controlled access database
  • Deny replay attacks by rejecting one-time passwords that have been used by the client
  • Throttle (rate limit) brute-force attacks against your application’s login functionality
  • When implementing a “greenfield” application, consider supporting FIDO U2F/WebAuthn in addition to HOTP/TOTP.

Lets do some implementation:

# import pyotp library
import pyotp

# Generate a random 32 bit value
key = pyotp.random_base32()


# This will give us a uri which will useful to generate QR Code
qr = pyotp.totp.TOTP(key).provisioning_uri('vaibhav.mishra2069@gmail.com')
print(qr)

The qr will return the value like otpauth://totp/vaibhav.mishra2069%40gmail.com?secret=A3OBQV1TQOE2BGKF23LDBVOLHKCS64IQ

Now we can append this uri with google chart uri to Genrate the QR Code
Google Chart URI https://www.google.com/chart?chs=200x200&chld=M|0&cht=qr&chl=
So final URI
https://www.google.com/chart?chs=200x200&chld=M|0&cht=qr&chl=otpauth://totp/vaibhav.mishra2069%40gmail.com?secret=A3OBQV1TQOE2BGKF23LDBVOLHKCS64IQ

Now we can scan the QR with any Authenticator app like google authenticator, after success scan it will give us a 6 digit code which further we can verify as a second client level.

# enter the value recived after scanning QR Code
enter_value = input("Enter the code received in mobile")

# value used to generate the QR
value_to_verify = pyotp.TOTP(key)

#condition to verify the code
if value_to_verify.verify(enter_value):
print("Hurray You did it")
else:
print("ahh! Wrong try")

Enjoy Happy Coding….. Suggestions are Welcome :-)

--

--

Vaibhav Mishra

I am passionate software developer working in different technologies like Python, ML, Django and JavaScript.