Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes
Sponsored Reserved space — layout preview until AdSense is connected

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.

Medium Python 3.9+ Jun 28, 2026 Files & data 2 views 0 copies

Requires third-party packages — install first
pip install cryptography

Python code

55 lines
Python 3.9+
import 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

stdout
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

  1. Use a master password derived via PBKDF2 instead of a file-based key
  2. 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

Sponsored Reserved space — layout preview until AdSense is connected

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Files & data

Related tutorials and quizzes for this topic.