Secret V2.0 — Terminal Password, Text, Clipboard & File Encryption Utility

Author: Perisa Reljic [ ▽ Ш ]

Script File: secret_V_2.0.py

Overview

Secret V2.0 is a lightweight Python command-line utility built for Linux terminal workflows. It combines cryptographically stronger random password generation, text and clipboard encryption/decryption, and binary-safe file encryption and decryption inside a clean numbered interactive menu—while still supporting direct CLI commands.

This tool is built with a clear mission — to serve activists, investigative journalists, tech enthusiasts, and anyone who values privacy, needs to secure sensitive text, or wants to generate unbreakable passwords directly from their terminal.

Secret V2.0 is one of “Let Me Script You” series made by Perisa Reljic / Art Studio Shumadia Gothic.

What Is New & Improved in Secret V2.0

  • Numbered Interactive Menu ([0–7]): Brings a clear, numbered terminal menu experience into Secret V2.0 alongside existing CLI subcommands (gen, enc, dec, fenc, fdec, clenc, cldec).
  • Universal Binary File Support: File encryption and decryption now operate in binary mode (rb / wb), supporting photos, PDFs, Office documents, archives, and plain text files without corrupting non-text data.
  • Integrity Verification on File Decryption: Secret V2.0 embeds a version header (LMSY_BIN_V2), a fresh 16-byte random salt per encryption, and a 32-byte SHA-256 digest of the original payload. When decrypting, it validates the SHA-256 digest before writing the restored file, catching wrong passphrases or corrupted files immediately.
  • Working-Directory-Focused Workflow & Retry Loop: Displays the active working directory in the header and expects target filenames within that current directory rather than long full paths. If a filename is mistyped or missing from the current working directory, it reports the error clearly and prompts again instead of aborting.
  • Stronger Random Password Generation: Uses Python’s secrets module rather than random for generating passwords, with optional direct copying to the system clipboard via xclip or xsel.

Disclaimer

This tool is provided for personal privacy, learning, and authorized local file/text handling. The author makes no warranties regarding fitness for any particular purpose and is not responsible for data loss, forgotten passphrases, or improper use. Always back up important files before encrypting or modifying data, and store master passphrases securely—lost passphrases cannot be recovered.

Source Code:

#!/usr/bin/env python3

import sys
import os
import secrets
import base64
import hashlib
import subprocess
from getpass import getpass

# ==========================================
# Title: Secret V2.0
# Series: Let Me Script You
# Author: Perisa Reljic [ ▽ Ш ]
# ==========================================

MAGIC_HEADER = b"LMSY_BIN_V2\x00"


# ------------------------------------------
# 1. PASSWORD GENERATOR
# ------------------------------------------
def generate_password(length: int = 16) -> str:
    """Generates a cryptographically secure random password."""
    chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+-=[]{}|;:,.<>?"
    return "".join(secrets.choice(chars) for _ in range(length))


# ------------------------------------------
# 2. KEY DERIVATION & BYTE STREAM CIPHER
# ------------------------------------------
def derive_key(passphrase: str, salt: bytes) -> bytes:
    """Derives a 32-byte cryptographic key from the master passphrase using PBKDF2."""
    return hashlib.pbkdf2_hmac("sha256", passphrase.encode("utf-8"), salt, 100_000)


def xor_bytes(data: bytes, key: bytes) -> bytes:
    """Applies XOR transformation over raw bytes using a repeating key."""
    key_len = len(key)
    return bytes(b ^ key[i % key_len] for i, b in enumerate(data))


# ------------------------------------------
# 3. TEXT ENCRYPTION & DECRYPTION
# ------------------------------------------
def simple_encrypt(plain_text: str, passphrase: str) -> str:
    """Encrypts plain text into a Base64 cipher string."""
    salt = os.urandom(16)
    key = derive_key(passphrase, salt)
    encrypted = xor_bytes(plain_text.encode("utf-8"), key)
    return base64.b64encode(salt + encrypted).decode("utf-8")


def simple_decrypt(cipher_base64: str, passphrase: str) -> tuple[bool, str]:
    """Decrypts a Base64 cipher string back to plain text."""
    try:
        combined = base64.b64decode(cipher_base64.encode("utf-8"))
        if len(combined) < 16:
            return False, "[Error]: Invalid cipher format."
        salt = combined[:16]
        encrypted = combined[16:]
        key = derive_key(passphrase, salt)
        decrypted = xor_bytes(encrypted, key)
        return True, decrypted.decode("utf-8")
    except Exception:
        return False, "[Error]: Decryption failed (wrong passphrase or invalid format)."


# ------------------------------------------
# 4. CURRENT DIRECTORY FILE RESOLUTION
# ------------------------------------------
def find_file_in_current_dir(filename: str) -> str | None:
    """Checks only the current working directory for the exact or matching filename."""
    cleaned = filename.strip().strip("'\"")
    if not cleaned:
        return None

    cwd = os.getcwd()
    direct_path = os.path.join(cwd, cleaned)
    if os.path.isfile(direct_path):
        return direct_path

    # If extension was omitted, check exact base name match in current directory
    target_lower = cleaned.lower()
    for entry in sorted(os.listdir(cwd)):
        full_path = os.path.join(cwd, entry)
        if os.path.isfile(full_path) and os.path.splitext(entry)[0].lower() == target_lower:
            return full_path

    return None


def prompt_existing_file(prompt_label: str) -> str | None:
    """Prompts for a filename in the current working directory until found or cancelled."""
    cwd = os.getcwd()
    while True:
        try:
            raw_name = input(prompt_label)
        except (KeyboardInterrupt, EOFError):
            print("\n[Info]: Cancelled.")
            return None

        cleaned = raw_name.strip().strip("'\"")
        if not cleaned:
            print("[Error]: Filename cannot be empty. Please try again.")
            continue

        found = find_file_in_current_dir(cleaned)
        if found:
            return found

        print(f"[Error]: File '{cleaned}' was not found in the current working directory ({cwd}). Please try again.")


def resolve_output_in_current_dir(user_out: str, default_name: str) -> str:
    """Resolves output filename inside the current working directory."""
    cwd = os.getcwd()
    cleaned = user_out.strip().strip("'\"")
    if not cleaned:
        return os.path.join(cwd, default_name)
    if os.path.dirname(cleaned) == "":
        return os.path.join(cwd, cleaned)
    return os.path.abspath(cleaned)


# ------------------------------------------
# 5. UNIVERSAL FILE ENCRYPTION & DECRYPTION
# ------------------------------------------
def encrypt_file(input_file: str, output_file: str, passphrase: str) -> bool:
    """Encrypts any file (photo, PDF, Office doc, text, etc.) in binary mode."""
    try:
        with open(input_file, "rb") as f:
            raw_data = f.read()

        salt = os.urandom(16)
        key = derive_key(passphrase, salt)
        digest = hashlib.sha256(raw_data).digest()

        encrypted_payload = xor_bytes(digest + raw_data, key)
        final_blob = MAGIC_HEADER + salt + encrypted_payload

        with open(output_file, "wb") as f:
            f.write(final_blob)

        print(f"[Success]: Encrypted '{os.path.basename(input_file)}' -> '{os.path.basename(output_file)}' ({len(final_blob)} bytes).")
        return True
    except Exception as e:
        print(f"[Error]: Failed to encrypt file -> {e}")
        return False


def decrypt_file(input_file: str, output_file: str, passphrase: str) -> bool:
    """Decrypts binary v2 files (with fallback for legacy v1 text files)."""
    try:
        with open(input_file, "rb") as f:
            blob = f.read()

        if blob.startswith(MAGIC_HEADER):
            header_len = len(MAGIC_HEADER)
            if len(blob) < header_len + 16 + 32:
                print("[Error]: Encrypted file is corrupted or incomplete.")
                return False

            salt = blob[header_len : header_len + 16]
            encrypted_payload = blob[header_len + 16 :]

            key = derive_key(passphrase, salt)
            decrypted_payload = xor_bytes(encrypted_payload, key)

            expected_digest = decrypted_payload[:32]
            raw_data = decrypted_payload[32:]

            if hashlib.sha256(raw_data).digest() != expected_digest:
                print("[Error]: Decryption failed (wrong passphrase or corrupted file).")
                return False

            with open(output_file, "wb") as f:
                f.write(raw_data)

            print(f"[Success]: Decrypted '{os.path.basename(input_file)}' -> '{os.path.basename(output_file)}' ({len(raw_data)} bytes).")
            return True

        ok, plain = simple_decrypt(blob.decode("utf-8").strip(), passphrase)
        if not ok:
            print(plain)
            return False

        with open(output_file, "w", encoding="utf-8") as f:
            f.write(plain)

        print(f"[Success]: Decrypted legacy file '{os.path.basename(input_file)}' -> '{os.path.basename(output_file)}'.")
        return True

    except Exception as e:
        print(f"[Error]: Failed to decrypt file -> {e}")
        return False


# ------------------------------------------
# 6. CLIPBOARD HANDLING (Xclip / Xsel)
# ------------------------------------------
def get_clipboard() -> str | None:
    """Reads text from the system clipboard on Linux."""
    for cmd in (["xclip", "-selection", "clipboard", "-o"], ["xsel", "--clipboard", "--output"]):
        try:
            p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
            if p.returncode == 0:
                return p.stdout
        except FileNotFoundError:
            continue

    print("[Error]: Neither 'xclip' nor 'xsel' found. Install via: sudo apt install xclip")
    return None


def set_clipboard(text: str) -> bool:
    """Copies given text to the system clipboard."""
    for cmd in (["xclip", "-selection", "clipboard"], ["xsel", "--clipboard", "--input"]):
        try:
            subprocess.run(cmd, input=text, text=True, check=True)
            return True
        except FileNotFoundError:
            continue

    print("[Error]: Unable to copy to clipboard (missing xclip/xsel).")
    return False


# ------------------------------------------
# 7. INTERACTIVE NUMBERED MENU
# ------------------------------------------
def print_banner():
    print("\n========================================================")
    print("  Secret V2.0 | From the series: Let Me Script You")
    print("  Author: Perisa Reljic [ ▽ Ш ]")
    print("========================================================")


def get_confirmed_passphrase() -> str | None:
    p1 = getpass("Enter master passphrase: ")
    if not p1:
        print("[Error]: Passphrase cannot be empty.")
        return None
    p2 = getpass("Confirm master passphrase: ")
    if p1 != p2:
        print("[Error]: Passphrases do not match.")
        return None
    return p1


def interactive_menu():
    while True:
        print_banner()
        print("  [1] Generate Strong Password")
        print("  [2] Encrypt Text (Terminal)")
        print("  [3] Decrypt Text (Terminal)")
        print("  [4] Encrypt File (Photo, PDF, Office, Text...)")
        print("  [5] Decrypt File")
        print("  [6] Encrypt Clipboard Text")
        print("  [7] Decrypt Clipboard Text")
        print("  [0] Exit")
        print("--------------------------------------------------------")

        try:
            choice = input("Select option [0-7]: ").strip()
        except (KeyboardInterrupt, EOFError):
            print("\nExiting Secret V2.0.")
            break

        if choice == "0":
            print("Exiting Secret V2.0.")
            break

        elif choice == "1":
            raw_len = input("Password length [Enter for 16]: ").strip()
            length = int(raw_len) if raw_len.isdigit() and int(raw_len) > 0 else 16
            pwd = generate_password(length)
            print(f"\nGenerated Password: {pwd}")
            if input("Copy to clipboard? [y/N]: ").strip().lower() == "y":
                if set_clipboard(pwd):
                    print("[Success]: Password copied to clipboard.")

        elif choice == "2":
            text = getpass("Enter text to encrypt: ")
            if not text:
                print("[Error]: Text cannot be empty.")
                continue
            passphrase = get_confirmed_passphrase()
            if passphrase:
                print(f"\nEncrypted Result:\n{simple_encrypt(text, passphrase)}")

        elif choice == "3":
            cipher = input("Enter encrypted string: ").strip()
            if not cipher:
                print("[Error]: Encrypted string cannot be empty.")
                continue
            passphrase = getpass("Enter master passphrase: ")
            ok, result = simple_decrypt(cipher, passphrase)
            print(f"\n{result}" if not ok else f"\nDecrypted Result:\n{result}")

        elif choice == "4":
            in_file = prompt_existing_file("Enter filename in current folder to encrypt: ")
            if not in_file:
                continue

            base_name = os.path.basename(in_file)
            default_out = f"{base_name}.enc"
            raw_out = input(f"Output filename [Enter for '{default_out}']: ")
            out_file = resolve_output_in_current_dir(raw_out, default_out)

            passphrase = get_confirmed_passphrase()
            if passphrase:
                encrypt_file(in_file, out_file, passphrase)

        elif choice == "5":
            in_file = prompt_existing_file("Enter encrypted filename in current folder: ")
            if not in_file:
                continue

            base_name = os.path.basename(in_file)
            if base_name.endswith(".enc"):
                suggested = base_name[:-4]
                if os.path.exists(os.path.join(os.getcwd(), suggested)):
                    suggested = f"{suggested}.dec"
            else:
                suggested = f"{base_name}.dec"

            raw_out = input(f"Output filename [Enter for '{suggested}']: ")
            out_file = resolve_output_in_current_dir(raw_out, suggested)

            passphrase = getpass("Enter master passphrase: ")
            decrypt_file(in_file, out_file, passphrase)

        elif choice == "6":
            text = get_clipboard()
            if text is None or not text.strip():
                print("[Error]: Clipboard is empty.")
                continue
            passphrase = get_confirmed_passphrase()
            if passphrase and set_clipboard(simple_encrypt(text, passphrase)):
                print("[Success]: Clipboard text encrypted and copied back to clipboard.")

        elif choice == "7":
            cipher = get_clipboard()
            if cipher is None or not cipher.strip():
                print("[Error]: Clipboard is empty.")
                continue
            passphrase = getpass("Enter master passphrase: ")
            ok, result = simple_decrypt(cipher.strip(), passphrase)
            if not ok:
                print(result)
            elif set_clipboard(result):
                print("[Success]: Clipboard cipher decrypted and copied back to clipboard.")

        else:
            print("[Warning]: Invalid option. Please choose a number between 0 and 7.")

        try:
            input("\nPress Enter to return to menu...")
        except (KeyboardInterrupt, EOFError):
            print("\nExiting Secret V2.0.")
            break


# ------------------------------------------
# 8. CLI ENTRY POINT
# ------------------------------------------
if __name__ == "__main__":
    if len(sys.argv) < 2:
        interactive_menu()
        sys.exit(0)

    cmd = sys.argv[1]

    if cmd == "gen":
        length = int(sys.argv[2]) if len(sys.argv) > 2 and sys.argv[2].isdigit() else 16
        print(f"Generated Password: {generate_password(length)}")

    elif cmd == "enc":
        text = getpass("Enter text to encrypt: ")
        passphrase = get_confirmed_passphrase()
        if passphrase:
            print(f"\nEncrypted Result:\n{simple_encrypt(text, passphrase)}")

    elif cmd == "dec":
        cipher = input("Enter encrypted string: ").strip()
        passphrase = getpass("Enter master passphrase: ")
        ok, result = simple_decrypt(cipher, passphrase)
        print(f"\n{result}" if not ok else f"\nDecrypted Result:\n{result}")
        sys.exit(0 if ok else 1)

    elif cmd == "fenc":
        if len(sys.argv) < 3:
            print("Usage: secret fenc <filename> [output_filename]")
            sys.exit(1)
        in_file = find_file_in_current_dir(sys.argv[2])
        if not in_file:
            print(f"[Error]: File '{sys.argv[2]}' was not found in the current working directory ({os.getcwd()}).")
            sys.exit(1)
        default_out = f"{os.path.basename(in_file)}.enc"
        out_file = resolve_output_in_current_dir(sys.argv[3] if len(sys.argv) > 3 else "", default_out)
        passphrase = get_confirmed_passphrase()
        if passphrase and encrypt_file(in_file, out_file, passphrase):
            sys.exit(0)
        sys.exit(1)

    elif cmd == "fdec":
        if len(sys.argv) < 3:
            print("Usage: secret fdec <encrypted_filename> [output_filename]")
            sys.exit(1)
        in_file = find_file_in_current_dir(sys.argv[2])
        if not in_file:
            print(f"[Error]: File '{sys.argv[2]}' was not found in the current working directory ({os.getcwd()}).")
            sys.exit(1)
        base_name = os.path.basename(in_file)
        suggested = base_name[:-4] if base_name.endswith(".enc") else f"{base_name}.dec"
        out_file = resolve_output_in_current_dir(sys.argv[3] if len(sys.argv) > 3 else "", suggested)
        passphrase = getpass("Enter master passphrase: ")
        if decrypt_file(in_file, out_file, passphrase):
            sys.exit(0)
        sys.exit(1)

    elif cmd == "clenc":
        text = get_clipboard()
        if not text or not text.strip():
            print("[Error]: Clipboard is empty.")
            sys.exit(1)
        passphrase = get_confirmed_passphrase()
        if passphrase and set_clipboard(simple_encrypt(text, passphrase)):
            print("[Success]: Clipboard text encrypted and copied back to clipboard.")
            sys.exit(0)
        sys.exit(1)

    elif cmd == "cldec":
        cipher = get_clipboard()
        if not cipher or not cipher.strip():
            print("[Error]: Clipboard is empty.")
            sys.exit(1)
        pwd = getpass("Enter master passphrase: ")
        ok, res = simple_decrypt(cipher.strip(), pwd)
        if ok and set_clipboard(res):
            print("[Success]: Clipboard cipher decrypted and copied back to clipboard.")
            sys.exit(0)
        print(res)
        sys.exit(1)

    else:
        print(f"[Error]: Unknown command '{cmd}'. Run 'secret' without arguments for the interactive menu.")
        sys.exit(1)

Download

You can download the full, original source code from my official GitHub repository: 🔗

— Author: Periša Reljić [ ▽ Ш ]