|
| 1 | +import string |
| 2 | +import secrets |
| 3 | +from cryptography.fernet import Fernet |
| 4 | +import os |
| 5 | + |
| 6 | +# Step 1: Generate or retrieve a secure encryption key |
| 7 | +key = os.environ.get('FERNET_KEY') |
| 8 | +if not key: |
| 9 | + print("Encryption key is missing. Please set the 'FERNET_KEY' environment variable.") |
| 10 | + exit(1) |
| 11 | +cipher_suite = Fernet(key) |
| 12 | + |
| 13 | +# Step 2: Define all character sets for password generation |
| 14 | +s1 = list(string.ascii_lowercase) # Lowercase letters |
| 15 | +s2 = list(string.ascii_uppercase) # Uppercase letters |
| 16 | +s3 = list(string.digits) # Digits |
| 17 | +s4 = list(string.punctuation) # Special characters |
| 18 | + |
| 19 | +# Step 3: Ask user for password length |
| 20 | +while True: |
| 21 | + try: |
| 22 | + characters_number = int(input("How many characters do you want in your password? ")) |
| 23 | + if 8 <= characters_number <= 128: |
| 24 | + break |
| 25 | + print("Please choose a number between 8 and 128.") |
| 26 | + except ValueError: |
| 27 | + print("Invalid input. Please enter a valid number.") |
| 28 | + |
| 29 | +# Step 4: Securely shuffle the character lists using secrets.SystemRandom() |
| 30 | +secure_random = secrets.SystemRandom() |
| 31 | +s1 = secure_random.sample(s1, len(s1)) # Securely shuffle lowercase letters |
| 32 | +s2 = secure_random.sample(s2, len(s2)) # Securely shuffle uppercase letters |
| 33 | +s3 = secure_random.sample(s3, len(s3)) # Securely shuffle digits |
| 34 | +s4 = secure_random.sample(s4, len(s4)) # Securely shuffle punctuation |
| 35 | + |
| 36 | +# Step 5: Create the password |
| 37 | +# Ensure at least one character from each set is included |
| 38 | +result = [ |
| 39 | + secrets.choice(s1), |
| 40 | + secrets.choice(s2), |
| 41 | + secrets.choice(s3), |
| 42 | + secrets.choice(s4) |
| 43 | +] |
| 44 | + |
| 45 | +# Fill the remaining slots randomly |
| 46 | +remaining_characters = characters_number - len(result) |
| 47 | +result.extend(secrets.choice(s1 + s2 + s3 + s4) for _ in range(remaining_characters)) |
| 48 | + |
| 49 | +# Secure final shuffle |
| 50 | +result = secure_random.sample(result, len(result)) |
| 51 | + |
| 52 | +# Step 6: Join and encrypt the password |
| 53 | +password = "".join(result) |
| 54 | +encrypted_password = cipher_suite.encrypt(password.encode()) |
| 55 | + |
| 56 | +# Step 7: Store the encrypted password securely |
| 57 | +try: |
| 58 | + with open("password_storage.txt", "wb") as file: |
| 59 | + file.write(encrypted_password) |
| 60 | + print("Your password has been securely generated and encrypted.") |
| 61 | + print("The encrypted password has been saved in 'password_storage.txt'.") |
| 62 | + print("Ensure your encryption key is securely stored to decrypt the password.") |
| 63 | +except IOError as e: |
| 64 | + print(f"File operation failed: {e}") |
| 65 | +except Exception as e: |
| 66 | + print(f"An unexpected error occurred: {e}") |
0 commit comments