Skip to content

Commit 3e8d3f7

Browse files
committed
Added password generator script and README
1 parent 837d8a8 commit 3e8d3f7

File tree

2 files changed

+354
-0
lines changed

2 files changed

+354
-0
lines changed

Python/README.md

Lines changed: 154 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,154 @@
1+
# Password Generator
2+
3+
A secure and customizable password generator written in Python. This tool allows you to create strong passwords with various character types and provides strength analysis for generated passwords.
4+
5+
## Features
6+
7+
- 🔒 **Cryptographically Secure**: Uses Python's `secrets` module for secure random generation
8+
- ⚙️ **Customizable**: Choose password length and character types
9+
- 📊 **Strength Analysis**: Get detailed feedback on password strength
10+
- 🔢 **Batch Generation**: Generate multiple passwords at once
11+
- 🖥️ **Dual Interface**: Both interactive and command-line modes
12+
- 🎯 **Smart Defaults**: Ensures at least one character from each selected type
13+
14+
## Installation
15+
16+
### Prerequisites
17+
- Python 3.6 or higher
18+
19+
### Setup
20+
1. **Clone or download** the script to your local machine
21+
2. **Make executable** (optional):
22+
```bash
23+
chmod +x password_generator.py
24+
```
25+
26+
## Usage
27+
28+
### Interactive Mode (Recommended for beginners)
29+
30+
Run the script without arguments to enter interactive mode:
31+
32+
```bash
33+
python3 password_generator.py
34+
```
35+
36+
or if executable:
37+
38+
```bash
39+
./password_generator.py
40+
```
41+
42+
You'll be prompted for:
43+
- Password length (default: 12)
44+
- Character types to include (lowercase, uppercase, digits, symbols)
45+
- Number of passwords to generate (default: 1)
46+
47+
### Command Line Mode
48+
49+
For quick password generation or scripting:
50+
51+
#### Basic Usage
52+
```bash
53+
# Generate one strong password with default settings (12 characters, all types)
54+
python3 password_generator.py
55+
56+
# Generate a 16-character password
57+
python3 password_generator.py -l 16
58+
59+
# Generate 5 passwords
60+
python3 password_generator.py -n 5
61+
```
62+
63+
#### Advanced Options
64+
```bash
65+
# Generate password without symbols
66+
python3 password_generator.py --no-symbols
67+
68+
# Generate numeric PIN (6 digits)
69+
python3 password_generator.py -l 6 --no-lower --no-upper --no-symbols
70+
71+
# Generate letters-only password
72+
python3 password_generator.py --no-digits --no-symbols
73+
74+
# Force interactive mode
75+
python3 password_generator.py --interactive
76+
```
77+
78+
### Command Line Arguments
79+
80+
| Argument | Short | Description | Default |
81+
|----------|-------|-------------|---------|
82+
| `--length` | `-l` | Password length | 12 |
83+
| `--number` | `-n` | Number of passwords to generate | 1 |
84+
| `--no-lower` | | Exclude lowercase letters | Included |
85+
| `--no-upper` | | Exclude uppercase letters | Included |
86+
| `--no-digits` | | Exclude digits | Included |
87+
| `--no-symbols` | | Exclude symbols | Included |
88+
| `--interactive` | | Force interactive mode | Auto-detect |
89+
90+
## Examples
91+
92+
### Strong Password
93+
```bash
94+
python3 password_generator.py -l 16
95+
# Example output: Xk8#pL$2*mQ9!vR@
96+
```
97+
98+
### Multiple Passwords
99+
```bash
100+
python3 password_generator.py -n 3 -l 10
101+
```
102+
Output:
103+
```
104+
Generated 3 passwords:
105+
1. aB3$fG8!kL
106+
2. pQ9@mN2#rT
107+
3. xY7!vW4$zU
108+
```
109+
110+
### Application-Specific Passwords
111+
```bash
112+
# API Key style (letters and digits only)
113+
python3 password_generator.py -l 32 --no-symbols
114+
115+
# PIN code
116+
python3 password_generator.py -l 6 --no-lower --no-upper --no-symbols
117+
118+
# Memorable password (letters only)
119+
python3 password_generator.py -l 14 --no-digits --no-symbols
120+
```
121+
122+
## Password Strength Ratings
123+
124+
The generator provides strength analysis based on:
125+
- **Length**: Minimum 8 characters, good at 12+
126+
- **Character diversity**: Lowercase, uppercase, digits, symbols
127+
- **Overall rating**:
128+
- **Strong**: Meets 6+ criteria
129+
- **Good**: Meets 4-5 criteria
130+
- **Weak**: Meets 3 or fewer criteria
131+
132+
## Security Notes
133+
134+
- ✅ Uses cryptographically secure random number generation
135+
- ✅ Ensures minimum character requirements are met
136+
- ✅ Properly shuffles final passwords
137+
- ✅ No passwords are stored or transmitted
138+
- ⚠️ Generated passwords are displayed in terminal - clear your history if needed
139+
140+
## Troubleshooting
141+
142+
### Common Issues
143+
144+
**"Password length too short" error**
145+
- Solution: Increase password length or reduce character type requirements
146+
147+
**No characters selected**
148+
- Solution: Enable at least one character type (lowercase, uppercase, digits, or symbols)
149+
150+
**Permission denied**
151+
- Solution: Make script executable with `chmod +x password_generator.py`
152+
153+
### Requirements
154+
- Python 3.6+ (for `secrets` module and type hints)

Python/password_generator.py

Lines changed: 200 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,200 @@
1+
#!/usr/bin/python3
2+
3+
import random
4+
import string
5+
import secrets
6+
import argparse
7+
from typing import List, Dict
8+
9+
10+
class PasswordGenerator:
11+
def __init__(self):
12+
self.character_sets = {
13+
'lowercase': string.ascii_lowercase,
14+
'uppercase': string.ascii_uppercase,
15+
'digits': string.digits,
16+
'symbols': string.punctuation
17+
}
18+
19+
def generate_password(self, length: int = 12, **requirements) -> str:
20+
"""
21+
Generate a password with specified requirements
22+
23+
Args:
24+
length: Length of the password
25+
requirements: Boolean flags for character types
26+
- lowercase: Include lowercase letters
27+
- uppercase: Include uppercase letters
28+
- digits: Include digits
29+
- symbols: Include symbols
30+
31+
Returns:
32+
Generated password string
33+
"""
34+
# Default requirements if none specified
35+
if not any(requirements.values()):
36+
requirements = {
37+
'lowercase': True,
38+
'uppercase': True,
39+
'digits': True,
40+
'symbols': True
41+
}
42+
43+
# Build character pool based on requirements
44+
character_pool = ""
45+
required_chars = []
46+
47+
for char_type, include in requirements.items():
48+
if include and char_type in self.character_sets:
49+
chars = self.character_sets[char_type]
50+
character_pool += chars
51+
# Add at least one character from each required type
52+
required_chars.append(secrets.choice(chars))
53+
54+
if not character_pool:
55+
raise ValueError("At least one character type must be selected")
56+
57+
# Calculate remaining characters needed
58+
remaining_length = length - len(required_chars)
59+
if remaining_length < 0:
60+
raise ValueError(f"Password length too short for required character types. Minimum: {len(required_chars)}")
61+
62+
# Generate remaining characters
63+
additional_chars = [secrets.choice(character_pool) for _ in range(remaining_length)]
64+
65+
# Combine and shuffle
66+
all_chars = required_chars + additional_chars
67+
secrets.SystemRandom().shuffle(all_chars)
68+
69+
return ''.join(all_chars)
70+
71+
def generate_multiple_passwords(self, count: int = 5, **kwargs) -> List[str]:
72+
"""Generate multiple passwords with the same settings"""
73+
return [self.generate_password(**kwargs) for _ in range(count)]
74+
75+
def check_password_strength(self, password: str) -> Dict[str, bool]:
76+
"""Check the strength of a password"""
77+
return {
78+
'has_lowercase': any(c.islower() for c in password),
79+
'has_uppercase': any(c.isupper() for c in password),
80+
'has_digit': any(c.isdigit() for c in password),
81+
'has_symbol': any(c in string.punctuation for c in password),
82+
'min_length': len(password) >= 8,
83+
'good_length': len(password) >= 12
84+
}
85+
86+
87+
def get_user_preferences():
88+
"""Get password generation preferences from user input"""
89+
print("=== Password Generator ===")
90+
91+
# Get password length
92+
while True:
93+
try:
94+
length = int(input("Enter password length (default 12): ") or "12")
95+
if length < 4:
96+
print("Password length must be at least 4 characters.")
97+
continue
98+
break
99+
except ValueError:
100+
print("Please enter a valid number.")
101+
102+
# Get character type preferences
103+
print("\nSelect character types to include:")
104+
requirements = {
105+
'lowercase': input("Include lowercase letters? (y/n, default y): ").lower() != 'n',
106+
'uppercase': input("Include uppercase letters? (y/n, default y): ").lower() != 'n',
107+
'digits': input("Include digits? (y/n, default y): ").lower() != 'n',
108+
'symbols': input("Include symbols? (y/n, default y): ").lower() != 'n'
109+
}
110+
111+
# Get number of passwords to generate
112+
while True:
113+
try:
114+
count = int(input("\nHow many passwords to generate? (default 1): ") or "1")
115+
if count < 1:
116+
print("Please enter at least 1.")
117+
continue
118+
break
119+
except ValueError:
120+
print("Please enter a valid number.")
121+
122+
return length, requirements, count
123+
124+
125+
def display_password_strength(password: str, generator: PasswordGenerator):
126+
"""Display strength analysis for a password"""
127+
strength = generator.check_password_strength(password)
128+
129+
print(f"\nPassword: {password}")
130+
print("Strength Analysis:")
131+
print(f"Length: {len(password)} characters")
132+
print(f"Lowercase letters: {'Yes' if strength['has_lowercase'] else 'No'}")
133+
print(f"Uppercase letters: {'Yes' if strength['has_uppercase'] else 'No'}")
134+
print(f"Digits: {'Yes' if strength['has_digit'] else 'No'}")
135+
print(f"Symbols: {'Yes' if strength['has_symbol'] else 'No'}")
136+
137+
# Overall strength rating
138+
criteria_met = sum(strength.values())
139+
if criteria_met >= 6:
140+
rating = "Strong"
141+
elif criteria_met >= 4:
142+
rating = "Good"
143+
else:
144+
rating = "Weak"
145+
146+
print(f"Overall Rating: {rating}")
147+
148+
149+
def main():
150+
"""Main function with command line interface"""
151+
parser = argparse.ArgumentParser(description='Generate secure passwords')
152+
parser.add_argument('-l', '--length', type=int, default=12, help='Password length')
153+
parser.add_argument('-n', '--number', type=int, default=1, help='Number of passwords')
154+
parser.add_argument('--no-lower', action='store_true', help='Exclude lowercase letters')
155+
parser.add_argument('--no-upper', action='store_true', help='Exclude uppercase letters')
156+
parser.add_argument('--no-digits', action='store_true', help='Exclude digits')
157+
parser.add_argument('--no-symbols', action='store_true', help='Exclude symbols')
158+
parser.add_argument('--interactive', action='store_true', help='Use interactive mode')
159+
160+
args = parser.parse_args()
161+
162+
generator = PasswordGenerator()
163+
164+
if args.interactive or not any(vars(args).values()):
165+
# Interactive mode
166+
length, requirements, count = get_user_preferences()
167+
else:
168+
# Command line mode
169+
length = args.length
170+
count = args.number
171+
requirements = {
172+
'lowercase': not args.no_lower,
173+
'uppercase': not args.no_upper,
174+
'digits': not args.no_digits,
175+
'symbols': not args.no_symbols
176+
}
177+
178+
try:
179+
# Generate passwords
180+
if count == 1:
181+
password = generator.generate_password(length=length, **requirements)
182+
display_password_strength(password, generator)
183+
else:
184+
passwords = generator.generate_multiple_passwords(count=count, length=length, **requirements)
185+
print(f"\nGenerated {count} passwords:")
186+
for i, password in enumerate(passwords, 1):
187+
print(f"{i:2d}. {password}")
188+
189+
# Show strength for first password as example
190+
if passwords:
191+
display_password_strength(passwords[0], generator)
192+
193+
except ValueError as e:
194+
print(f"Error: {e}")
195+
except Exception as e:
196+
print(f"Unexpected error: {e}")
197+
198+
199+
if __name__ == "__main__":
200+
main()

0 commit comments

Comments
 (0)