How to Build a Password Manager in Python



This password manager application will enable the storage and protection of passwords by encrypting them in an organized manner.

This password manager is created using Python and the user interface has been created using Tkinter while ensuring password security using the cryptography library. One of the features of the application is to save and show passwords safely and securely with the help of the strong encryptions.

Installations

First follow these installation steps −

1. Install Python

Ensure you have Python 3.11 or later installed. Download and install it. Read more − Python Environment Setup.

2. Install Required Libraries

Open a terminal or command prompt and install the libraries using pip −

pip install cryptography

Explanation of Password Manager Components

The password manager application consists of several key components: The password manager application consists of several key components −

1. Key Generation and Management

The last is generate_key() function that causes generation of a new encryption key.

This function load_key()as a default function to load an existing key from file if it is available otherwise it creates a new one.

2. Encryption and Decryption

Passwords are encrypted using the Fernet encryption algorithm which is done by the encrypt_message() function while decryption is done using the decrypt_message() function before presentation.

3. Save Password

The save_password() function takes string input from the user for service, username and the password, and then encrypts it before putting it into the JSON file. It deals with file operation and modified the data which is already exist.

4. View Passwords

The view_passwords() function reads encrypted passwords from the JSON file then decrypts them and displays them for the user's convenience.

5. Graphical User Interface (GUI)

Tkinter library is used to implement a basic User interface that consists of entry widgets for Service, Username, and Password and buttons for save and show password.

Read More: Python GUI Programming

Python Code to Build a Password Manager

import tkinter as tk
from tkinter import messagebox
from cryptography.fernet import Fernet
import os
import json

# Key generation and encryption setup
def generate_key():
   return Fernet.generate_key()

def load_key():
   if os.path.exists("secret.key"):
      with open("secret.key", "rb") as key_file:
         return key_file.read()
   else:
      key = generate_key()
      with open("secret.key", "wb") as key_file:
         key_file.write(key)
      return key

def encrypt_message(message, key):
   f = Fernet(key)
   encrypted_message = f.encrypt(message.encode())
   return encrypted_message

def decrypt_message(encrypted_message, key):
   f = Fernet(key)
   decrypted_message = f.decrypt(encrypted_message).decode()
   return decrypted_message

# Initialize the key
key = load_key()

# Application functions
def save_password():
   service = service_entry.get()
   username = username_entry.get()
   password = password_entry.get()

   if not service or not username or not password:
      messagebox.showwarning("Input Error", "Please fill all fields.")
      return

   encrypted_password = encrypt_message(password, key)
   new_data = {service: {"username": username, "password": encrypted_password}}

   if os.path.exists("passwords.json"):
      with open("passwords.json", "r") as file:
         try:
            existing_data = json.load(file)
         except (json.JSONDecodeError, TypeError):
            existing_data = {}
      existing_data.update(new_data)
   else:
      existing_data = new_data

   # Ensure all values in existing_data are serializable
   for service, info in existing_data.items():
      if isinstance(info.get("password"), bytes):
         info["password"] = info["password"].decode()  # Convert bytes to string for serialization

   with open("passwords.json", "w") as file:
      try:
         json.dump(existing_data, file, indent=4)
      except TypeError as e:
         messagebox.showerror("Serialization Error", f"Error serializing data: {e}")

   service_entry.delete(0, tk.END)
   username_entry.delete(0, tk.END)
   password_entry.delete(0, tk.END)
   messagebox.showinfo("Success", "Password saved successfully!")

def view_passwords():
   if os.path.exists("passwords.json"):
      with open("passwords.json", "r") as file:
         try:
            data = json.load(file)
         except json.JSONDecodeError:
            data = {}

   result = ""
   if data:
      for service, info in data.items():
         username = info.get("username", "N/A")
         password = info.get("password", b"")
         decrypted_password = decrypt_message(password.encode(), key)
            result += f"Service: {service}\nUsername: {username}\nPassword: {decrypted_password}\n\n"
   else:
      result = "No passwords stored yet."

      messagebox.showinfo("Stored Passwords", result)
   else:
      messagebox.showinfo("No Data", "No passwords stored yet.")

# GUI setup
root = tk.Tk()
root.title("Password Manager")

tk.Label(root, text="Service").grid(row=0, column=0, padx=10, pady=10)
tk.Label(root, text="Username").grid(row=1, column=0, padx=10, pady=10)
tk.Label(root, text="Password").grid(row=2, column=0, padx=10, pady=10)

service_entry = tk.Entry(root, width=50)
service_entry.grid(row=0, column=1, padx=10, pady=10)

username_entry = tk.Entry(root, width=50)
username_entry.grid(row=1, column=1, padx=10, pady=10)

password_entry = tk.Entry(root, width=50, show="*")
password_entry.grid(row=2, column=1, padx=10, pady=10)

tk.Button(root, text="Save Password", command=save_password).grid(row=3, column=0, columnspan=2, pady=10)
tk.Button(root, text="View Passwords", command=view_passwords).grid(row=4, column=0, columnspan=2, pady=10)

root.mainloop()

Output

First you have to write your Service, username, password.

Password Manager

Then you have to click save button for save this −

Password Manager

After that you can view the password that you saved −

Password Manager

Again you can create password, username and service −

Password Manager

After saving the password, click View Password, and you will see both usernames that you created previously −

Password Manager

That all passwords will be saved in a JSON file −

Password Manager

Conclusion

This password manager created with the help of Python can be the useful tool to handle passwords with security issues. Using simple encryption, and a friendly graphical user interface it only allows access to authorized users while data security is maintained. As it seen from the installation instructions and source code, users can run their own password manager and improve their online safety.

python_projects_from_basic_to_advanced.htm
Advertisements