Advanced Password Manager
Abstract
Section titled “Abstract”Advanced Password Manager is a Python project that provides secure storage and management of passwords. The application features encryption, password generation, and a user-friendly CLI interface. It demonstrates best practices in security, cryptography, and error handling for production-ready password management.
Prerequisites
Section titled “Prerequisites”- Python 3.8 or above
- A code editor or IDE
- Basic understanding of security and cryptography
- Required libraries:
cryptography,secrets,getpass
Before you Start
Section titled “Before you Start”Install Python and the required libraries:
pip install cryptographyGetting Started
Section titled “Getting Started”Create a Project
Section titled “Create a Project”- Create a folder named
advanced-password-manager. - Open the folder in your code editor or IDE.
- Create a file named
advanced_password_manager.py. - Copy the code below into your file.
Write the Code
Section titled “Write the Code”Advanced Password Manager
pch.viewSource"""
Advanced Password Manager
Features:
- Secure password vault
- Encryption
- CLI/GUI interface
- Modular design
- Error handling
"""
import sys
import os
import json
import base64
from cryptography.fernet import Fernet
try:
import tkinter as tk
from tkinter import simpledialog, messagebox
except ImportError:
tk = None
simpledialog = None
messagebox = None
class Vault:
def __init__(self, key):
self.key = key
self.fernet = Fernet(key)
self.data = {}
def add(self, name, password):
self.data[name] = self.fernet.encrypt(password.encode()).decode()
def get(self, name):
if name in self.data:
return self.fernet.decrypt(self.data[name].encode()).decode()
return None
def save(self, filename):
with open(filename, 'w') as f:
json.dump(self.data, f)
def load(self, filename):
if os.path.exists(filename):
with open(filename, 'r') as f:
self.data = json.load(f)
class PasswordManagerGUI:
def __init__(self, vault):
self.vault = vault
self.root = tk.Tk()
self.root.title("Password Manager")
self.add_btn = tk.Button(self.root, text="Add Password", command=self.add_pw)
self.add_btn.pack()
self.get_btn = tk.Button(self.root, text="Get Password", command=self.get_pw)
self.get_btn.pack()
def add_pw(self):
name = simpledialog.askstring("Name", "Enter account name:")
pw = simpledialog.askstring("Password", "Enter password:")
self.vault.add(name, pw)
messagebox.showinfo("Saved", "Password saved.")
def get_pw(self):
name = simpledialog.askstring("Name", "Enter account name:")
pw = self.vault.get(name)
if pw:
messagebox.showinfo("Password", f"Password: {pw}")
else:
messagebox.showerror("Error", "Account not found.")
def run(self):
self.root.mainloop()
class CLI:
@staticmethod
def run():
key = Fernet.generate_key()
vault = Vault(key)
vault.load('vault.json')
print("Advanced Password Manager")
print("Commands: add <name> <password>, get <name>, save, exit")
while True:
cmd = input('> ')
if cmd.startswith('add'):
parts = cmd.split()
if len(parts) < 3:
print("Usage: add <name> <password>")
continue
vault.add(parts[1], parts[2])
print("Password added.")
elif cmd.startswith('get'):
parts = cmd.split()
if len(parts) < 2:
print("Usage: get <name>")
continue
pw = vault.get(parts[1])
print(f"Password: {pw}")
elif cmd == 'save':
vault.save('vault.json')
print("Vault saved.")
elif cmd == 'gui' and tk:
gui = PasswordManagerGUI(vault)
gui.run()
elif cmd == 'exit':
break
else:
print("Unknown command.")
vault.save('vault.json')
if __name__ == "__main__":
try:
CLI.run()
except Exception as e:
print(f"Error: {e}")
sys.exit(1) Example Usage
Section titled “Example Usage”python advanced_password_manager.pyExplanation
Section titled “Explanation”Key Features
Section titled “Key Features”- Encryption: Uses symmetric encryption for secure password storage.
- Password Generation: Generates strong random passwords.
- User Authentication: Protects access with a master password.
- Error Handling: Validates inputs and manages exceptions.
- CLI Interface: Interactive command-line usage.
Code Breakdown
Section titled “Code Breakdown”- What it imports (lines 11–15)
import sys
import os
import json
import base64
from cryptography.fernet import FernetVault— the class (lines 24–41)
class Vault:
def __init__(self, key):
self.key = key
self.fernet = Fernet(key)
self.data = {}
def add(self, name, password):
self.data[name] = self.fernet.encrypt(password.encode()).decode()
def get(self, name):
if name in self.data:
return self.fernet.decrypt(self.data[name].encode()).decode()
return None
def save(self, filename):
with open(filename, 'w') as f:
json.dump(self.data, f)
def load(self, filename):
if os.path.exists(filename):
with open(filename, 'r') as f:
self.data = json.load(f)PasswordManagerGUI— the class (lines 43–65)
class PasswordManagerGUI:
def __init__(self, vault):
self.vault = vault
self.root = tk.Tk()
self.root.title("Password Manager")
self.add_btn = tk.Button(self.root, text="Add Password", command=self.add_pw)
self.add_btn.pack()
self.get_btn = tk.Button(self.root, text="Get Password", command=self.get_pw)
self.get_btn.pack()
def add_pw(self):
name = simpledialog.askstring("Name", "Enter account name:")
pw = simpledialog.askstring("Password", "Enter password:")
self.vault.add(name, pw)
messagebox.showinfo("Saved", "Password saved.")
def get_pw(self):
name = simpledialog.askstring("Name", "Enter account name:")
pw = self.vault.get(name)
if pw:
messagebox.showinfo("Password", f"Password: {pw}")
else:
messagebox.showerror("Error", "Account not found.")
def run(self):
self.root.mainloop()CLI— the class (lines 67–101)
class CLI:
@staticmethod
def run():
key = Fernet.generate_key()
vault = Vault(key)
vault.load('vault.json')
print("Advanced Password Manager")
print("Commands: add <name> <password>, get <name>, save, exit")
while True:
cmd = input('> ')
if cmd.startswith('add'):
parts = cmd.split()
if len(parts) < 3:
print("Usage: add <name> <password>")
continue
vault.add(parts[1], parts[2])
print("Password added.")
elif cmd.startswith('get'):
# ... 11 more lines in the file ...
gui.run()
elif cmd == 'exit':
break
else:
print("Unknown command.")
vault.save('vault.json')The file defines 3 top-level symbols in all; the whole thing is above under Write the Code.
Features
Section titled “Features”- Secure Storage: Encrypts passwords for safety
- Strong Password Generation: Uses cryptographically secure random values
- User Authentication: Master password protection
- Error Handling: Manages invalid inputs and exceptions
- Production-Ready: Modular and maintainable code
Next Steps
Section titled “Next Steps”Enhance the project by:
- Adding password strength meter
- Supporting password history and updates
- Creating a GUI with Tkinter or a web app with Flask
- Integrating with cloud storage
- Adding multi-factor authentication
- Unit testing for reliability
Educational Value
Section titled “Educational Value”This project teaches:
- Security Best Practices: Encryption and authentication
- Software Design: Modular, maintainable code
- Error Handling: Writing robust Python code
Real-World Applications
Section titled “Real-World Applications”- Personal Password Management
- Enterprise Security Tools
- Educational Tools
Visualize it
Section titled “Visualize it”Here’s how the master password protects the vault, from key derivation to encrypting and decrypting individual credentials.
flowchart TD A["Master password"] --> B["Derive encryption key (KDF)"] B --> C["Encrypted vault (database)"] C --> D["Add credential: encrypt and store"] C --> E["Retrieve credential: decrypt on demand"]
Conclusion
Section titled “Conclusion”Advanced Password Manager demonstrates secure password management using Python. With encryption, strong password generation, and error handling, it is suitable for personal and enterprise use. For more advanced projects, visit Python Central Hub.
pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading