-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
78 lines (65 loc) · 2.58 KB
/
main.py
File metadata and controls
78 lines (65 loc) · 2.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import string
import secrets
def generate_password(length=12, use_special=True, use_numbers=True):
# Check the minimum length to avoid an infinite loop
if length < 8:
raise ValueError("Password length must be at least 8 characters.")
# Define basic character sets
letters = string.ascii_letters
digits = string.digits
special = string.punctuation
# Build the character pool based on user options
alphabet = letters
if use_numbers:
alphabet += digits
if use_special:
alphabet += special
while True:
# Generate the password using the secure secrets module
password = ''.join(secrets.choice(alphabet) for _ in range(length))
# Validate whether the password meets all requirements
has_upper = any(c.isupper() for c in password)
has_lower = any(c.islower() for c in password)
has_digit = any(c.isdigit() for c in password) or not use_numbers
has_spec = any(c in special for c in password) or not use_special
# If the password is strong enough, return it
if has_upper and has_lower and has_digit and has_spec:
return password
# --- USER INTERFACE ---
print("--- Secure Password Generator ---")
try:
# Get password length with validation
while True:
try:
length = int(input("Enter password length (min. 8, max. 128 characters): "))
if length < 8:
print("Password too short! Setting length to 8.")
length = 8
elif length > 128:
print("Password too long! Setting length to 128.")
length = 128
break
except ValueError:
print("Error: Length must be a number. Please try again.")
# Get options with validation
while True:
use_special = input("Include special characters? (y/n): ").lower()
if use_special in ['y', 'n']:
use_special = use_special == 'y'
break
print("Error: Please answer 'y' or 'n'.")
while True:
use_numbers = input("Include numbers? (y/n): ").lower()
if use_numbers in ['y', 'n']:
use_numbers = use_numbers == 'y'
break
print("Error: Please answer 'y' or 'n'.")
# Call the function with selected parameters
new_password = generate_password(length, use_special, use_numbers)
print(f"\nYour secure password: {new_password}")
except ValueError as e:
# Handle validation errors
print(f"Error: {e}")
except Exception as e:
# Handle unexpected errors
print(f"Unexpected error: {e}")