ในบทความนี้เราจะเรียนรู้วิธาสร้างตัวเลขสุ่มที่ปลอดภัย (Cryptographically secure) สำหรับใช้เป็นรหัสผ่าน หรือ token ต่างๆ โดยใช้โมดูล secrets ซึ่งออกแบบมาสำหรับวัตถุประสงค์ด้านความปลอดภัยโดยเฉพาะ
การสร้างรหัสผ่านแบบง่ายด้วย secrets.choice
ฟังก์ชัน secrets.choice สามารถสุ่มตัวอักษรจากชุดที่กำหนดได้ ใช้ลูป for ร่วมกับ range เพื่อสร้างรหัสผ่านยาวตามที่ต้องการ
ตัวอย่าง
import secrets
import string
allowed_chars = string.ascii_letters + string.digits + string.punctuation
pswd = ''.join(secrets.choice(allowed_chars) for i in range(8))
print("The generated password is:\n", pswd)
ผลลัพธ์
The generated password is: $pB7WY
การสร้างรหัสผ่านที่มีเงื่อนไข (At least conditions)
บังคับให้รหัสผ่านมีตัวพิมพ์เล็ก ตัวพิมพ์ใหญ่ และตัวเลขอย่างน้อย 3 ตัว โดยใช้ลูป while ตรวจสอบเงื่อนไขก่อน break
ตัวอย่าง
import secrets
import string
allowed_chars = string.ascii_letters + string.digits + string.punctuation
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 password is:\n", pswd)
break
ผลลัพธ์
The generated password is: p7$7nS2w
การสร้าง Token แบบสุ่มสำหรับ URL
โมดูล secrets มีฟังก์ชันสำหรับสร้าง token แบบต่างๆ:
token_bytes(n)- ไบต์สุ่ม n ไบต์token_hex(n)- สตริง hex สุ่ม n ไบต์token_urlsafe(n)- สตริง URL-safe สุ่ม (ค่า default 32 ไบต์)
ตัวอย่าง
import secrets
# ไบต์สุ่ม
tkn1 = secrets.token_bytes(8)
# สตริง hex สุ่ม
tkn2 = secrets.token_hex(8)
# URL-safe token
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
สรุป: ควรใช้โมดูล secrets แทน random เมื่อต้องการความปลอดภัยทางการเข้ารหัส เช่น รหัสผ่าน Token API และ Session ID