Python程序生成一次性密码(OTP)
一次性密码 (OTP) 是一种仅对计算机或数字设备中的一次登录会话或交易有效的密码。现在,OTP 几乎用于所有服务,如网上银行、在线交易等。它们通常是 4 位或 6 位数字或 6 位字母数字的组合。
random()函数可用于生成随机库中预定义的随机 OTP。让我们看看如何使用Python生成 OTP。
Used Function:
random.random(): This function returns any random number between 0 to 1.
math.floor(): It returns floor of any floating number to a integer value.
Using the above function pick random index of string array which contains all the possible candidates of a particular digit of the OTP.
示例 #1:生成 4 位数字 OTP
Python3
# import library
import math, random
# function to generate OTP
def generateOTP() :
# Declare a digits variable
# which stores all digits
digits = "0123456789"
OTP = ""
# length of password can be changed
# by changing value in range
for i in range(4) :
OTP += digits[math.floor(random.random() * 10)]
return OTP
# Driver code
if __name__ == "__main__" :
print("OTP of 4 digits:", generateOTP())
Python3
# import library
import math, random
# function to generate OTP
def generateOTP() :
# Declare a string variable
# which stores all string
string = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
OTP = ""
length = len(string)
for i in range(6) :
OTP += string[math.floor(random.random() * length)]
return OTP
# Driver code
if __name__ == "__main__" :
print("OTP of length 6:", generateOTP())
Python3
# Importing random to generate
# random string sequence
import random
# Importing string library function
import string
def rand_pass(size):
# Takes random choices from
# ascii_letters and digits
generate_pass = ''.join([random.choice( string.ascii_uppercase +
string.ascii_lowercase +
string.digits)
for n in range(size)])
return generate_pass
# Driver Code
password = rand_pass(10)
print(password)
输出:
OTP of 4 digits: 3211
示例 #2:生成长度为 6 的字母数字 OTP
Python3
# import library
import math, random
# function to generate OTP
def generateOTP() :
# Declare a string variable
# which stores all string
string = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
OTP = ""
length = len(string)
for i in range(6) :
OTP += string[math.floor(random.random() * length)]
return OTP
# Driver code
if __name__ == "__main__" :
print("OTP of length 6:", generateOTP())
输出:
OTP of length 6: pyelJl
示例 #3:使用字符串常量
Python3
# Importing random to generate
# random string sequence
import random
# Importing string library function
import string
def rand_pass(size):
# Takes random choices from
# ascii_letters and digits
generate_pass = ''.join([random.choice( string.ascii_uppercase +
string.ascii_lowercase +
string.digits)
for n in range(size)])
return generate_pass
# Driver Code
password = rand_pass(10)
print(password)
输出:
2R8gaoDKqn