Last modified: Jun 01, 2025 By Alexander Williams
Install PyOTP for Time-based OTP in Python
Time-based One-Time Passwords (TOTP) are widely used for secure authentication. PyOTP is a Python library for generating and verifying OTPs. This guide will help you install and use it.
What is PyOTP?
PyOTP is a Python library for generating and verifying OTPs. It supports both time-based (TOTP) and counter-based (HOTP) OTPs. It is easy to use and highly secure.
Install PyOTP in Python
You can install PyOTP using pip, Python's package manager. Run the following command in your terminal.
pip install pyotp
This will download and install PyOTP along with its dependencies. If you need help with pip, check our guide on installing PyCryptodome.
Basic Usage of PyOTP
PyOTP makes it easy to generate and verify OTPs. Below is a simple example.
import pyotp
# Generate a secret key
secret_key = pyotp.random_base32()
# Create a TOTP object
totp = pyotp.TOTP(secret_key)
# Generate the current OTP
current_otp = totp.now()
print("Current OTP:", current_otp)
The random_base32
method generates a secure secret key. The TOTP
class creates a time-based OTP generator. The now
method returns the current OTP.
Verify an OTP
To verify an OTP, use the verify
method. Here's how.
# Verify the OTP
is_valid = totp.verify(current_otp)
print("Is OTP valid?", is_valid)
The verify
method checks if the OTP is valid. It returns True if valid and False otherwise.
Generate a Provisioning URI
PyOTP can generate a URI for adding the OTP to authenticator apps like Google Authenticator.
# Generate a provisioning URI
uri = totp.provisioning_uri(name="user@example.com", issuer_name="MyApp")
print("Provisioning URI:", uri)
The provisioning_uri
method creates a URI with the secret key. This URI can be scanned by authenticator apps.
Advanced Usage
PyOTP allows customization of OTP parameters. You can set the interval and digits.
# Custom TOTP with 60-second interval and 8 digits
custom_totp = pyotp.TOTP(secret_key, interval=60, digits=8)
print("Custom OTP:", custom_totp.now())
The interval sets the OTP validity period. The digits sets the OTP length.
Conclusion
PyOTP is a powerful library for implementing TOTP in Python. It is easy to install and use. Secure your applications with PyOTP today.
For more Python guides, check our articles on python-docx and PyTables.