Encrypted Private Diary App in Python
Code prompt
Local encrypted chat record manager.
import tkinter as tk
from tkinter import ttk, scrolledtext, messagebox, simpledialog
import json
import os
from datetime import datetime
from cryptography.fernet import Fernet
import hashlib
import base64
from pathlib import Path
import threading
import time
class SecureChatManager:
def __init__(self):
self.data_dir = Path("secure_chats")
self.data_dir.mkdir(exist_ok=True)
self.key_file = self.data_dir / "master.key"
self.chats_file = self.data_dir / "encrypted_chats.enc"
self.master_key = self.load_or_create_master_key()
self.cipher = Fernet(self.master_key)
self.chats = self.load_chats()
self.current_chat_id = None
self.root = None
def load_or_create_master_key(self):
if self.key_file.exists():
with open(self.key_file, 'rb') as f:
return f.read()
else:
key = Fernet.generate_key()
with open(self.key_file, 'wb') as f:
f.write(key)
# Set restrictive permissions
os.chmod(self.key_file, 0o600)
return key
def encrypt_data(self, data):
return self.cipher.encrypt(json.dumps(data).encode())
def decrypt_data(self, encrypted_data):
try:
decrypted = self.cipher.decrypt(encrypted_data)
return json.loads(decrypted.decode())
except Exception:
messagebox.showerror("Error", "Failed to decrypt data. Wrong key or corrupted file.")
return {}
def load_chats(self):
if self.chats_file.exists():
try:
with open(self.chats_file, 'rb') as f:
encrypted = f.read()
return self.decrypt_data(encrypted)
except Exception:
return {}
return {}
def save_chats(self):
try:
encrypted = self.encrypt_data(self.chats)
with open(self.chats_file, 'wb') as f:
f.write(encrypted)
os.chmod(self.chats_file, 0o600)
except Exception as e:
messagebox.showerror("Error", f"Failed to save chats: {str(e)}")
def create_chat(self, title):
chat_id = hashlib.md5(f"{title}{datetime.now()}".encode()).hexdigest()[:12]
self.chats[chat_id] = {
"title": title,
"messages": [],
"created_at": datetime.now().isoformat(),
"last_updated": datetime.now().isoformat()
}
self.save_chats()
return chat_id
def add_message(self, chat_id, sender, content):
if chat_id not in self.chats:
return False
self.chats[chat_id]["messages"].append({
"sender": sender,
"content": content,
"timestamp": datetime.now().isoformat()
})
self.chats[chat_id]["last_updated"] = datetime.now().isoformat()
self.save_chats()
return True
def get_chat_list(self):
return sorted(
[(cid, data["title"], data["last_updated"]) for cid, data in self.chats.items()],
key=lambda x: x[2],
reverse=True
)
def get_chat(self, chat_id):
return self.chats.get(chat_id, None)
def delete_chat(self, chat_id):
if chat_id in self.chats:
del self.chats[chat_id]
self.save_chats()
return True
return False
class ChatGUI:
def __init__(self):
self.manager = SecureChatManager()
self.setup_ui()
self.refresh_chat_list()
def setup_ui(self):
self.root = tk.Tk()
self.root.title("SecureChat • Local • Encrypted")
self.root.geometry("1000x700")
self.root.configure(bg="#f0f4f8")
# Soft color palette
self.colors = {
"bg": "#f0f4f8",
"sidebar": "#e6edf5",
"accent": "#7c9cb8",
"text": "#2c3e50",
"message_user": "#a8d5ba",
"message_other": "#d4e0f0",
"input_bg": "#ffffff"
}
self.root.configure(bg=self.colors["bg"])
# Main container
main_frame = tk.Frame(self.root, bg=self.colors["bg"])
main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
# Sidebar
sidebar = tk.Frame(main_frame, bg=self.colors["sidebar"], width=280, relief=tk.RAISED, bd=1)
sidebar.pack(side=tk.LEFT, fill=tk.Y, padx=(0, 8))
sidebar.pack_propagate(False)
# Header
header = tk.Frame(sidebar, bg=self.colors["accent"], height=60)
header.pack(fill=tk.X)
header.pack_propagate(False)
tk.Label(header, text="🔒 SecureChat", font=("Helvetica", 18, "bold"),
fg="white", bg=self.colors["accent"]).pack(pady=15)
# New chat button
new_btn = tk.Button(sidebar, text="+ New Conversation", font=("Helvetica", 11, "bold"),
bg="#5a8a9e", fg="white", relief=tk.FLAT, height=2,
command=self.new_chat)
new_btn.pack(pady=15, padx=15, fill=tk.X)
# Chat list
tk.Label(sidebar, text="Conversations", font=("Helvetica", 10, "bold"),
bg=self.colors["sidebar"], fg=self.colors["text"], anchor="w").pack(padx=15, pady=(10,5))
self.chat_listbox = tk.Listbox(sidebar, bg="white", font=("Helvetica", 10),
selectbackground=self.colors["accent"], relief=tk.FLAT,
highlightthickness=0)
self.chat_listbox.pack(fill=tk.BOTH, expand=True, padx=15, pady=(0,15))
self.chat_listbox.bind('<<ListboxSelect>>', self.on_chat_select)
# Main chat area
chat_area = tk.Frame(main_frame, bg=self.colors["bg"])
chat_area.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)
# Chat header
self.chat_header = tk.Frame(chat_area, bg=self.colors["accent"], height=55)
self.chat_header.pack(fill=tk.X)
self.chat_header.pack_propagate(False)
self.title_label = tk.Label(self.chat_header, text="Select or create a conversation",
font=("Helvetica", 14, "bold"), fg="white",
bg=self.colors["accent"], anchor="w")
self.title_label.pack(side=tk.LEFT, padx=20, pady=15)
# Messages area
self.messages_area = scrolledtext.ScrolledText(chat_area, wrap=tk.WORD, font=("Helvetica", 11),
bg="#f8fafc", fg=self.colors["text"],
relief=tk.FLAT, padx=15, pady=15)
self.messages_area.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
self.messages_area.config(state=tk.DISABLED)
# Input area
input_frame = tk.Frame(chat_area, bg=self.colors["bg"])
input_frame.pack(fill=tk.X, padx=10, pady=(0,10))
self.input_text = tk.Text(input_frame, height=4, font=("Helvetica", 11),
bg=self.colors["input_bg"], relief=tk.SOLID, bd=1)
self.input_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=(0,8))
send_btn = tk.Button(input_frame, text="Send", font=("Helvetica", 11, "bold"),
bg=self.colors["accent"], fg="white", width=10, height=2,
command=self.send_message)
send_btn.pack(side=tk.RIGHT)
# Status bar
self.status = tk.Label(self.root, text="All conversations encrypted locally • Never leaves your device",
bg="#e6edf5", fg="#546e7a", font=("Helvetica", 9), anchor="w")
self.status.pack(side=tk.BOTTOM, fill=tk.X, ipady=4, padx=10)
# Keyboard binding
self.root.bind('<Control-Return>', lambda e: self.send_message())
self.current_chat_id = None
def refresh_chat_list(self):
self.chat_listbox.delete(0, tk.END)
for chat_id, title, last_updated in self.manager.get_chat_list():
dt = datetime.fromisoformat(last_updated)
time_str = dt.strftime("%b %d, %H:%M")
self.chat_listbox.insert(tk.END, f"{title} • {time_str}")
self.chat_listbox.itemconfig(tk.END, {'fg': '#2c3e50'})
def new_chat(self):
title = simpledialog.askstring("New Conversation", "Conversation title:",
initialvalue=f"Chat {datetime.now().strftime('%b %d')}")
if title and title.strip():
chat_id = self.manager.create_chat(title.strip())
self.refresh_chat_list()
self.load_chat(chat_id)
def on_chat_select(self, event):
selection = self.chat_listbox.curselection()
if not selection:
return
index = selection[0]
chat_list = self.manager.get_chat_list()
if index < len(chat_list):
chat_id = chat_list[index][0]
self.load_chat(chat_id)
def load_chat(self, chat_id):
self.current_chat_id = chat_id
chat = self.manager.get_chat(chat_id)
if not chat:
return
self.title_label.config(text=chat["title"])
self.messages_area.config(state=tk.NORMAL)
self.messages_area.delete(1.0, tk.END)
for msg in chat["messages"]:
timestamp = datetime.fromisoformat(msg["timestamp"]).strftime("%H:%M")
if msg["sender"] == "You":
prefix = "You"
color = "#2e7d32"
align = "right"
else:
prefix = "Assistant"
color = "#1565c0"
align = "left"
self.messages_area.insert(tk.END, f"{prefix} • {timestamp}\n", "header")
self.messages_area.insert(tk.END, f"{msg['content']}\n\n", "message")
self.messages_area.tag_config("header", font=("Helvetica", 9, "bold"), foreground=color)
self.messages_area.tag_config("message", font=("Helvetica", 11), lmargin1=20, lmargin2=20)
self.messages_area.config(state=tk.DISABLED)
self.messages_area.see(tk.END)
def send_message(self):
if not self.current_chat_id:
messagebox.showinfo("Info", "Please create or select a conversation first.")
return
content = self.input_text.get("1.0", tk.END).strip()
if not content:
return
# Add user message
self.manager.add_message(self.current_chat_id, "You", content)
# Display immediately
self.messages_area.config(state=tk.NORMAL)
timestamp = datetime.now().strftime("%H:%M")
self.messages_area.insert(tk.END, f"You • {timestamp}\n", "header")
self.messages_area.insert(tk.END, f"{content}\n\n", "message")
self.messages_area.tag_config("header", font=("Helvetica", 9, "bold"), foreground="#2e7d32")
self.messages_area.tag_config("message", font=("Helvetica", 11), lmargin1=20, lmargin2=20)
self.messages_area.config(state=tk.DISABLED)
self.messages_area.see(tk.END)
self.input_text.delete("1.0", tk.END)
# Simulate assistant reply (you can replace with real LLM if desired)
self.root.after(800, self.simulate_reply)
self.refresh_chat_list()
def simulate_reply(self):
if not self.current_chat_id:
return
reply = "Message received and stored securely on your device. All data is encrypted with AES-256."
self.manager.add_message(self.current_chat_id, "Assistant", reply)
self.messages_area.config(state=tk.NORMAL)
timestamp = datetime.now().strftime("%H:%M")
self.messages_area.insert(tk.END, f"Assistant • {timestamp}\n", "header")
self.messages_area.insert(tk.END, f"{reply}\n\n", "message")
self.messages_area.tag_config("header", font=("Helvetica", 9, "bold"), foreground="#1565c0")
self.messages_area.config(state=tk.DISABLED)
self.messages_area.see(tk.END)
self.refresh_chat_list()
def run(self):
self.root.mainloop()
if __name__ == "__main__":
print("Starting SecureChat - All conversations are encrypted locally")
print("Data is stored in ./secure_chats/ directory")
print("Master encryption key is automatically generated and stored securely\n")
app = ChatGUI()
app.run()Write a Python script that can locally create a secure chat record manager. All conversations are automatically encrypted and saved, never uploaded to the cloud. The interface design has soft tones.
This prompt focuses on “Local Encrypted Chat Record Manager”: Local encrypted chat record manager. It is ready to use for code generation on HackAIGC.
Open the prompt, tap Use prompt or Copy prompt, then run it with your preferred model and settings.
The brief for “Local Encrypted Chat Record Manager” includes soft cues. Edit the prompt to change the tone, structure, or level of detail.
Yes. Copy the prompt text, modify details, then generate again on HackAIGC.