-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpython.py
More file actions
316 lines (261 loc) · 10.9 KB
/
python.py
File metadata and controls
316 lines (261 loc) · 10.9 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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
import re
import hashlib
import secrets
import string
import requests
from datetime import datetime
class PasswordSecurityTool:
"""Comprehensive password security analyzer and generator"""
def __init__(self):
self.common_passwords = [
'password', '123456', '12345678', 'qwerty', 'abc123',
'monkey', '1234567', 'letmein', 'trustno1', 'dragon',
'baseball', 'iloveyou', 'master', 'sunshine', 'ashley',
'bailey', 'passw0rd', 'shadow', '123123', '654321',
'superman', 'qazwsx', 'michael', 'football'
]
def analyze_password(self, password):
"""Comprehensive password strength analysis"""
print(f"\n🔍 Analyzing Password: {'*' * len(password)}")
print("=" * 60)
issues = []
score = 0
max_score = 100
# Length check
length = len(password)
if length < 8:
issues.append(" Too short (minimum 8 characters)")
score += 0
elif length < 12:
issues.append(" Length OK but could be longer (12+ recommended)")
score += 15
elif length < 16:
score += 25
else:
score += 30
# Character variety checks
has_lower = bool(re.search(r'[a-z]', password))
has_upper = bool(re.search(r'[A-Z]', password))
has_digit = bool(re.search(r'\d', password))
has_special = bool(re.search(r'[!@#$%^&*(),.?":{}|<>]', password))
char_types = sum([has_lower, has_upper, has_digit, has_special])
if char_types == 1:
issues.append(" Only one character type used")
score += 5
elif char_types == 2:
issues.append(" Only two character types")
score += 15
elif char_types == 3:
score += 25
else:
score += 35
if not has_lower:
issues.append(" No lowercase letters")
if not has_upper:
issues.append(" No uppercase letters")
if not has_digit:
issues.append(" No numbers")
if not has_special:
issues.append(" No special characters")
# Pattern detection
if re.search(r'(.)\1{2,}', password):
issues.append(" Repeated characters detected (e.g., 'aaa', '111')")
score -= 10
if re.search(r'(012|123|234|345|456|567|678|789|890|abc|bcd|cde)', password.lower()):
issues.append(" Sequential characters detected")
score -= 10
if re.search(r'\d{4}', password):
issues.append(" Contains 4+ consecutive digits (possible year/date)")
score -= 5
# Common password check
if password.lower() in self.common_passwords:
issues.append(" CRITICAL: This is a commonly used password!")
score -= 50
# Dictionary word check (simple)
if len(password) > 4 and password.isalpha():
issues.append(" Appears to be a dictionary word")
score -= 15
# Keyboard pattern check
keyboard_patterns = ['qwerty', 'asdfgh', 'zxcvbn', '1qaz2wsx', 'qazwsx']
for pattern in keyboard_patterns:
if pattern in password.lower():
issues.append(" Contains keyboard pattern")
score -= 15
break
# Entropy calculation
charset_size = 0
if has_lower: charset_size += 26
if has_upper: charset_size += 26
if has_digit: charset_size += 10
if has_special: charset_size += 32
entropy = length * (charset_size.bit_length() if charset_size > 0 else 0)
score += min(20, entropy // 10)
# Normalize score
score = max(0, min(100, score))
# Generate rating
if score >= 80:
rating = " STRONG"
color = "strong"
elif score >= 60:
rating = " MODERATE"
color = "moderate"
elif score >= 40:
rating = " WEAK"
color = "weak"
else:
rating = " VERY WEAK"
color = "very weak"
# Display results
print(f"\n Strength Score: {score}/100")
print(f" Rating: {rating}")
print(f" Length: {length} characters")
print(f" Character Types: {char_types}/4")
print(f" Estimated Entropy: {entropy} bits")
if issues:
print(f"\n Issues Found ({len(issues)}):")
for issue in issues:
print(f" {issue}")
else:
print("\n No major issues found!")
# Time to crack estimate (simplified)
self._estimate_crack_time(length, charset_size)
# Check if breached (using Have I Been Pwned API)
self._check_breach(password)
return {
'score': score,
'rating': color,
'length': length,
'issues': issues,
'entropy': entropy
}
def _estimate_crack_time(self, length, charset_size):
"""Estimate time to crack password"""
if charset_size == 0:
return
combinations = charset_size ** length
# Assume 10 billion guesses per second (modern hardware)
guesses_per_second = 10_000_000_000
seconds = combinations / guesses_per_second
if seconds < 1:
time_str = "< 1 second"
elif seconds < 60:
time_str = f"{int(seconds)} seconds"
elif seconds < 3600:
time_str = f"{int(seconds/60)} minutes"
elif seconds < 86400:
time_str = f"{int(seconds/3600)} hours"
elif seconds < 31536000:
time_str = f"{int(seconds/86400)} days"
elif seconds < 31536000000:
time_str = f"{int(seconds/31536000)} years"
else:
time_str = f"{int(seconds/31536000000)} billion years"
print(f"\n Time to Crack (estimated): {time_str}")
def _check_breach(self, password):
"""Check if password appears in known data breaches"""
print("\n Checking against breach databases...")
try:
# Hash the password (SHA-1)
sha1 = hashlib.sha1(password.encode('utf-8')).hexdigest().upper()
prefix = sha1[:5]
suffix = sha1[5:]
# Query Have I Been Pwned API (k-anonymity)
url = f"https://api.pwnedpasswords.com/range/{prefix}"
response = requests.get(url, timeout=5)
if response.status_code == 200:
hashes = response.text.split('\n')
for hash_line in hashes:
hash_suffix, count = hash_line.split(':')
if hash_suffix == suffix:
print(f" WARNING: Password found in {count.strip()} data breaches!")
print(" This password is publicly known and should NEVER be used.")
return True
print(" Password not found in known breaches")
return False
else:
print(" Unable to check breach database")
return None
except Exception as e:
print(f" Breach check failed: {str(e)}")
return None
def generate_password(self, length=16, include_symbols=True, include_numbers=True,
include_uppercase=True, include_lowercase=True,
exclude_ambiguous=False):
"""Generate a cryptographically secure password"""
charset = ""
if include_lowercase:
charset += string.ascii_lowercase
if include_uppercase:
charset += string.ascii_uppercase
if include_numbers:
charset += string.digits
if include_symbols:
charset += "!@#$%^&*()_+-=[]{}|;:,.<>?"
if exclude_ambiguous:
# Remove ambiguous characters: 0, O, l, 1, I
charset = charset.replace('0', '').replace('O', '').replace('l', '')
charset = charset.replace('1', '').replace('I', '')
if not charset:
return "Error: No character types selected!"
# Generate password
password = ''.join(secrets.choice(charset) for _ in range(length))
print(f"\n Generated Password: {password}")
print(f" Length: {length} characters")
print(f" Charset size: {len(charset)} characters")
# Analyze the generated password
self.analyze_password(password)
return password
def generate_passphrase(self, num_words=4):
"""Generate a memorable passphrase (XKCD-style)"""
# Common word list (you'd want a larger list in production)
words = [
'correct', 'horse', 'battery', 'staple', 'purple', 'monkey',
'dishwasher', 'dragon', 'coffee', 'mountain', 'river', 'ocean',
'forest', 'thunder', 'crystal', 'shadow', 'phoenix', 'tiger',
'elephant', 'penguin', 'falcon', 'rocket', 'silver', 'golden',
'diamond', 'marble', 'sunset', 'sunrise', 'moonlight', 'starlight'
]
selected_words = [secrets.choice(words) for _ in range(num_words)]
passphrase = '-'.join(selected_words)
print(f"\n Generated Passphrase: {passphrase}")
print(f" Tip: Passphrases are easier to remember than random passwords!")
return passphrase
def generate_pin(self, length=6):
"""Generate a secure PIN"""
pin = ''.join(secrets.choice(string.digits) for _ in range(length))
print(f"\n Generated PIN: {pin}")
print(f" Avoid: 123456, 000000, birth years, repeated digits")
return pin
# Example usage
if __name__ == "__main__":
tool = PasswordSecurityTool()
print(" PASSWORD SECURITY TOOL")
print("=" * 60)
# Test some passwords
print("\n" + "="*60)
print("DEMO 1: Analyzing Weak Passwords")
print("="*60)
tool.analyze_password("password123")
print("\n" + "="*60)
print("DEMO 2: Analyzing Strong Password")
print("="*60)
tool.analyze_password("Tr0ub4dor&3#xK")
# Generate secure passwords
print("\n" + "="*60)
print("DEMO 3: Generate Secure Password")
print("="*60)
tool.generate_password(length=16, include_symbols=True)
print("\n" + "="*60)
print("DEMO 4: Generate Passphrase")
print("="*60)
tool.generate_passphrase(num_words=4)
print("\n" + "="*60)
print("DEMO 5: Generate PIN")
print("="*60)
tool.generate_pin(length=6)
print("\n Tool demonstration complete!")
print("\n Usage Tips:")
print("Use different passwords for each account")
print("Enable 2FA whenever possible")
print("Use a password manager")
print("Change passwords if breached")