Build a Secure Local Password Vault with Encrypted Storage in Python
A Python class that stores and retrieves passwords in an encrypted JSON file using Fernet symmetric encryption from the cryptography library.
pip install cryptography
Python code
55 linesimport json
import os
import base64
import hashlib
from cryptography.fernet import Fernet
from getpass import getpass
class PasswordVault:
def __init__(self, vault_file="vault.json", key_file="vault.key"):
self.vault_file = vault_file
self.key_file = key_file
self.key = self._load_or_create_key()
self.cipher = Fernet(self.key)
def _load_or_create_key(self):
if os.path.exists(self.key_file):
with open(self.key_file, "rb") as f:
return f.read()
key = Fernet.generate_key()
with open(self.key_file, "wb") as f:
f.write(key)
return key
def _load_vault(self):
if os.path.exists(self.vault_file):
with open(self.vault_file, "rb") as f:
encrypted_data = f.read()
try:
decrypted_data = self.cipher.decrypt(encrypted_data)
return json.loads(decrypted_data)
except:
return {}
return {}
def _save_vault(self, vault):
json_data = json.dumps(vault).encode()
encrypted_data = self.cipher.encrypt(json_data)
with open(self.vault_file, "wb") as f:
f.write(encrypted_data)
def add_password(self, service, username, password):
vault = self._load_vault()
vault[service] = {"username": username, "password": password}
self._save_vault(vault)
def get_password(self, service):
vault = self._load_vault()
return vault.get(service, None)
if __name__ == "__main__":
vault = PasswordVault()
vault.add_password("example.com", "user123", "SecurePass1!")
entry = vault.get_password("example.com")
if entry:
print(f"Service: example.com\nUsername: {entry['username']}\nPassword: {entry['password']}")
Output
Service: example.com
Username: user123
Password: SecurePass1!
How it works
The vault uses Fernet symmetric encryption to encrypt the entire JSON data before writing to disk. A key is generated and stored in a separate file on first run, then reused. The PasswordVault class handles loading and saving with transparent encryption/decryption. This approach ensures passwords are never stored in plaintext locally.
Common mistakes
- Forgetting to install cryptography with pip install cryptography
- Losing or deleting vault.key which makes decryption impossible
- Not handling exceptions when vault file is corrupted or tampered
- Storing the key in the same git repository or sharing it accidentally
Variations
- Use a master password derived via PBKDF2 instead of a file-based key
- Store vault data in a SQLite database with encrypted columns instead of JSON
Real-world use cases
- Saving API credentials locally for automated scripts without hardcoding secrets.
- Storing personal login details in a CLI tool that syncs via a cloud drive.
- Securing database connection strings in development environments.
Sponsored
More from Files & data
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a Personal Work Hours Tracker in Python medium
- Build a Python Script That Detects and Deletes Empty Files Across Folders easy
Keep learning
Related tutorials and quizzes for this topic.