最終更新 10 months ago

這段程式碼定義了一個 PasswordGenerator 類別,依據指定的類型("easy" 或 "hard")和密碼長度,隨機產生密碼。其中 "easy" 模式生成的密碼僅包含去除易混淆字元的大小寫英文字母和數字,而 "hard" 模式則包含了所有大小寫字母及標點符號。程式最後示範如何使用該生成器產生 10 個隨機密碼。

timmy revised this gist 10 months ago. Go to revision

No changes

timmy revised this gist 10 months ago. Go to revision

No changes

timmy revised this gist 10 months ago. Go to revision

1 file changed, 38 insertions

secure_password_generator.py(file created)

@@ -0,0 +1,38 @@
1 + import random
2 + import string
3 +
4 +
5 + class PasswordGenerator:
6 + def __init__(self, type, length=12):
7 +
8 + self.length = length
9 + self.type = type
10 +
11 + def generate_password(self):
12 + if self.type == "easy":
13 + # 存儲大小寫英文字母和數字,避免使用可能有歧義的字符
14 + characters = (
15 + string.ascii_uppercase.replace("O", "")
16 + + string.ascii_lowercase.replace("l", "")
17 + + string.digits.replace("0", "").replace("1", "")
18 + )
19 + # 隨機選擇 self.length 個字符
20 + password = "".join(random.choice(characters) for i in range(self.length))
21 + elif self.type == "hard":
22 + # 存儲大小寫英文字母和罕見的字元
23 + characters = string.ascii_letters + string.punctuation
24 + # 隨機選擇 self.length 個字符
25 + password = "".join(random.choice(characters) for i in range(self.length))
26 + return password
27 +
28 +
29 + # 建立一個長度為 12 的密碼產生器物件,用來產生 "Easy to read" 的密碼
30 + generator = PasswordGenerator("easy")
31 +
32 + # 建立一個長度為 10 的密碼產生器物件,用來產生 "Easy to read" 的密碼
33 + # generator = PasswordGenerator("easy", 10)
34 +
35 +
36 + # 產生 10 個隨機密碼
37 + for i in range(10):
38 + print(generator.generate_password())
Newer Older