Python One Time Password Library

2.9.0 · active · verified Sun Mar 29

PyOTP is a Python library for generating and verifying one-time passwords, supporting both Time-Based One-Time Passwords (TOTP) from RFC 6238 and HMAC-Based One-Time Passwords (HOTP) from RFC 4226. It is widely used to implement two-factor (2FA) or multi-factor (MFA) authentication in various systems, compatible with apps like Google Authenticator. The library is actively maintained, with its current version being 2.9.0, and follows a regular release cadence.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to generate a random secret, create a Time-Based One-Time Password (TOTP) object, generate a provisioning URI for client applications (like Google Authenticator), and then verify an OTP. It also shows a basic example for HMAC-Based One-Time Passwords (HOTP).

import pyotp
import time

# Generate a random base32 secret key
secret = pyotp.random_base32()
print(f"Generated Secret: {secret}")

# Create a TOTP object
totp = pyotp.TOTP(secret)

# Generate a provisioning URI for Google Authenticator (or similar)
# In a real app, 'alice@example.com' would be the user's email
# 'SecureApp' would be the name of your application
uri = totp.provisioning_uri(name="alice@example.com", issuer_name="SecureApp")
print(f"Provisioning URI: {uri}")

# In a real application, you'd render this URI as a QR code for the user to scan.
# For demonstration, we'll manually get a code.

# Simulate getting an OTP code from the user (e.g., from their authenticator app)
current_otp = totp.now()
print(f"Current OTP (will change every 30s): {current_otp}")

# Verify the OTP code
# You might wait a few seconds to demonstrate validity windows
# user_input_otp = input("Enter the OTP from your authenticator app: ")
user_input_otp = current_otp # For demonstration, assume correct input

if totp.verify(user_input_otp):
    print("OTP verified successfully!")
else:
    print("Invalid OTP.")

# For HOTP (counter-based):
hotp = pyotp.HOTP(secret)
initial_count = 0
first_hotp = hotp.at(initial_count)
print(f"HOTP for count {initial_count}: {first_hotp}")

# Verify HOTP
# In a real app, you'd store and increment the counter after each successful verification
if hotp.verify(first_hotp, initial_count):
    print("HOTP verified successfully!")

view raw JSON →