One Time Password (OTP) Generator in Python

December 25, 2022 - by admin

OTP stands for One-Time Password. It is a password that is valid for only one login session or transaction, on a computer system or other digital device. OTPs are typically generated by a software program or a hardware device, and are designed to be used for secure authentication and to protect against replay attacks.

The importance of OTP is that it provides an additional level of security for user authentication by ensuring that even if a password is compromised, it can only be used once. This makes it much more difficult for an attacker to gain unauthorized access to a system or account.

In Python, there are several libraries available that can be used to generate and validate OTPs. One popular library is pyotp, which is a Python library for generating and validating OTPs based on the HOTP and TOTP algorithms.

Here’s an example of how you can use pyotp to generate a TOTP (time-based one-time password) in Python:

# import library
import math 
import random
# function to generate OTP
def generateOtpCode(length) :
    digits = "0123456789"
    OTP = ""
    for i in range(length) :
        OTP += digits[random.randint(0,len(digits)-1)]
    return OTP
if __name__ == "__main__" :
    print("Your OTP Code is : ", generateOtpCode(6))

Advanced Python OTP Code generator by using pyotp library

import pyotp

# Generate a secret key
secret = pyotp.random_base32()

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

# Generate a one-time password
otp =

if totp.verify(otp):
    print("OTP verified")
    print("OTP invalid")

You can also use other libraries such as python-otp and onetimepass to generate and validate OTPs in Python.

Related Post

Top 10 Python Library

Python vs PHP