Python Program to Generate One-Time Password (OTP)


In this article, we will discuss how to generate a random one-time password (OTP). We will be using two modules in Python, namely the random and string modules, to accomplish this task. The random module provides relevant functions for generating random numbers, while the string module consists of numerous appropriate string constants. This application can be used for secure authentication or temporary access codes, catering to various aspects and requirements. We will present a few examples to illustrate the different approaches in which these programs can be applied.

Let's take an example to demonstrate the computation. The following examples are provided for understanding purposes, and we will go through the computation process step-by-step.

Example 1: Python Program to generate one-time password (OTP) by using random.choice() method

Code Explanation and Design Steps

Step 1: Open Jupyter Notebook in Anaconda prompt and start writing the code in its cell.

Step 2: Import ‘random’ and ‘string’ modules.

Step 3: Use this function ‘generate_otp’ which takes a parameter called ‘length’ which specifies the desired length of OTP.

Step 4: Define a variable ‘letters’ inside the function, this variable will store a combination of letters and digits (Uppercase, Lowercase, and digits), generated by ‘ascii_letters’ and ‘digits’ constants from the ‘string’ module.

Step 5: OTP will be generated from the pool of characters and digits and the string would be randomly selected characters and digits from the letters using ‘random.choice ()’ and generates OTP.

Step 6: Finally, Return the generated output.

Code for generate one-time password (OTP)

Example

import random    # Import random module
import string    # Import string module

def generate_otp(length): # Define the function with the parameter ‘length’
    letters = string.ascii_letters + string.digits # stores upper and lower 
                                   #character and digit in ‘letters’ variable
    otp = ''.join(random.choice(letters) for _ in range(length))
    return otp

otp_length = 8  # Length of the OTP
otp = generate_otp(otp_length) # Generate OTP
print("Generated OTP:", otp) # Print OTP

Output

Generated OTP: O6sbK1zM

This program generates a random one-time password that gives you in the form of an alphanumeric, and prints it to the console. It can be customized by varying the length of the OTP as needed.

Example 2: Python Program to generate one-time password (OTP) by using numeric OTP

Code Explanation and Design Steps

Step 1: Open Jupyter Notebook in the Anaconda prompt and start writing the code in its cell.

Step 2: Import ‘random’ modules to generate random numbers for the OTP.

Step 3: Use this function ‘generate_otp’ which takes a parameter called ‘length’ which specifies the desired length of OTP.

Step 4: Randomly generate the OTP number by appending random digits (0 - 9) to the OTP string length number of times.

Step 5: Function ‘validate_otp’ takes two parameters namely ‘user_input’ and ‘otp’.

Step 6: Compares the input with the ‘generated_ OTP’ and checks for true condition, returns True if they match, indicating a valid OTP, otherwise False.

Step 7: Set the desired length of OTP, here we took, its length of 6 but you can also change it to any length of OTP.

Step 8: Generate the OTP by calling the ‘generate_otp’ function and store it in the otp variable.

Step 9: Generated OTP will be printed on the console, and the user can see it.

Step 10: The user can enter the OTP by using the input function only in numerical form.

Step 11: Calling the ‘validate_otp’ function, validate the user's input by giving the user input and generate OTP as arguments.

Step 12: Result will store in a variable ‘vaild’.

Step 13: Check the value of ‘vaild’. Print the message which shows the OTP is either valid or invalid.

Code For Generating one-time password using an Alternate way.

Example

import random  # Import random module

def generate_otp(length): # Define the function with the parameter ‘length’
    otp = ""
    for _ in range(length): # Use for loop
        otp += str(random.randint(0, 9)) # 
    return otp

def validate_otp(user_input, otp):
    return user_input == otp

length = 6  # Length of the OTP

# Generate OTP
otp = generate_otp(length)
print("Generated OTP:", otp)

# Prompt user to enter OTP
user_input = 30847

# Validate OTP
if validate_otp(user_input, otp):
    print("OTP is valid!")
else:
   print("Invalid OTP!")

Output

Generated OTP: 348071
Invalid OTP!

Viewing The Result

This program will generate a random numerical OTP. Furthermore, it verifies by comparing it to the user's given input. This can be used for your specific needs as necessary.

In this article, we generate a one-time password (OTP) using two different ways to fulfill our needs the first one is alphanumeric and the second for only numeric OTP. We have shown in this document how to generate one-time password (OTP) elements that are divisible by a given number. These programs can be used in various domains for instance User Authentication, Password Reset, Two-Factor Authentication (2FA), Transaction Verification, Time-based OTP (TOTP), Secure File Sharing, and Captcha Replacement.

Updated on: 28-Aug-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements