Repository navigation
Expand file tree
/
Copy pathrandom_password_generator.py
More file actions
110 lines (90 loc) · 3.84 KB
/
Copy pathrandom_password_generator.py
File metadata and controls
110 lines (90 loc) · 3.84 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# --------------------------------------------------------------------------
# Random Password Generator
# Generates a strong, random password based on user-defined length and complexity.
# --------------------------------------------------------------------------
import random
import string
def generate_password(length=12, use_letters=True, use_numbers=True, use_symbols=True):
"""
Generates a secure password based on specified criteria.
Args:
length (int): The desired length of the password.
use_letters (bool): Include upper and lowercase letters.
use_numbers (bool): Include digits (0-9).
use_symbols (bool): Include common symbols (!@#$%^&*).
Returns:
str: The generated password, or a message if criteria are invalid.
"""
if not any([use_letters, use_numbers, use_symbols]):
return "Error: You must select at least one character type."
if length <= 0:
return "Error: Password length must be greater than zero."
# Define the character sets
characters = ""
required_chars = [] # Ensures at least one of each selected type is included
if use_letters:
letters = string.ascii_letters
characters += letters
required_chars.append(random.choice(letters))
if use_numbers:
numbers = string.digits
characters += numbers
required_chars.append(random.choice(numbers))
if use_symbols:
# Common secure symbols
symbols = "!@#$%^&*()-_+=[]{}|;:,.<>?"
characters += symbols
required_chars.append(random.choice(symbols))
# Calculate remaining length needed for random filler
remaining_length = length - len(required_chars)
# Generate random filler characters
if remaining_length < 0:
# If the required characters already exceed the desired length
# This will only happen if the user inputs a very small length (e.g., 2)
random_filler = []
password_list = required_chars[:length]
else:
random_filler = [random.choice(characters) for _ in range(remaining_length)]
password_list = required_chars + random_filler
# Shuffle the list to ensure the required characters aren't always at the start
random.shuffle(password_list)
# Join the list of characters to form the final password string
return "".join(password_list)
def main():
"""
Main function to handle user interaction for password generation.
"""
print("\n--- Python Random Password Generator ---")
# Get password length
while True:
try:
length = int(input("Enter desired password length (e.g., 16): "))
if length > 0:
break
else:
print("Length must be a positive number.")
except ValueError:
print("Invalid input. Please enter a whole number.")
# Get complexity preferences
def get_preference(prompt):
while True:
choice = input(f"{prompt} (y/n): ").strip().lower()
if choice in ['y', 'n']:
return choice == 'y'
else:
print("Invalid input. Please enter 'y' for yes or 'n' for no.")
use_letters = get_preference("Include letters (A-Z, a-z)?")
use_numbers = get_preference("Include numbers (0-9)?")
use_symbols = get_preference("Include symbols (!@#$)?")
print("\nGenerating password...")
# Generate and print the password
password = generate_password(length, use_letters, use_numbers, use_symbols)
# Check if the result is an error message
if password.startswith("Error"):
print(password)
else:
print("\n" + "="*40)
print(f"Generated Password: {password}")
print("="*40)
if __name__ == "__main__":
main()