Skip to content

Commit 4c36f3f

Browse files
authored
PR #66: Password Generator
Add comprehensive README for the password generator Merge pull request #66 from Bestbrainof24/feature/readme
2 parents 61ea33d + ae38733 commit 4c36f3f

File tree

2 files changed

+234
-55
lines changed

2 files changed

+234
-55
lines changed

Password-Generator/README.md

Lines changed: 162 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,162 @@
1+
# Secure Password Generator
2+
3+
A secure and customizable password generator built with Python that creates cryptographically strong passwords using the `secrets` module.
4+
5+
## Features
6+
7+
- Generates cryptographically secure passwords
8+
- Customizable password length (6-128 characters)
9+
- Option to include/exclude digits and symbols
10+
- Generates multiple passwords at once
11+
- Save passwords to a text file
12+
- Input validation and error handling
13+
14+
## Installation
15+
16+
### Prerequisites
17+
- Python 3.6 or higher
18+
19+
### Setup
20+
1. Clone or download the `password.py` file to your local machine
21+
2. No additional dependencies required - uses only Python's standard library
22+
23+
### In Terminal
24+
```bash
25+
git clone https://github.com/Grow-with-Open-Source/Python-Projects.git
26+
cd Python-Projects
27+
cd Password-Generator
28+
python password.py
29+
```
30+
31+
## Usage
32+
33+
Run the script from your terminal or command prompt:
34+
35+
```bash
36+
python password.py
37+
```
38+
39+
### In your own script
40+
```python
41+
from password import generate_password
42+
43+
# Generate a single password
44+
password = generate_password(length=12, digits=True, symbols=True)
45+
print(password)
46+
47+
# Generate without symbols
48+
simple_password = generate_password(length=10, digits=True, symbols=False)
49+
print(simple_password)
50+
```
51+
52+
## Running Examples
53+
### Example 1: Basic Password Generation
54+
55+
```python
56+
> python password.py
57+
Enter the length of the password: 12
58+
Enter the number of passwords to generate: 3
59+
Include digits? (y/n): y
60+
Include symbols? (y/n): y
61+
62+
Generating Secure Passwords...
63+
64+
Password #1: aB3@kL9#mN2!
65+
Password #2: pQ8$rS1^tU4*
66+
Password #3: xY7&zW5!vZ9@
67+
68+
Do you want to save the passwords to a file? (y/n): y
69+
Enter the name of the file (without .txt): my_passwords
70+
71+
Saving passwords to file...
72+
Passwords saved successfully!
73+
```
74+
75+
### Example 2: Simple Alphanumeric Passwords
76+
```python
77+
> python password.py
78+
Enter the length of the password: 8
79+
Enter the number of passwords to generate: 2
80+
Include digits? (y/n): y
81+
Include symbols? (y/n): n
82+
83+
Generating Secure Passwords...
84+
85+
Password #1: aB3cD9eF
86+
Password #2: gH4iJ7kL
87+
```
88+
89+
### Example 3: Short Password (Auto-corrected)
90+
```python
91+
> python password.py
92+
Enter the length of the password: 4
93+
Enter the number of passwords to generate: 1
94+
Include digits? (y/n): y
95+
Include symbols? (y/n): y
96+
97+
Password is too short - Generating Passwords of length 6
98+
99+
Generating Secure Passwords...
100+
101+
Password #1: a@3b#9
102+
```
103+
104+
## Interactive Options
105+
When you run the script, you'll be prompted for the following:
106+
107+
1. Password Length: Enter an integer between 6 and 128
108+
- If you enter less than 6, it will automatically set to 6
109+
- Maximum length is 128 characters
110+
111+
2. Number of Passwords: How many passwords to generate (positive integer)
112+
113+
3. Include Digits?: (y/n) - Whether to include numbers (0-9)
114+
115+
4. Include Symbols?: (y/n) - Whether to include special characters (!@#$%^&*(), etc.)
116+
117+
5. Save to File?: (y/n) - Option to save generated passwords to a text file
118+
- If yes, you can specify a filename (default: "passwords.txt")
119+
120+
## Password Security Features
121+
1. **Cryptographically Secure**: Uses ``secrets`` module (not ``random``) for true randomness
122+
123+
2. **Character Variety**: Ensures at least one character from each selected character set
124+
125+
3. **Shuffling**: Passwords are shuffled after generation to avoid predictable patterns
126+
127+
4. **Length Enforcement**: Minimum 6 characters for basic security
128+
129+
5. **Input Validation**: Validates all user inputs to prevent errors
130+
131+
## File Structure
132+
```text
133+
password.py
134+
├── generate_password(length, digits, symbols) # Core generator function
135+
├── save(passwords) # File saving function
136+
└── main() # Interactive CLI interface
137+
```
138+
139+
## Error Handling
140+
The script includes comprehensive error handling for:
141+
142+
- Invalid integer inputs
143+
- File system errors when saving
144+
- Unexpected exceptions
145+
- Length constraints and requirements
146+
147+
## Limitations
148+
- Maximum password length is 128 characters
149+
- Minimum password length is 6 characters (enforced)
150+
- Uses standard Python string punctuation for symbols
151+
- Text file saving is optional and basic
152+
153+
## Security Notes
154+
- ✅ Uses secrets module for cryptographically secure random generation
155+
- ✅ No external dependencies or network calls
156+
- ✅ Passwords are generated locally on your machine
157+
- ❗ Saved passwords are stored in plain text - handle with care!
158+
- ❗ Always use strong, unique passwords for different services
159+
160+
## License
161+
This project is open-source and intended for educational and practical use.
162+
Refer to the repository license for usage terms.

Password-Generator/password.py

Lines changed: 72 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -1,63 +1,80 @@
1-
import random
1+
import secrets
2+
import string
23

3-
def generatePassword(pwlength):
4-
5-
alphabet = "abcdefghijklmnopqrstuvwxyz"
6-
7-
passwords = []
8-
9-
for i in pwlength:
10-
11-
password = ""
12-
for j in range(i):
13-
next_letter_index = random.randrange(len(alphabet))
14-
password = password + alphabet[next_letter_index]
15-
16-
password = replaceWithNumber(password)
17-
password = replaceWithUppercaseLetter(password)
18-
19-
passwords.append(password)
20-
21-
return passwords
22-
23-
24-
def replaceWithNumber(pword):
25-
for i in range(random.randrange(1,3)):
26-
replace_index = random.randrange(len(pword)//2)
27-
pword = pword[0:replace_index] + str(random.randrange(10)) + pword[replace_index+1:]
28-
return pword
29-
30-
31-
def replaceWithUppercaseLetter(pword):
32-
for i in range(random.randrange(1,3)):
33-
replace_index = random.randrange(len(pword)//2,len(pword))
34-
pword = pword[0:replace_index] + pword[replace_index].upper() + pword[replace_index+1:]
35-
return pword
36-
37-
38-
39-
def main():
4+
def generate_password(length: int = 12, digits: bool = True, symbols: bool = True) -> str:
405

41-
numPasswords = int(input("How many passwords do you want to generate? "))
6+
min_required = int(digits) + int(symbols)
7+
if length < min_required:
8+
raise ValueError("Password length too small for selected options")
429

43-
print("Generating " +str(numPasswords)+" passwords")
10+
pool = string.ascii_letters
11+
required_chars = []
4412

45-
passwordLengths = []
46-
47-
print("Minimum length of password should be 3")
13+
if digits:
14+
pool += string.digits
15+
required_chars.append(secrets.choice(string.digits))
4816

49-
for i in range(numPasswords):
50-
length = int(input("Enter the length of Password #" + str(i+1) + " "))
51-
if length<3:
52-
length = 3
53-
passwordLengths.append(length)
17+
if symbols:
18+
pool += string.punctuation
19+
required_chars.append(secrets.choice(string.punctuation))
5420

21+
remaining_length = length - len(required_chars)
5522

56-
Password = generatePassword(passwordLengths)
57-
58-
for i in range(numPasswords):
59-
print ("Password #"+str(i+1)+" = " + Password[i])
60-
61-
23+
password = required_chars + [secrets.choice(pool) for _ in range(remaining_length)]
24+
secrets.SystemRandom().shuffle(password)
25+
26+
return ''.join(password)
27+
28+
def save(passwords: list) -> None:
29+
try:
30+
agree: str = input("Do you want to save the passwords to a file? (y/n): ").lower().strip()
31+
if agree not in ["y", "yes"]:
32+
return
33+
else:
34+
fileName: str = input("Enter the name of the file (without .txt): ").strip()
35+
if not fileName:
36+
fileName: str = "passwords"
37+
print("\nSaving passwords to file...")
38+
with open(fileName + ".txt", "w") as f:
39+
for password in passwords:
40+
f.write(password + "\n")
41+
print("Passwords saved successfully!")
42+
except OSError as e:
43+
print(f"Error saving passwords: {e}")
44+
45+
def main() -> None:
46+
try:
47+
length: int = int(input("Enter the length of the password: "))
48+
count: int = int(input("Enter the number of passwords to generate: "))
49+
50+
if length < 1 or count < 1:
51+
print("Please enter positive integers only.")
52+
return
53+
54+
if length > 128:
55+
print("Password length cannot be greater than 128 characters.")
56+
return
57+
58+
if length < 6:
59+
print("Password is too short - Generating Passwords of length 6")
60+
length = 6
61+
62+
digits: bool = input("Include digits? (y/n): ").lower().strip() in ["y", "yes"]
63+
symbols: bool = input("Include symbols? (y/n): ").lower().strip() in ["y", "yes"]
64+
65+
print("\nGenerating Secure Passwords...\n")
66+
passwords = []
67+
for i in range(count):
68+
password = generate_password(length, digits=digits, symbols=symbols)
69+
passwords.append(password)
70+
print(f"Password #{i + 1}: {password}")
71+
72+
save(passwords)
73+
74+
except ValueError:
75+
print("Please Enter Valid Integers Only")
76+
except Exception as e:
77+
print(f"An unexpected error occurred: {e}")
6278

63-
main()
79+
if __name__ == "__main__":
80+
main()

0 commit comments

Comments
 (0)