ในบทความนี้ เราจะมาดูกันว่าเราจะสร้างตัวเลขสุ่มที่ปลอดภัยได้อย่างไร ซึ่งสามารถใช้เป็นรหัสผ่านได้อย่างมีประสิทธิภาพ นอกจากตัวเลขสุ่มแล้ว เรายังเพิ่มตัวอักษรและอักขระอื่นๆ เพื่อทำให้ดีขึ้นได้
มีความลับ
โมดูล secrets มีฟังก์ชันที่เรียกว่าตัวเลือก ซึ่งสามารถใช้สร้างรหัสผ่านที่มีความยาวที่ต้องการได้โดยใช้ฟังก์ชัน for loop และ range
ตัวอย่าง
import secrets
import string
allowed_chars = string.ascii_letters + string.digits + string.printable
pswd = ''.join(secrets.choice(allowed_chars) for i in range(8))
print("The generated password is: \n",pswd) ผลลัพธ์
การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -
The generated password is: $pB7WY
มีเงื่อนไขเป็นอย่างน้อย
เราสามารถบังคับเงื่อนไขต่างๆ เช่น ตัวพิมพ์เล็กและตัวพิมพ์ใหญ่ ตลอดจนตัวเลขให้เป็นส่วนหนึ่งของตัวสร้างรหัสผ่าน ที่นี่เราใช้โมดูลความลับอีกครั้ง
ตัวอย่าง
import secrets
import string
allowed_chars = string.ascii_letters + string.digits + string.printable
while True:
pswd = ''.join(secrets.choice(allowed_chars) for i in range(8))
if (any(c.islower() for c in pswd) and any(c.isupper()
for c in pswd) and sum(c.isdigit() for c in pswd) >= 3):
print("The generated pswd is: \n", pswd)
break ผลลัพธ์
การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -
The generated pswd is: p7$7nS2w
สุ่มโทเค็น
เมื่อจัดการกับ URL หากคุณต้องการให้โทเค็นสุ่มเป็นส่วนหนึ่งของ URL เราสามารถใช้วิธีการด้านล่างจากโมดูลความลับ
ตัวอย่าง
import secrets
# A random byte string
tkn1 = secrets.token_bytes(8)
# A random text string in hexadecimal
tkn2 = secrets.token_hex(8)
# random URL-safe text string
url = 'https://thename.com/reset=' + secrets.token_urlsafe()
print("A random byte string:\n ",tkn1)
print("A random text string in hexadecimal: \n ",tkn2)
print("A text string with url-safe token: \n ",url) ผลลัพธ์
การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -
A random byte string: b'\x0b-\xb2\x13\xb0Z#\x81' A random text string in hexadecimal: d94da5763fce71a3 A text string with url-safe token: https://thename.com/reset=Rd8eVookY54Q7aTipZfdmz-HS62rHmRjSAXumZdNITo