-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpassword_generator.py
More file actions
256 lines (217 loc) · 8.12 KB
/
Copy pathpassword_generator.py
File metadata and controls
256 lines (217 loc) · 8.12 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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
"""
Password Generator - Core Module
Author: RIFINOO
License: MIT License
A professional, secure password generator using Python's secrets module
for cryptographically strong password generation.
"""
import secrets
import string
import math
import logging
from typing import Optional, Dict, Tuple
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('password_generator.log'),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
class PasswordGenerator:
"""Professional password generator with security features."""
def __init__(self):
"""Initialize the password generator."""
self.uppercase = string.ascii_uppercase
self.lowercase = string.ascii_lowercase
self.numbers = string.digits
self.special = "!@#$%^&*()_+-=[]{}|;:,.<>?"
def generate_password(
self,
length: int = 16,
include_uppercase: bool = True,
include_lowercase: bool = True,
include_numbers: bool = True,
include_special: bool = True
) -> Optional[str]:
"""
Generate a cryptographically strong password.
Args:
length: Desired password length (minimum 4)
include_uppercase: Include uppercase letters
include_lowercase: Include lowercase letters
include_numbers: Include numbers
include_special: Include special characters
Returns:
Generated password or None if invalid parameters
"""
if length < 4:
logger.warning("Password length must be at least 4 characters")
return None
# Build character set based on user preferences
charset = ""
if include_uppercase:
charset += self.uppercase
if include_lowercase:
charset += self.lowercase
if include_numbers:
charset += self.numbers
if include_special:
charset += self.special
if not charset:
logger.warning("At least one character type must be enabled")
return None
# Generate password using secrets module
password = ''.join(secrets.choice(charset) for _ in range(length))
# Ensure at least one character from each selected type is included
password = self._ensure_character_types(
password, length, include_uppercase, include_lowercase,
include_numbers, include_special, charset
)
logger.info(f"Password generated successfully (length: {length})")
return password
def _ensure_character_types(
self,
password: str,
length: int,
include_uppercase: bool,
include_lowercase: bool,
include_numbers: bool,
include_special: bool,
charset: str
) -> str:
"""
Ensure password contains at least one character from each enabled type.
Args:
password: Generated password
length: Password length
include_uppercase: Whether uppercase is enabled
include_lowercase: Whether lowercase is enabled
include_numbers: Whether numbers are enabled
include_special: Whether special chars are enabled
charset: Full character set
Returns:
Password with guaranteed character types
"""
password_list = list(password)
required_chars = []
if include_uppercase:
required_chars.append(secrets.choice(self.uppercase))
if include_lowercase:
required_chars.append(secrets.choice(self.lowercase))
if include_numbers:
required_chars.append(secrets.choice(self.numbers))
if include_special:
required_chars.append(secrets.choice(self.special))
# Replace random positions with required characters
for i, char in enumerate(required_chars):
if i < len(password_list):
password_list[i] = char
# Shuffle the password to avoid predictable patterns
for i in range(len(password_list) - 1, 0, -1):
j = secrets.randbelow(i + 1)
password_list[i], password_list[j] = password_list[j], password_list[i]
return ''.join(password_list)
def calculate_entropy(self, password: str) -> float:
"""
Calculate password entropy in bits.
Args:
password: Password to analyze
Returns:
Entropy in bits
"""
if not password:
return 0.0
# Determine character set size
charset_size = 0
if any(c in self.uppercase for c in password):
charset_size += len(self.uppercase)
if any(c in self.lowercase for c in password):
charset_size += len(self.lowercase)
if any(c in self.numbers for c in password):
charset_size += len(self.numbers)
if any(c in self.special for c in password):
charset_size += len(self.special)
if charset_size == 0:
return 0.0
# Entropy = log2(charset_size^length)
entropy = len(password) * math.log2(charset_size)
return round(entropy, 2)
def check_strength(self, password: str) -> Dict[str, any]:
"""
Evaluate password strength.
Args:
password: Password to evaluate
Returns:
Dictionary with strength analysis
"""
if not password:
return {
'strength': 'Very Weak',
'score': 0,
'feedback': ['Password is empty']
}
score = 0
feedback = []
# Length checks
if len(password) >= 12:
score += 2
feedback.append("✓ Good length (12+ characters)")
elif len(password) >= 8:
score += 1
feedback.append("⚠ Moderate length (8-11 characters)")
else:
feedback.append("✗ Too short (less than 8 characters)")
# Character variety checks
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)
has_special = any(c in self.special for c in password)
char_types = sum([has_upper, has_lower, has_digit, has_special])
if char_types == 4:
score += 2
feedback.append("✓ Contains all character types")
elif char_types == 3:
score += 1
feedback.append("⚠ Contains 3 character types")
else:
feedback.append("✗ Limited character variety")
# Specific checks
if has_upper:
feedback.append("✓ Contains uppercase letters")
if has_lower:
feedback.append("✓ Contains lowercase letters")
if has_digit:
feedback.append("✓ Contains numbers")
if has_special:
feedback.append("✓ Contains special characters")
# Entropy check
entropy = self.calculate_entropy(password)
if entropy >= 80:
score += 2
feedback.append(f"✓ Excellent entropy ({entropy} bits)")
elif entropy >= 60:
score += 1
feedback.append(f"⚠ Good entropy ({entropy} bits)")
else:
feedback.append(f"✗ Low entropy ({entropy} bits)")
# Determine strength level
if score >= 6:
strength = "Very Strong"
elif score >= 4:
strength = "Strong"
elif score >= 2:
strength = "Moderate"
elif score >= 1:
strength = "Weak"
else:
strength = "Very Weak"
return {
'strength': strength,
'score': score,
'entropy': entropy,
'length': len(password),
'feedback': feedback
}