Secure Notes App

 import os

import tkinter as tk

from tkinter import messagebox, simpledialog

from cryptography.fernet import Fernet


# Generate a key file if it doesn’t exist

KEY_FILE = "secret.key"

NOTES_FILE = "secure_notes.txt"


def generate_key():

    key = Fernet.generate_key()

    with open(KEY_FILE, "wb") as key_file:

        key_file.write(key)


def load_key():

    if not os.path.exists(KEY_FILE):

        generate_key()

    with open(KEY_FILE, "rb") as key_file:

        return key_file.read()


# Load encryption key

key = load_key()

cipher_suite = Fernet(key)


def encrypt_message(message):

    return cipher_suite.encrypt(message.encode()).decode()


def decrypt_message(encrypted_message):

    return cipher_suite.decrypt(encrypted_message.encode()).decode()


def save_note():

    note = note_text.get("1.0", tk.END).strip()

    if not note:

        messagebox.showwarning("Warning", "Note cannot be empty!")

        return

    

    encrypted_note = encrypt_message(note)

    with open(NOTES_FILE, "a") as file:

        file.write(encrypted_note + "\n")

    

    messagebox.showinfo("Success", "Note saved securely!")

    note_text.delete("1.0", tk.END)


def load_notes():

    if not os.path.exists(NOTES_FILE):

        messagebox.showinfo("No Notes", "No saved notes found.")

        return

    

    with open(NOTES_FILE, "r") as file:

        encrypted_notes = file.readlines()

    

    if not encrypted_notes:

        messagebox.showinfo("No Notes", "No saved notes found.")

        return


    password = simpledialog.askstring("Password", "Enter decryption password:", show="*")

    

    if password:  # Dummy check

        try:

            decrypted_notes = [decrypt_message(note.strip()) for note in encrypted_notes]

            messagebox.showinfo("Your Notes", "\n\n".join(decrypted_notes))

        except Exception as e:

            messagebox.showerror("Error", "Failed to decrypt notes.")

    else:

        messagebox.showwarning("Warning", "Password cannot be empty!")


# GUI Setup

root = tk.Tk()

root.title("Secure Notes App")

root.geometry("400x400")


tk.Label(root, text="Enter your note:", font=("Arial", 12)).pack(pady=5)

note_text = tk.Text(root, height=8, width=40)

note_text.pack()


save_btn = tk.Button(root, text="Save Note", command=save_note)

save_btn.pack(pady=5)


load_btn = tk.Button(root, text="Load Notes", command=load_notes)

load_btn.pack(pady=5)


root.mainloop()


No comments: