DEV Community

Free Python Code
Free Python Code

Posted on

How To Generate and Verify OTP Codes Using Python and pyotp

Hi 🙂🖐

In this post, I will share with you How To Generate and Verify OTP Codes Using Python and pyotp.

PyOTP is a Python library for generating and verifying one-time passwords. It can be used to implement two-factor (2FA) or multi-factor (MFA) authentication methods in web applications and in other systems that require users to log in.

Step 1

Install pyotp

pip install pyotp
Enter fullscreen mode Exit fullscreen mode

Step 2

Generate secret key

import pyotp
print(pyotp.random_base32())
Enter fullscreen mode Exit fullscreen mode

Result

KDLZXFSPUQQPFG2HUFZNRHBTWJNZUATJ
Enter fullscreen mode Exit fullscreen mode

Step 3

Use this secret key to generate OTP codes

otp = pyotp.TOTP(s='KDLZXFSPUQQPFG2HUFZNRHBTWJNZUATJ')
print(otp.now())
Enter fullscreen mode Exit fullscreen mode

Result

088644
Enter fullscreen mode Exit fullscreen mode

Step 4

verify OTP Codes

otp.verify(otp.now())
Enter fullscreen mode Exit fullscreen mode

Result

True
Enter fullscreen mode Exit fullscreen mode
print(otp.now()) # 294950
time.sleep(30)
print(otp.verify('294950'))
Enter fullscreen mode Exit fullscreen mode

verify code after 30s this will return False because this code expired

Generate QRCode to use it in Google Authenticator, Authy, or another compatible app. Users can set up auth tokens in their apps easily by using their phone camera to scan otpauth:// QR codes provided by PyOTP.

You can use any browser extinction like:
https://chromewebstore.google.com/detail/%D9%85%D8%B5%D8%A7%D8%AF%D9%82%D8%A9/bhghoamapcdpbohphigoooaddinpkbai

Install pyqrcode

pip install pyqrcode
Enter fullscreen mode Exit fullscreen mode
import pyqrcode

secret_key = 'KDLZXFSPUQQPFG2HUFZNRHBTWJNZUATJ'
auth_data = pyotp.TOTP(s = secret_key).provisioning_uri(
    name = 'user123@test.com',
    issuer_name = 'Secure APP',
)

qr = pyqrcode.create(auth_data)
qr.png('qr.png')
Enter fullscreen mode Exit fullscreen mode

Result

Image description

I used Google Authenticator


otp = pyotp.TOTP(s='KDLZXFSPUQQPFG2HUFZNRHBTWJNZUATJ')

otp_code = '087035' # from Google Authenticator 

print(otp.verify(otp_code))

Enter fullscreen mode Exit fullscreen mode

Result

True
Enter fullscreen mode Exit fullscreen mode

Note

"After 30 seconds, this code will expire."

Top comments (0)