secure_password_generator.py
· 1.3 KiB · Python
Brut
import random
import string
class PasswordGenerator:
def __init__(self, type, length=12):
self.length = length
self.type = type
def generate_password(self):
if self.type == "easy":
# 存儲大小寫英文字母和數字,避免使用可能有歧義的字符
characters = (
string.ascii_uppercase.replace("O", "")
+ string.ascii_lowercase.replace("l", "")
+ string.digits.replace("0", "").replace("1", "")
)
# 隨機選擇 self.length 個字符
password = "".join(random.choice(characters) for i in range(self.length))
elif self.type == "hard":
# 存儲大小寫英文字母和罕見的字元
characters = string.ascii_letters + string.punctuation
# 隨機選擇 self.length 個字符
password = "".join(random.choice(characters) for i in range(self.length))
return password
# 建立一個長度為 12 的密碼產生器物件,用來產生 "Easy to read" 的密碼
generator = PasswordGenerator("easy")
# 建立一個長度為 10 的密碼產生器物件,用來產生 "Easy to read" 的密碼
# generator = PasswordGenerator("easy", 10)
# 產生 10 個隨機密碼
for i in range(10):
print(generator.generate_password())
| 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()) |
| 39 |