Python 隨機密碼產生器

在 Python 中產生安全的隨機密碼。學習使用 random 模組和字串常數來建立強大的安全工具。

在編輯器中嘗試

概述

密碼產生器需要存取隨機數字函數並將它們對應到 ASCII 字元集。

Python 標準函式庫提供了「random」和「secrets」來執行無偏隨機選擇。

對於加密或高安全性需求,Python 的「secrets」模組比「random」模組更受青睞,因為它在加密方面很強大。

程式碼和執行輸出

組合大寫、小寫、數字和符號以輸出 16 個字元的安全字串。

password_gen.py
在編輯器中嘗試
import random
import string

def generate_password(length=12):
    # Combine all character sets
    characters = string.ascii_letters + string.digits + string.punctuation
    
    # Randomly select characters until the desired length
    password = ''.join(random.choice(characters) for _ in range(length))
    return password

print("Generating 3 secure passwords:")
for i in range(3):
    print(f"Password {i+1}: {generate_password(16)}")
端子輸出
Generating 3 secure passwords:
Password 1: a!7T#nP@zQ8k*L1w
Password 2: xY9^vB4$mC2&pR5j
Password 3: dF3%hK6*tW9@nM1q
(Output will be random during real execution)

逐步實施

  • 自动分配用户凭证
  • 為滲透測試套件產生模擬數據
  • 用於伺服器部署的系統管理實用程式腳本

常見問題解答

「隨機」模組對於真實密碼安全嗎?

“random”模組是偽隨機的。為了在生產中產生實際的安全密碼,您應該使用 Python 的「secrets」模組,該模組利用作業系統級安全熵。

相關主題