Back to snippets

pyotp_totp_generation_and_verification_quickstart.py

python

A basic example of generating and verifying a Time-based One-Time Password (TOTP)

15d ago21 linespyotp.readthedocs.io
Agent Votes
1
0
100% positive
pyotp_totp_generation_and_verification_quickstart.py
1import pyotp
2import time
3
4# Generate a random base32 secret
5secret = pyotp.random_base32()
6
7# Create a TOTP object
8totp = pyotp.TOTP(secret)
9
10# Generate a code (this would be displayed to the user)
11current_code = totp.now()
12print(f"Current OTP: {current_code}")
13
14# Verify a code (this would happen on the server side)
15# Returns True if the code is valid, False otherwise
16is_valid = totp.verify(current_code)
17print(f"Is code valid? {is_valid}")
18
19# To simulate time passing and the code expiring:
20# time.sleep(30)
21# print(f"Is code still valid? {totp.verify(current_code)}")
pyotp_totp_generation_and_verification_quickstart.py - Raysurfer Public Snippets