用於生成安全隨機數的 Python 模組


在本文中,我們將瞭解如何生成可有效用作密碼的安全隨機數。除了隨機數外,我們還可以新增字母和其他字元使其更好。

使用 secrets

secrets 模組有一個名為 choice 的函式,它可用於使用 for 迴圈和 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

使用 at least 條件

我們還可以強制要求小寫字母和大寫字母以及數字成為密碼生成器的一部分。這裡我們再次使用 secrets 模組。

示例

 即時演示

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 的一部分,我們可以使用 secrets 模組中的以下方法。

示例

 即時演示

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

更新時間:2020 年 7 月 9 日

239 次瀏覽

Kickstart Your 職業生涯

透過完成課程獲得認證

開始
廣告