Rajan Kumar

rajan

Founder & Programmer at HackersFriend Updated Aug. 2, 2019, 4:19 p.m. ⋅ 342 views

How to generate OTP (One time password) using python


In this article I'll talk about how can you generate random OTP using Python. OTP is used in a lot of works, like resetting password, email verification, mobile verification and a lot.

If you are developing something in which you need to register users, you are going to need to generate OTP.

OTP is expected to be hard to guess and it should be random. It can be all digit, all chracter, or mixture of it. In this article, I'll talk about generating numeric OTP and alphanumeric OTP. 

Approach

We will use python's random function to generate random numbers and this number will be used to generate our OTP.

 

Implementation

Generating 4 digit, all numeric OTP.

import math, random 

def OTPgenerator() :
	digits_in_otp = "0123456789"
	OTP = ""

# for a 4 digit OTP we are using 4 in range
	for i in range(4) : 
		OTP += digits[math.floor(random.random() * 10)] 

	return OTP 



# Main function 

print("Your 4 digit OTP is: ", OTPgenerator()) 
Your 4 digit OTP is: 5342

 

Generating alphanumeric OTP of 8 digit:

import math, random 
 
def OTPgenerator() : 

	digits_in_otp = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
	OTP = "" 
	length = len(string)
	for i in range(8) : 
		OTP += string[math.floor(random.random() * length)] 

	return OTP 


# Main Function 

print("Your 8 digit alphanumeric OTP is: ", OTPgenerator())
Your 8 digit alphanumeric OTP is: IaPtE2D8

 



arrow_upward Upvote

comment Comment

arrow_downward downvote



Go back to feed

HackersFriend Updates





View more


Events


Nov. 28, 2018, 5:30 p.m.

Python from zero to hero

place Delhi

View details


Aug. 13, 2018, 5:30 p.m.

Python from zero to hero

place Bangalore ( HackersFriend office BTM Layout)

View details