Write a Python program to generate a One Time Password (OTP)

How to generate a One Time Password (OTP) in Python. Write a python program to generate OTP.

How to generate a One Time Password (OTP)?

One Time Password (OTP) is a secret key that is substantial for only one login meeting or transaction in a PC or an advanced gadget. Presently OTPs are utilized in pretty much every help like Internet Banking, online exchanges, and so on. They are a blend of 4 or 6 numeric digits or a 6-digit alphanumeric.

random.random() and math.floor() function can be used to produce arbitrary OTP which is predefined in the Python library.

What is a One Time Password (OTP)?

Input: OTP Generation

Output: OTP of 6 digits: 683687

Algorithm to generate a One Time Password (OTP):

  •       Import random.
  •       Assign a variable which will contain all alphanumeric values from 0-9, a-z, and A-Z.
  •       Iterate using a for loop defining the length of the OTP.
  •       Call the random.random() and random.floor() function within the loop.
  •       Return the variable.

Python program to generate a One Time Password (OTP).

Method 1: using only digits

import math, random
def generateOTP():
  digits = "0123456789"
  OTP = ""
  print("OTP Generation")
  for i in range(6):
    	OTP += digits[math.floor(random.random() * 10)]
  return OTP

if __name__ == "__main__":
  print("OTP of 6 digits:", generateOTP())

Output: Printing the generated OTP

Method 2: using alphanumeric

import math, random
def generateOTP():
  string = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  OTP = ""
  length = len(string)
  print("OTP Generation")
  for i in range(6):
    	OTP += string[math.floor(random.random() * length)]

  return OTP

if __name__ == "__main__":
  print("OTP of length 6:", generateOTP())

Output: Printing the generated OTP