w3resource

Create a Secure Password Manager Project in Python: Two Approaches

Password Manager:

Develop a password manager that stores and retrieves passwords securely.

Input values:
Add, edit, delete, or retrieve passwords stored in the password manager.

Output value:
Feedback based on user actions, such as success messages or retrieving passwords.

Example:

Input values:
1. Add Password
2. Retrieve Password
3. Edit Password
4. Delete Password
5. Exit
Select an option: 1
Input website/app name: example.com
Input user ID: user_111
Input password: Oui*%#$ki
Output value:
Password added successfully.
Input values:
1. Add Password
2. Retrieve Password
3. Edit Password
4. Delete Password
5. Exit
Select an option: 2
Input website/app name: example.com
Input user ID: user_111
Output value:
Retrieved Password: Oui*%#$ki

Here are two different solutions for a password manager in Python. This program will allow users to add, edit, delete, and retrieve passwords securely.

Solution 1: Basic Approach using a Dictionary and 'getpass' for Secure Input

Code:

# Solution 1: Basic Approach Using a Dictionary and `getpass` for Secure Input

import getpass  # Import getpass to securely handle password input

# Dictionary to store passwords in the format: {(website, user_id): password}
password_storage = {}

def add_password(website, user_id, password):
    """Add a password to the storage."""
    key = (website, user_id)
    password_storage[key] = password
    print("Password added successfully.")

def retrieve_password(website, user_id):
    """Retrieve a password from the storage."""
    key = (website, user_id)
    if key in password_storage:
        print(f"Retrieved Password: {password_storage[key]}")
    else:
        print("No password found for the given website and user ID.")

def edit_password(website, user_id, new_password):
    """Edit an existing password in the storage."""
    key = (website, user_id)
    if key in password_storage:
        password_storage[key] = new_password
        print("Password updated successfully.")
    else:
        print("No password found to update.")

def delete_password(website, user_id):
    """Delete a password from the storage."""
    key = (website, user_id)
    if key in password_storage:
        del password_storage[key]
        print("Password deleted successfully.")
    else:
        print("No password found to delete.")

def main():
    """Main function to interact with the user."""
    print("Welcome to the Password Manager!")

    while True:
        # Display the menu
        print("\n1. Add Password")
        print("2. Retrieve Password")
        print("3. Edit Password")
        print("4. Delete Password")
        print("5. Exit")

        # Get user choice
        choice = input("Select an option: ")

        if choice == '1':
            # Add Password
            website = input("Input website/app name: ")
            user_id = input("Input user ID: ")
            password = getpass.getpass("Input password: ")  # Securely input password
            add_password(website, user_id, password)

        elif choice == '2':
            # Retrieve Password
            website = input("Input website/app name: ")
            user_id = input("Input user ID: ")
            retrieve_password(website, user_id)

        elif choice == '3':
            # Edit Password
            website = input("Input website/app name: ")
            user_id = input("Input user ID: ")
            new_password = getpass.getpass("Input new password: ")  # Securely input new password
            edit_password(website, user_id, new_password)

        elif choice == '4':
            # Delete Password
            website = input("Input website/app name: ")
            user_id = input("Input user ID: ")
            delete_password(website, user_id)

        elif choice == '5':
            # Exit
            print("Exiting Password Manager. Goodbye!")
            break

        else:
            print("Invalid option. Please choose a valid number.")

# Run the Password Manager
main()

Output:

Welcome to the Password Manager!

1. Add Password
2. Retrieve Password
3. Edit Password
4. Delete Password
5. Exit
Select an option: 1
Input website/app name: example.com
Input user ID: user1
 Input password:  
Password added successfully.

1. Add Password
2. Retrieve Password
3. Edit Password
4. Delete Password
5. Exit
Select an option: 3
Input website/app name: example.com
Input user ID: user1

Input new password:  
Password updated successfully.

1. Add Password
2. Retrieve Password
3. Edit Password
4. Delete Password
5. Exit
Select an option: 4
Input website/app name: example.com
Input user ID: user1
Password deleted successfully.

1. Add Password
2. Retrieve Password
3. Edit Password
4. Delete Password
5. Exit
Select an option: 5
Exiting Password Manager. Goodbye!

Explanation:

  • Uses a simple dictionary ('password_storage') to store passwords in memory.
  • Functions 'add_password', 'retrieve_password', 'edit_password', and 'delete_password' handle adding, retrieving, editing, and deleting passwords, respectively.
  • Uses 'getpass.getpass()' to securely handle password input without displaying it on the screen.
  • This solution is straightforward but stores passwords in memory, making it less secure if the program is terminated.

Solution 2: Using a Class-Based Approach and cryptography for Secure Storage

First, install the cryptography library:

pip install cryptography

Code:

# Solution 2: Using a Class-Based Approach and `cryptography` for Secure Storage

from cryptography.fernet import Fernet  # Import Fernet for encryption and decryption
import getpass  # Import getpass to securely handle password input
import os  # Import os to interact with the operating system

class PasswordManager:
    """Class to handle password management with encryption."""

    def __init__(self, key_file='key.key', storage_file='passwords.txt'):
        """Initialize the manager with a key and storage file."""
        self.key_file = key_file
        self.storage_file = storage_file
        self.key = self.load_key()
        self.cipher = Fernet(self.key)

    def load_key(self):
        """Load or generate an encryption key."""
        if os.path.exists(self.key_file):
            with open(self.key_file, 'rb') as keyfile:
                return keyfile.read()
        else:
            key = Fernet.generate_key()
            with open(self.key_file, 'wb') as keyfile:
                keyfile.write(key)
            return key

    def encrypt(self, text):
        """Encrypt text using the Fernet cipher."""
        return self.cipher.encrypt(text.encode()).decode()

    def decrypt(self, text):
        """Decrypt text using the Fernet cipher."""
        return self.cipher.decrypt(text.encode()).decode()

    def save_password(self, website, user_id, password):
        """Save an encrypted password to the storage file."""
        encrypted_password = self.encrypt(password)
        with open(self.storage_file, 'a') as file:
            file.write(f"{website},{user_id},{encrypted_password}\n")
        print("Password added successfully.")

    def find_password(self, website, user_id):
        """Find and decrypt a password from the storage file."""
        if os.path.exists(self.storage_file):
            with open(self.storage_file, 'r') as file:
                for line in file:
                    stored_website, stored_user_id, encrypted_password = line.strip().split(',')
                    if stored_website == website and stored_user_id == user_id:
                        decrypted_password = self.decrypt(encrypted_password)
                        print(f"Retrieved Password: {decrypted_password}")
                        return
        print("No password found for the given website and user ID.")

    def run(self):
        """Main function to interact with the user."""
        print("Welcome to the Password Manager!")

        while True:
            # Display the menu
            print("\n1. Add Password")
            print("2. Retrieve Password")
            print("3. Exit")

            # Get user choice
            choice = input("Select an option: ")

            if choice == '1':
                # Add Password
                website = input("Input website/app name: ")
                user_id = input("Input user ID: ")
                password = getpass.getpass("Input password: ")  # Securely input password
                self.save_password(website, user_id, password)

            elif choice == '2':
                # Retrieve Password
                website = input("Input website/app name: ")
                user_id = input("Input user ID: ")
                self.find_password(website, user_id)

            elif choice == '3':
                # Exit
                print("Exiting Password Manager. Goodbye!")
                break

            else:
                print("Invalid option. Please choose a valid number.")

# Create an instance of PasswordManager and start it
password_manager = PasswordManager()
password_manager.run()
Welcome to the Password Manager!

1. Add Password
2. Retrieve Password
3. Exit
Select an option: 1
Input website/app name: example.com
Input user ID: user1
Input password:
Password added successfully.

1. Add Password
2. Retrieve Password
3. Exit
Select an option: 2
Input website/app name: example.com
Input user ID: user1
Retrieved Password: Ajuie#2

1. Add Password
2. Retrieve Password
3. Exit
Select an option: 3
Exiting Password Manager. Goodbye!

Explanation:

  • Uses the cryptography library's 'Fernet' class to securely encrypt and decrypt passwords.
  • The 'PasswordManager' class encapsulates all functionality, such as encryption, decryption, saving, and retrieving passwords.
  • The encryption key is stored in a file ('key.key'), and passwords are stored in an encrypted format in a file ('passwords.txt').
  • Uses methods like 'save_password()' and 'find_password()' to handle password management securely.
  • This approach provides stronger security by encrypting passwords, making it suitable for more secure storage solutions.

Note:
Both solutions provide a password manager that allows adding, editing, deleting, and retrieving passwords. Solution 1 uses a simple dictionary, while Solution 2 uses a class-based approach with encryption for secure storage.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/projects/python/python-password-manager-project.php