YouTip LogoYouTip

Python Password Manager

## Building a Password Manager in Python In this tutorial, we will design and implement a simple, object-oriented **Password Manager** class in Python. This class allows users to securely store, retrieve, delete, and list account credentials. To keep the core logic easy to understand, this initial implementation stores passwords in memory using a dictionary. In a production environment, you should always encrypt passwords before storing them and persist them to a secure database or file. --- ## Class Architecture & Design The `PasswordManager` class uses a Python dictionary (`dict`) where the **keys** represent account names (e.g., `"email"`, `"bank"`) and the **values** represent the corresponding passwords. ### Key Methods: 1. `__init__()`: Initializes an empty dictionary to hold credentials. 2. `add_password(account, password)`: Adds or updates a password for a specific account. 3. `get_password(account)`: Retrieves the password for a given account. Returns an error message if the account does not exist. 4. `delete_password(account)`: Removes the account and its password from the manager. 5. `list_accounts()`: Displays all accounts currently stored in the manager. --- ## Code Implementation Below is the complete Python implementation of the `PasswordManager` class: ```python class PasswordManager: def __init__(self): # Initialize an empty dictionary to store account-password pairs self.passwords = {} def add_password(self, account, password): """Adds a new account and password, or updates an existing one.""" self.passwords = password print(f"Password for {account} added successfully.") def get_password(self, account): """Retrieves the password for a given account.""" if account in self.passwords: return self.passwords else: return f"No password found for {account}." def delete_password(self, account): """Deletes an account and its password from the manager.""" if account in self.passwords: del self.passwords print(f"Password for {account} deleted successfully.") else: print(f"No password found for {account}.") def list_accounts(self): """Lists all accounts that currently have stored passwords.""" if self.passwords: print("Accounts with stored passwords:") for account in self.passwords: print(f"- {account}") else: print("No accounts with stored passwords.") ``` --- ## Code Explanation 1. **`__init__` Method**: Initializes the instance variable `self.passwords` as an empty dictionary. This dictionary acts as our in-memory database. 2. **`add_password` Method**: Takes `account` and `password` as arguments and maps them in the `self.passwords` dictionary. If the account already exists, it overwrites the old password. 3. **`get_password` Method**: Checks if the requested `account` key exists in the dictionary. If found, it returns the password; otherwise, it returns a user-friendly error message. 4. **`delete_password` Method**: Uses Python's `del` statement to remove the key-value pair from the dictionary if the account exists. 5. **`list_accounts` Method**: Iterates through the dictionary keys to display all registered accounts. It includes a fallback check in case the dictionary is empty. --- ## Usage Example Here is how you can instantiate and use the `PasswordManager` class in your Python scripts: ```python # Instantiate the password manager pm = PasswordManager() # 1. Add new credentials pm.add_password("email", "myemailpassword") pm.add_password("bank", "mybankpassword") # 2. Retrieve a password print(pm.get_password("email")) # Output: myemailpassword # 3. Delete an account pm.delete_password("bank") # 4. List all remaining accounts pm.list_accounts() # Output: # Accounts with stored passwords: # - email ``` --- ## Production Considerations While this in-memory implementation is excellent for learning object-oriented programming (OOP) basics in Python, it is not secure for real-world use. If you plan to use this in a real application, consider implementing the following enhancements: * **Data Persistence**: Use Python's built-in `sqlite3` module or the `json` module to save credentials to a local file so they are not lost when the program exits. * **Encryption**: Never store passwords in plaintext. Use cryptography libraries like `cryptography` (specifically `Fernet` symmetric encryption) to encrypt passwords before saving them. * **Master Password**: Implement a master password authentication system to restrict access to the `PasswordManager` instance.
← Python Ebook ClassPython Update Person β†’