Digital security has become a priority for anyone who uses the internet. With dozens of accounts and services, memorizing complex combinations for each one is nearly impossible. This is where programming offers a practical, personalized solution. In this guide, you will learn how to build a simple password manager with Python, using fundamental logic and cryptography concepts to centralize your credentials securely and efficiently.
Python is the ideal choice for this kind of project due to its clear syntax and rich library ecosystem. Even if you are just starting to learn Python, you will be able to follow along. The goal is not just to store data, but to understand how to handle sensitive information, write organized files, and ensure only the creator has access to the stored secrets.
Why build your own password manager?
Building your own tool offers unparalleled control and learning. You will come into direct contact with programming logic applied to information security, understand how the computer handles hidden text, and interact with the operating system. This project is a turning point for anyone who wants to go beyond theory: it turns basic functions into a real daily utility.
Project structure and required libraries
We will use the cryptography library, one of the world’s leading Python security references. It follows standards recommended by the NIST (National Institute of Standards and Technology). We will also use the os module to manage files and paths, plus secrets and string for password generation.
pip install cryptographyStep 1: Generating the encryption key
We will use symmetric encryption — the same key that locks (encrypts) the information is used to unlock (decrypt) it. The code below checks whether a key already exists, and if not, creates a key.key file. Never share this file; it is the only way to read your saved passwords.
from cryptography.fernet import Fernet
import os
def generate_key():
if not os.path.exists("key.key"):
key = Fernet.generate_key()
with open("key.key", "wb") as key_file:
key_file.write(key)
def load_key():
return open("key.key", "rb").read()
generate_key()
key = load_key()
fernet = Fernet(key)Note the use of the with context manager. It is one of the best practices for handling files, ensuring the file closes properly even if an error occurs during execution. Learn more about using with to open files in Python.
Step 2: Adding passwords
Fernet encryption requires text in bytes format. We use encode() on the string before encrypting and save the result in a plain text file — so anyone who opens passwords.txt sees only meaningless codes.
def add_password():
name = input("Service/Account name: ")
password = input("Password: ")
encrypted = fernet.encrypt(password.encode()).decode()
with open("passwords.txt", "a") as f:
f.write(f"{name} | {encrypted}n")
print("Password saved successfully!")Step 3: Viewing saved passwords
The view function reads the file line by line, splits the service name from the encrypted password, applies the key to decrypt, and shows the original text on screen. We handle potential errors with a try-except block.
def view_passwords():
try:
with open("passwords.txt", "r") as f:
for line in f.readlines():
data = line.rstrip()
name, enc_pass = data.split(" | ")
real_pass = fernet.decrypt(enc_pass.encode()).decode()
print(f"Service: {name} | Password: {real_pass}")
except FileNotFoundError:
print("No passwords saved yet.")Step 4: Generating secure passwords
A good password manager also helps create passwords. The secrets module is designed specifically to generate cryptographically strong random data — unlike the common random module, which is predictable. Learn more about generating secure random numbers with secrets.
import secrets
import string
def generate_strong_password(length=16):
characters = string.ascii_letters + string.digits + string.punctuation
return ''.join(secrets.choice(characters) for _ in range(length))Step 5: Building the interactive menu
def menu():
while True:
print("1. Add new password")
print("2. View saved passwords")
print("3. Generate strong password suggestion")
print("4. Exit")
choice = input("nChoose an option: ")
if choice == "1":
add_password()
elif choice == "2":
view_passwords()
elif choice == "3":
print(f"nSuggestion: {generate_strong_password()}n")
elif choice == "4":
print("Closing manager. Keep your key.key file safe!")
break
else:
print("n[ERROR] Invalid option. Try again.n")
if __name__ == "__main__":
menu()Security best practices and next steps
Although this script is functional, in a real scenario you should never store the master key in the same location as the password database. A more professional solution would derive the key from a master password entered by the user, using password hashing algorithms. Another improvement is ensuring sensitive data does not stay in RAM for long. For high-security projects, developers follow guidelines from OWASP, which provides extensive manuals on preventing data leaks.
Frequently Asked Questions
Where are passwords stored?
In the passwords.txt file in the same folder where you run the script. They are encrypted and cannot be read without the key.
What happens if I delete key.key?
You permanently lose access to all saved passwords in passwords.txt — there is no way to decrypt them without the key.
Why use secrets instead of random?
The random module produces pseudo-random numbers that are predictable for hackers. The secrets module uses secure OS sources to generate real randomness.
Does this code work on Windows, Linux, and Mac?
Yes. The code follows Python’s cross-platform standards, using libraries that operate identically on all major operating systems.
Can I add a master password to open the program?
Yes. Create a function that asks for a password at startup and only shows the menu if the input matches a pre-defined hash value.






