Files
ChaosCrypt/chaoscrypt/tui.py
T
dvs dd49043171 v4.2.6: Self-describing format, byte pipeline, and a performance pass
Every key file and ciphertext now carries a header that states how it was
produced: magic, two fixed markers, and a complete JSON configuration record.
A reader takes its parameters from the artefact rather than from the caller.

This is an incompatible format change. Headerless input is rejected with E017;
pre-4.2.6 material is read through a compatibility API that wraps it in a
minimal header and then uses the ordinary path, so the strict path stays strict.

Added
- Self-describing header on all artefacts, with a normative specification in
  docs/FORMAT.md
- E017 MissingMagicHeader and E018 MalformedHeader
- Byte pipeline for turbo and raw: the XOR layers exchange raw bytes rather
  than hexadecimal text, cutting expansion from 5.33x to 2.00x and raising
  throughput about 4x. The old behaviour is available as mid="hex".
- Selectable output encoding for turbo and raw: hex (2.00x) or base64 (1.33x)
- Legacy compatibility API: wrap_legacy, decrypt_legacy, decrypt_legacy_auto,
  load_legacy_keys
- Frozen reference vectors covering every mode, encoding and intermediate
- docs/benchmark.md with measured throughput and the profiling behind it

Changed
- Default mode is fast: byte-for-byte compatible with the original algorithm,
  roughly 30x quicker
- Substitution, case flipping and the printable fold use bytes.translate over
  precomputed tables
- XOR layers use one big-integer operation instead of a per-byte loop
- Keystream derivation caches length-independent base material; expansion uses
  cached translation tables and list accumulation rather than str +=
- _get_dynamic_key repeats by multiplication. The loop version was quadratic:
  covering a 5.6 MB intermediate took 866 ms, now 3 ms, output unchanged.
- _derive_final_key decodes only the prefix the output consumes
- The decrypt path no longer copies or scans the whole artefact: a redundant
  strip(), a full-string int(payload, 16), and three whole-string slices in
  strip_header were removed. Decryption at 512 KiB went from 34 to 87 MB/s.
- Documentation rewritten for 4.2.6; all eleven markdown files are English

Fixed
1. Key derivation is no longer quadratic (_get_dynamic_key and
   _expand_keystream_slow shared the str += pattern)
2. Two hex-intermediate pipelines were asymmetric, so a turbo or raw artefact
   written with mid="hex" could not be read back
3. change_key_password and export_key_text wrote artefacts without a header
4. The constructor accepted encoding="base64" while the header records
   out="base"; both spellings are now accepted
5. A payload that is not valid hexadecimal reports E010 (MalformedCiphertext)
   rather than E011 (DecryptionFailed)
6. The TUI encoding menu referenced a missing translation

Security
- Format break from pre-4.2.6 artefacts, documented rather than accidental
- fast is not a weaker mode: the frozen vectors assert identical output
- The header adds no secrecy and is not authenticated; an application that must
  detect header tampering should MAC the whole artefact

Performance
- raw with the default bt intermediate: ~60 MB/s encryption, ~70 MB/s
  decryption, ciphertext 2.00x the payload
- Throughput holds steady from 64 KiB to 1 GiB
- The original implementation managed 0.08 MB/s
2026-09-27 22:06:34 +08:00

550 lines
19 KiB
Python

"""
ChaosCrypt interactive terminal UI.
A dependency-free menu-driven interface, intended for people who would
rather not memorise command line flags. English is the default language;
the menu can switch to Chinese at runtime.
Running ``chaoscrypt`` with no arguments launches this UI. The module is
imported lazily so that library users never pay for it.
"""
from __future__ import annotations
import os
import sys
from typing import Optional
from . import (DEFAULT_KEY_FILE, __version__, ChaosCrypt, MODES,
DEFAULT_MODE, ENCODINGS, DEFAULT_ENCODING)
from .errors import ChaosCryptError
from .i18n import DEFAULT_LANG, LANG_NAMES, t
__all__ = ["run_tui", "TUI"]
WIDTH = 66
# ANSI styling; degrades to plain text when the terminal cannot handle it.
_C = {
"reset": "\033[0m",
"bold": "\033[1m",
"dim": "\033[2m",
"cyan": "\033[36m",
"green": "\033[32m",
"yellow": "\033[33m",
"red": "\033[31m",
"magenta": "\033[35m",
}
def _supports_color() -> bool:
"""Whether the attached stdout can render ANSI colour."""
if os.environ.get("NO_COLOR"):
return False
if not sys.stdout.isatty():
return False
if os.name == "nt":
try:
import ctypes
kernel32 = ctypes.windll.kernel32
kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)
return True
except Exception:
return False
return True
_COLOR = _supports_color()
def c(text: str, *styles: str) -> str:
"""Wrap ``text`` in ANSI styles, or return it unchanged."""
if not _COLOR or not styles:
return text
return "".join(_C.get(s, "") for s in styles) + text + _C["reset"]
# ---------------------------------------------------------------------------
# Input helpers
# ---------------------------------------------------------------------------
class _Abort(Exception):
"""Raised when the user asks to return to the main menu."""
def _ask(prompt: str, default: Optional[str] = None) -> str:
suffix = f" [{default}]" if default else ""
try:
val = input(f"{c('>', 'cyan')} {prompt}{suffix}: ").strip()
except (EOFError, KeyboardInterrupt):
print()
raise _Abort()
if not val and default is not None:
return default
return val
def _ask_secret(prompt: str) -> str:
"""Read a password without echoing it when possible.
Interactive terminals use ``getpass`` so the input is not shown. Piped or
redirected input cannot use ``getpass``, so it falls back to ``input``,
which keeps the UI scriptable.
"""
label = f"{c('>', 'cyan')} {prompt}: "
if sys.stdin is not None and sys.stdin.isatty():
try:
import getpass
return getpass.getpass(label)
except (EOFError, KeyboardInterrupt):
print()
raise _Abort()
except Exception:
pass # Fall through to the non-echoing fallback below.
try:
return input(label).strip()
except (EOFError, KeyboardInterrupt):
print()
raise _Abort()
def _ask_yes_no(prompt: str, lang: str) -> bool:
try:
val = input(f"{c('>', 'cyan')} {prompt} [y/n]: ").strip().lower()
except (EOFError, KeyboardInterrupt):
print()
raise _Abort()
return val in ("y", "yes")
def _pause(lang: str) -> None:
try:
input(c(f" {t('press_enter', lang)}", "dim"))
except (EOFError, KeyboardInterrupt):
print()
def _rule() -> str:
return "-" * WIDTH
# ---------------------------------------------------------------------------
# TUI
# ---------------------------------------------------------------------------
class TUI:
"""Menu-driven bilingual interface over :class:`~chaoscrypt.ChaosCrypt`."""
def __init__(self, lang: str = DEFAULT_LANG,
key_file: str = DEFAULT_KEY_FILE,
mode: str = DEFAULT_MODE,
encoding: str = DEFAULT_ENCODING) -> None:
self.lang = lang if lang in LANG_NAMES else DEFAULT_LANG
self.key_file = key_file
self.mode = mode if mode in MODES else DEFAULT_MODE
self.encoding = encoding if encoding in ENCODINGS else DEFAULT_ENCODING
self.cc = ChaosCrypt(mode=self.mode, encoding=self.encoding)
self.key_password: Optional[str] = None
# ------------------------------------------------------------------ view
def _tr(self, key: str) -> str:
return t(key, self.lang)
def banner(self) -> None:
print()
print(c("+" + "=" * (WIDTH - 2) + "+", "magenta"))
title = f" {self._tr('app_title')} v{__version__}"
print(c("|", "magenta")
+ c(title.ljust(WIDTH - 2), "bold", "cyan")
+ c("|", "magenta"))
print(c("+" + "=" * (WIDTH - 2) + "+", "magenta"))
for line in self._tr("warn_banner").split("\n"):
print(c(line, "yellow"))
shown = self.cc.key_file or self.key_file or DEFAULT_KEY_FILE
state = (
c("[*] " + self._tr("key_loaded"), "green")
if self.cc.loaded
else c("[ ] " + self._tr("no_key_loaded"), "red")
)
print(f"\n{state} {c(shown, 'dim')} {c('[' + self.mode + ']', 'yellow')}")
def _print_error(self, exc: Exception) -> None:
"""Render a unified error, with a hint where one applies."""
print()
print(c("+" + "-" * (WIDTH - 2) + "+", "red"))
print(c("| ", "red")
+ c(f"{self._tr('err_prefix')}: {exc}", "red", "bold"))
print(c("+" + "-" * (WIDTH - 2) + "+", "red"))
msg = str(exc)
if "_E011" in msg or "_E003" in msg:
print(c(" " + self._tr("err_hint_password"), "dim"))
elif "_E004" in msg or "_E001" in msg:
print(c(" " + self._tr("err_hint_key_required"), "dim"))
# ------------------------------------------------------------------ menu
def menu(self) -> str:
items = [
("1", "menu_encrypt"),
("2", "menu_decrypt"),
("3", "menu_encrypt_file"),
("4", "menu_decrypt_file"),
("5", "menu_keygen"),
("6", "menu_loadkey"),
("7", "menu_keyinfo"),
("8", "menu_chpwd"),
("9", "menu_lang"),
("m", "menu_mode"),
("e", "menu_encoding"),
("a", "menu_about"),
("q", "menu_quit"),
]
print()
print(c(_rule(), "dim"))
print(c(" " + self._tr("menu_choose"), "bold"))
print(c(_rule(), "dim"))
for key, label in items:
print(f" {c('[' + key + ']', 'cyan')} {self._tr(label)}")
print(c(_rule(), "dim"))
return _ask(self._tr("menu_prompt")).lower()
# ------------------------------------------------------------ key state
def _ensure_key(self) -> bool:
"""Make sure a key is loaded, offering to create one if none exists.
Searches the instance's loaded key, then the remembered file, then
the default name.
"""
if self.cc.loaded:
return True
path = (
self.cc.key_file
or self.key_file
or DEFAULT_KEY_FILE
)
self.key_file = path
if not os.path.exists(path):
if _ask_yes_no(self._tr("prompt_create_if_missing"), self.lang):
return self.action_keygen()
return False
try:
pwd = self.key_password or _ask_secret(self._tr("prompt_key_password"))
self.cc.load(path, pwd)
self.key_password = pwd
print(c(f"{self._tr('key_loaded')}: {path}", "green"))
return True
except ChaosCryptError as exc:
self._print_error(exc)
return False
# ---------------------------------------------------------------- actions
def action_encrypt(self) -> None:
if not self._ensure_key():
return
text = _ask(self._tr("prompt_plaintext"))
if not text:
print(c(" " + self._tr("cancelled"), "dim"))
return
pwd = _ask_secret(self._tr("prompt_user_password"))
try:
ct = self.cc.encrypt(text, pwd)
print()
print(c(f"{self._tr('result_ciphertext')}:", "green", "bold"))
print(c(ct, "cyan"))
except ChaosCryptError as exc:
self._print_error(exc)
def action_decrypt(self) -> None:
if not self._ensure_key():
return
text = _ask(self._tr("prompt_ciphertext"))
if not text:
print(c(" " + self._tr("cancelled"), "dim"))
return
pwd = _ask_secret(self._tr("prompt_user_password"))
try:
pt = self.cc.decrypt(text, pwd)
print()
print(c(f"{self._tr('result_plaintext')}:", "green", "bold"))
print(c(pt, "cyan"))
except ChaosCryptError as exc:
self._print_error(exc)
def action_encrypt_file(self) -> None:
if not self._ensure_key():
return
src = _ask(self._tr("prompt_src_file"))
if not src or not os.path.exists(src):
print(c(f" {self._tr('failed')}: {src}", "red"))
return
dst = _ask(self._tr("prompt_dst_file")) or None
pwd = _ask_secret(self._tr("prompt_user_password"))
try:
out = self.cc.encrypt_file(src, pwd, dst)
print(c(f"{self._tr('file_written')}: {out}", "green"))
except ChaosCryptError as exc:
self._print_error(exc)
def action_decrypt_file(self) -> None:
if not self._ensure_key():
return
src = _ask(self._tr("prompt_src_file"))
if not src or not os.path.exists(src):
print(c(f" {self._tr('failed')}: {src}", "red"))
return
dst = _ask(self._tr("prompt_dst_file")) or None
pwd = _ask_secret(self._tr("prompt_user_password"))
try:
out = self.cc.decrypt_file(src, pwd, dst)
print(c(f"{self._tr('file_written')}: {out}", "green"))
except ChaosCryptError as exc:
self._print_error(exc)
def action_keygen(self) -> bool:
default = self.cc.key_file or self.key_file or DEFAULT_KEY_FILE
path = _ask(self._tr("prompt_key_file"), default)
overwrite = False
if os.path.exists(path):
if not _ask_yes_no(self._tr("prompt_overwrite"), self.lang):
print(c(" " + self._tr("cancelled"), "dim"))
return False
overwrite = True
pwd = _ask_secret(self._tr("prompt_key_password_new"))
if not pwd:
print(c(" " + self._tr("failed"), "red"))
return False
confirm = _ask_secret(self._tr("prompt_key_password_confirm"))
if pwd != confirm:
print(c(" ChaosCrypt_ERR_PasswordMismatch_E007", "red"))
return False
try:
out = self.cc.create_key(pwd, path, overwrite=overwrite)
self.key_file = out
self.key_password = pwd
print(c(f"{self._tr('key_saved')}: {out}", "green"))
return True
except ChaosCryptError as exc:
self._print_error(exc)
return False
def action_loadkey(self) -> None:
default = self.cc.key_file or self.key_file or DEFAULT_KEY_FILE
path = _ask(self._tr("prompt_key_file"), default)
pwd = _ask_secret(self._tr("prompt_key_password"))
try:
self.cc.load(path, pwd)
self.key_file = path
self.key_password = pwd
print(c(f"{self._tr('key_loaded')}: {path}", "green"))
except ChaosCryptError as exc:
self._print_error(exc)
def action_keyinfo(self) -> None:
if not self._ensure_key():
return
try:
info = self.cc.info()
except ChaosCryptError as exc:
self._print_error(exc)
return
rows = [
("info_key_file", info["key_file"]),
("info_version", info["version"]),
("info_upper", info["upper_mapping"]),
("info_lower", info["lower_mapping"]),
("info_digit", "".join(info["digit_mapping"].values())),
("info_equal", "".join(info["equal_mapping"].values())),
("info_flip", info["flip_pattern"]),
("info_long_key",
f"{info['long_key_length']} {self._tr('characters')}"),
("info_short_key",
f"{info['short_key_length']} {self._tr('characters')}"),
("info_loaded", self._tr("yes")),
("info_mode", self.mode),
("info_encoding", self.encoding),
]
print()
print(c(_rule(), "dim"))
for key, val in rows:
print(f" {c(self._tr(key), 'bold'):<38} {val}")
print(c(_rule(), "dim"))
def action_chpwd(self) -> None:
default = self.cc.key_file or self.key_file or DEFAULT_KEY_FILE
path = _ask(self._tr("prompt_key_file"), default)
if not os.path.exists(path):
print(c(" ChaosCrypt_ERR_KeyFileNotFound_E001", "red"))
return
old = _ask_secret(self._tr("prompt_key_password_old"))
new = _ask_secret(self._tr("prompt_key_password_new"))
confirm = _ask_secret(self._tr("prompt_key_password_confirm"))
if new != confirm:
print(c(" ChaosCrypt_ERR_PasswordMismatch_E007", "red"))
return
try:
out = self.cc.change_key_password(old, new, path)
self.key_password = new
print(c(f"{self._tr('key_password_changed')}: {out}", "green"))
except ChaosCryptError as exc:
self._print_error(exc)
def action_lang(self) -> None:
codes = list(LANG_NAMES.keys())
print()
for i, (code, name) in enumerate(LANG_NAMES.items(), 1):
mark = "*" if code == self.lang else " "
print(f" {c('[' + str(i) + ']', 'cyan')} {mark} {name} ({code})")
default_index = str(codes.index(self.lang) + 1) if self.lang in codes else "1"
choice = _ask("Language", default_index)
try:
idx = int(choice) - 1
if 0 <= idx < len(codes):
self.lang = codes[idx]
except ValueError:
if choice in codes:
self.lang = choice
print(c(f" -> {LANG_NAMES[self.lang]}", "green"))
def action_mode(self) -> None:
"""Switch the performance mode of the active core."""
print()
for i, name in enumerate(MODES, 1):
mark = "*" if name == self.mode else " "
desc = self._tr(f"mode_{name}_desc")
print(f" {c('[' + str(i) + ']', 'cyan')} {mark} {desc}")
default_index = str(MODES.index(self.mode) + 1)
choice = _ask(self._tr("mode_prompt"), default_index)
try:
idx = int(choice) - 1
if 0 <= idx < len(MODES):
self.mode = MODES[idx]
except ValueError:
if choice in MODES:
self.mode = choice
# Rebuild the core so the new mode takes effect, then reload the key
# if one was already loaded so the user does not have to re-enter the
# password.
was_loaded = self.cc.loaded
path = self.cc.key_file or self.key_file
pwd = self.key_password
self.cc = ChaosCrypt(mode=self.mode, encoding=self.encoding)
if was_loaded and path and pwd:
try:
self.cc.load(path, pwd)
except ChaosCryptError:
pass
print(c(f" -> {self._tr('mode_changed')} {self.mode}", "green"))
def action_encoding(self) -> None:
"""Switch the output encoding (turbo and raw only)."""
print()
for i, name in enumerate(ENCODINGS, 1):
mark = "*" if name == self.encoding else " "
desc = self._tr(f"encoding_{name}_desc")
print(f" {c('[' + str(i) + ']', 'cyan')} {mark} {desc}")
print(c(" " + self._tr("encoding_note"), "dim"))
default_index = str(ENCODINGS.index(self.encoding) + 1)
choice = _ask(self._tr("encoding_prompt"), default_index)
try:
idx = int(choice) - 1
if 0 <= idx < len(ENCODINGS):
self.encoding = ENCODINGS[idx]
except ValueError:
if choice in ENCODINGS:
self.encoding = choice
# Rebuild so the new encoding applies, then restore the loaded key.
was_loaded = self.cc.loaded
path = self.cc.key_file or self.key_file
pwd = self.key_password
self.cc = ChaosCrypt(mode=self.mode, encoding=self.encoding)
if was_loaded and path and pwd:
try:
self.cc.load(path, pwd)
except ChaosCryptError:
pass
print(c(f" -> {self._tr('encoding_changed')} {self.encoding}", "green"))
def action_about(self) -> None:
print()
print(c(self._tr("about_body"), "cyan"))
# ------------------------------------------------------------- main loop
def run(self) -> int:
while True:
self.banner()
try:
choice = self.menu()
except _Abort:
print()
print(c(self._tr("bye"), "green"))
return 0
try:
if choice == "1":
self.action_encrypt()
elif choice == "2":
self.action_decrypt()
elif choice == "3":
self.action_encrypt_file()
elif choice == "4":
self.action_decrypt_file()
elif choice == "5":
self.action_keygen()
elif choice == "6":
self.action_loadkey()
elif choice == "7":
self.action_keyinfo()
elif choice == "8":
self.action_chpwd()
elif choice == "9":
self.action_lang()
elif choice in ("m", "mode"):
self.action_mode()
elif choice in ("e", "encoding"):
self.action_encoding()
elif choice in ("a", "about"):
self.action_about()
elif choice in ("q", "quit", "exit"):
print()
print(c(self._tr("bye"), "green"))
return 0
else:
print(c(" " + self._tr("menu_invalid"), "yellow"))
continue
except _Abort:
print(c(" " + self._tr("cancelled"), "dim"))
continue
except KeyboardInterrupt:
print()
print(c(self._tr("bye"), "green"))
return 0
_pause(self.lang)
def run_tui(lang: str = DEFAULT_LANG,
key_file: str = DEFAULT_KEY_FILE) -> int:
"""Launch the interactive UI and return the process exit code."""
try:
return TUI(lang=lang, key_file=key_file).run()
except KeyboardInterrupt:
print()
return 0
if __name__ == "__main__": # pragma: no cover
sys.exit(run_tui())