From 2529edac1dd25a712abe811d624ae376829747a5 Mon Sep 17 00:00:00 2001 From: Dvs Date: Sun, 27 Sep 2026 17:03:05 +0800 Subject: [PATCH] v2.1.6: Restructure as a distributable library Restructure ChaosCrypt from a single-file script into a complete, installable Python package with three interfaces: a typed Python API, an argument-driven CLI, and a bilingual interactive TUI. The algorithm itself is unchanged. Ciphertexts and key files remain fully interoperable with the original implementation in both directions, which is enforced by dedicated tests rather than merely documented. Added - Library API: ChaosCrypt facade plus ChaosCryptCore for the raw algorithm - Unified error hierarchy: 16 named types, all ChaosCryptError subclasses, rendering as ChaosCrypt_ERR__ - CLI: keygen, encrypt, decrypt, file, info, chpwd, tui, with --json output, stdin/stdout piping, and three password sources per secret - Bilingual TUI: English default, runtime switch to Chinese, getpass password entry with a non-TTY fallback that keeps it scriptable - Binary and file support: encrypt_bytes/decrypt_bytes and encrypt_file/decrypt_file - Key management: change_key_password rewraps without altering key material; export_key_text/load_from_text move a key without touching disk - Documentation: SECURITY.md with the full design and threat analysis, plus docs/ covering the API, CLI, architecture and build process - Test suite: 92 tests across round-trips, binary safety, key management, error types, CLI, TUI, i18n and legacy interoperability - Packaging: pyproject.toml, setup.py compatibility shim, MANIFEST.in, py.typed, examples, MIT licence Fixed - Conflicting --pwd option between the -p and -P groups prevented the CLI from starting at all - Wrong key file password reported as file corruption (E002); structural validation now distinguishes it from a damaged file (E003) - export_key_text produced key material without loading it into the instance - Non-hexadecimal input was accepted as ciphertext and silently decrypted into garbage, making corruption indistinguishable from success; malformed input now raises E010 before any processing - TUI failed under piped input because getpass requires a TTY - TUI kept reading the default key file name after generating a new one Changed - Source tree reorganised: the package lives at chaoscrypt/, with tests, examples and legacy alongside it; documentation and build artefacts at the repository root - Code comments unified in English; public docstrings document parameters, return values and raised exceptions - English is now the default UI language - ChaosCryptChat removed from the repository - Attribution updated to Dvs (DvsXT); project URLs point to Gitea --- .gitignore | 64 +- CHANGELOG.md | 115 + ChaosCryptChat/qtmain.py | 4147 ----------------- ChaosCryptChat/server.py | 418 -- LICENSE | 41 + MANIFEST.in | 26 + README.md | 1237 ++--- SECURITY.md | 1166 ++--- chaoscrypt/__init__.py | 474 ++ chaoscrypt/__main__.py | 15 + chaoscrypt/_core.py | 740 +++ chaoscrypt/cli.py | 598 +++ chaoscrypt/errors.py | 145 + chaoscrypt/examples/basic_usage.py | 118 + chaoscrypt/i18n.py | 240 + chaoscrypt/legacy/README.md | 57 + .../legacy/chaoscrypt_legacy.py | 574 ++- chaoscrypt/py.typed | 0 chaoscrypt/tests/test_chaoscrypt.py | 603 +++ chaoscrypt/tests/test_legacy_interop.py | 84 + chaoscrypt/tests/test_tui.py | 139 + chaoscrypt/tui.py | 473 ++ docs/API.md | 463 ++ docs/ARCHITECTURE.md | 386 ++ docs/BUILDING.md | 356 ++ docs/CLI.md | 408 ++ docs/README.md | 34 + pyproject.toml | 116 + setup.py | 24 + 29 files changed, 6802 insertions(+), 6459 deletions(-) create mode 100644 CHANGELOG.md delete mode 100644 ChaosCryptChat/qtmain.py delete mode 100644 ChaosCryptChat/server.py create mode 100644 LICENSE create mode 100644 MANIFEST.in create mode 100644 chaoscrypt/__init__.py create mode 100644 chaoscrypt/__main__.py create mode 100644 chaoscrypt/_core.py create mode 100644 chaoscrypt/cli.py create mode 100644 chaoscrypt/errors.py create mode 100644 chaoscrypt/examples/basic_usage.py create mode 100644 chaoscrypt/i18n.py create mode 100644 chaoscrypt/legacy/README.md rename chaoscrypt.py => chaoscrypt/legacy/chaoscrypt_legacy.py (58%) create mode 100644 chaoscrypt/py.typed create mode 100644 chaoscrypt/tests/test_chaoscrypt.py create mode 100644 chaoscrypt/tests/test_legacy_interop.py create mode 100644 chaoscrypt/tests/test_tui.py create mode 100644 chaoscrypt/tui.py create mode 100644 docs/API.md create mode 100644 docs/ARCHITECTURE.md create mode 100644 docs/BUILDING.md create mode 100644 docs/CLI.md create mode 100644 docs/README.md create mode 100644 pyproject.toml create mode 100644 setup.py diff --git a/.gitignore b/.gitignore index c7baae9..965d81e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,20 +1,54 @@ -# 运行时数据(聊天记录/账户/服务器状态) -data/ -server_data/ -ChaosCryptChat/data/ -ChaosCryptChat/server_data/ - -# 密钥文件(严禁上传!) -*.key - -# Python 缓存 +# Byte-compiled / optimized / DLL files __pycache__/ -*.pyc +*.py[cod] +*$py.class -# 媒体缓存 -media/ +# Distribution / packaging +build/ +dist/ +*.egg-info/ +*.egg +.eggs/ +wheels/ -# 系统文件 -Thumbs.db +# Test / coverage +.pytest_cache/ +.coverage +.coverage.* +htmlcov/ +.tox/ +.nox/ +coverage.xml + +# Virtual environments +venv/ +.venv/ +env/ +ENV/ + +# Editors / IDEs +.idea/ +.vscode/ +*.swp +*.swo +*~ + +# OS .DS_Store +Thumbs.db desktop.ini + +# 🔐 密钥文件与密文 —— 绝不提交! +*.key +encryption.key +*.cc +!tests/**/*.key +!examples/**/*.key + +# 密码文件 +*.pwd +.pwd + +# 构建产物 +*.whl +*.tar.gz diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..3e5c39e --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,115 @@ +# Changelog + +All notable changes to this project are documented in this file. + +The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), +and this project adheres to [Semantic Versioning](https://semver.org/). + +--- + +## [2.1.6] — 2026-09-27 + +Packaging and documentation release. The algorithm is unchanged; this version +restructures the project as a distributable library and brings the +documentation in line with it. + +### Added + +- **Bilingual interactive TUI.** A menu-driven interface with English and + Chinese, switchable at runtime. Uses `getpass` for password entry on a + terminal and degrades to plain input when piped, so it remains scriptable. +- **Full command line interface.** Subcommands `keygen`, `encrypt`, `decrypt`, + `file`, `info`, `chpwd` and `tui`, with `--json` output, stdin/stdout + piping, and three ways to supply each password (inline, environment + variable, password file). +- **Unified error hierarchy.** Sixteen named error types, all subclasses of + `ChaosCryptError`, each rendering as `ChaosCrypt_ERR__`. Every + failure path in the library now raises rather than returning a sentinel. +- **Binary and file support.** `encrypt_bytes` / `decrypt_bytes` for arbitrary + binary data, and `encrypt_file` / `decrypt_file` for whole files. +- **Key management helpers.** `change_key_password` re-wraps a key file under + a new password without altering the key material. `export_key_text` and + `load_from_text` move a key without touching disk. +- **Comprehensive documentation.** `SECURITY.md` presents the design, key + space derivation, threat model and attack analysis in full. `docs/` + contains API, CLI and architecture references. +- **Test suite.** Round-trip integrity, binary safety, key management, error + types, CLI behaviour, TUI interaction, internationalisation, and + bidirectional interoperability with the original implementation. +- **Packaging.** `pyproject.toml`, `MANIFEST.in`, `.gitignore`, `py.typed`, + runnable examples, and MIT licensing. + +### Changed + +- **Project restructured** into a standard library layout. The importable + package now lives at `chaoscrypt/`, with tests, examples and the legacy + implementation alongside it, and documentation and build artefacts at the + repository root. +- **Code comments unified in English**, and public docstrings expanded to + document parameters, return values and raised errors. +- **English is now the default UI language**, with Chinese available as an + alternative. +- **Packaging metadata** updated for the new layout and SPDX licence + expression. + +### Fixed + +Six defects found and corrected during the restructure: + +1. The `-p` and `-P` option groups both registered `--pwd`, causing an + `argparse` conflict that prevented the CLI from starting at all. +2. An incorrect key file password was reported as a corrupted file (`E002`) + rather than a credential error (`E003`). A structural validation step now + distinguishes the two cases. +3. `export_key_text` produced key material without loading it into the + instance, so the returned key could not be used directly. +4. **Non-hexadecimal input was accepted as ciphertext and silently decrypted + into garbage.** This was the most serious defect: a corrupt or truncated + ciphertext was indistinguishable from a successful decryption. Malformed + input now raises `E010` before any processing occurs. +5. The TUI failed outright under piped input, because `getpass` requires a + TTY. It now detects this and falls back to plain input. +6. After generating a key file, the TUI continued to look at the default file + name rather than the one just created. The key file is now remembered for + the rest of the session. + +### Security + +- Clearly documented that ChaosCrypt is unaudited and non-standardised, and + that it is intended for obfuscation, personal use, and research or teaching + rather than production deployment. +- Documented the deterministic-output property and its consequences, and the + information disclosed by ciphertext length and Base64 padding class. +- Documented the strength of the construction in full, including the + approximately 10^5621 key space, the absence of algebraic and + number-theoretic structure, and the effect of Shor's and Grover's + algorithms. + +### Compatibility + +Fully backward compatible with the original single-file implementation, in +both directions: + +- key files produced by either implementation load in the other; +- ciphertext produced by either implementation decrypts in the other; +- the default key file name remains `encryption.key`, and the on-disk key + file format is unchanged. + +--- + +## [2.0.0] — Original release + +The original single-file implementation of the ChaosCrypt cipher. + +### Added + +- Random system key generation: independent uppercase and lowercase + bijections, digit and padding substitutions, a 10-bit case-flip pattern, a + 4096-nibble long key and a 512-nibble short key. +- Password-protected key file wrapping. +- Layered encryption: Base64 encoding, substitution, conditional case + flipping, whole-message reversal, and two XOR stages. +- Interactive menu for encryption, decryption and key management. + +[2.1.6]: https://git.dvscloud.net/dvs/ChaosCrypt/releases/tag/v2.1.6 +[2.0.0]: https://git.dvscloud.net/dvs/ChaosCrypt/releases/tag/v2.0.0 diff --git a/ChaosCryptChat/qtmain.py b/ChaosCryptChat/qtmain.py deleted file mode 100644 index 6fafea7..0000000 --- a/ChaosCryptChat/qtmain.py +++ /dev/null @@ -1,4147 +0,0 @@ -# -*- coding: utf-8 -*- -""" -🔐 混沌加密聊天 v6 - 单文件版 (PyQt5 客户端 + 全部后端) -============================================================ -· 后端: 混沌加密/每用户密钥认证/账户SQLite/历史SQLite/媒体持久存储 -· 界面: PyQt5 现代圆角UI, 自适应消息气泡 -· 两种群: 🔗端到端(P2P) + ☁️中央服务器(解决NAT) -· 中央服务器单独运行 server.py -运行: python dvs_enc.py -""" -import os -os.environ.setdefault('PYGAME_HIDE_SUPPORT_PROMPT', '1') -import io -import sys -import time -import queue -import wave -import json -import base64 -import struct -import socket -import hashlib -import hmac -import threading -import tempfile -import sqlite3 -import shutil -from datetime import datetime - -# ---------------- 路径 ---------------- -APP_DIR = os.path.dirname(os.path.abspath(__file__)) -DATA_DIR = os.path.join(APP_DIR, 'data') -try: - os.makedirs(DATA_DIR, exist_ok=True) -except Exception: - DATA_DIR = APP_DIR - -USERS_DB = os.path.join(DATA_DIR, 'users.db') -HISTORY_DB = os.path.join(DATA_DIR, 'chat_history.db') -SESSION_FILE = os.path.join(DATA_DIR, 'session.dat') -SERVER_DB = os.path.join(DATA_DIR, 'server_state.db') - -# 媒体持久目录: 文档/ChaosChat/media (用户可在 GUI 清理, 清理后数据消失) -MEDIA_DIR = os.path.join(os.path.expanduser('~'), 'Documents', 'ChaosChat', 'media') -try: - os.makedirs(MEDIA_DIR, exist_ok=True) -except Exception: - MEDIA_DIR = os.path.join(DATA_DIR, 'media') - try: - os.makedirs(MEDIA_DIR, exist_ok=True) - except Exception: - pass - -# ---------------- 可选依赖 ---------------- -try: - import tkinter as tk - from tkinter import scrolledtext, messagebox, simpledialog, filedialog - GUI_AVAILABLE = True -except Exception: - GUI_AVAILABLE = False - -try: - import pygame - PYGAME_AVAILABLE = True -except Exception: - PYGAME_AVAILABLE = False - -try: - from PIL import Image, ImageTk - PIL_AVAILABLE = True -except Exception: - PIL_AVAILABLE = False - -# 录音后端: 优先 sounddevice, 其次 pyaudio -RECORDER = None -try: - import sounddevice as sd - import numpy as np - RECORDER = 'sounddevice' -except Exception: - RECORDER = None -if RECORDER is None: - try: - import pyaudio - RECORDER = 'pyaudio' - except Exception: - RECORDER = None - -try: - import qrcode - QR_AVAILABLE = True -except Exception: - QR_AVAILABLE = False - - -# ==================== 混沌加密核心 ==================== -class ChaosCryptCore: - def __init__(self, debug=False): - self.debug = debug - self.special_encrypt = {'+': '.', '/': "'", '=': ''} - self.special_decrypt = {'.': '+', "'": '/'} - self.flip_pattern = [1, 1, 0, 0, 1, 0, 0, 0, 1, 0] - - def _generate_random_alphabet(self, lowercase=False): - chars = list("abcdefghijklmnopqrstuvwxyz" if lowercase else "ABCDEFGHIJKLMNOPQRSTUVWXYZ") - n = len(chars) - for i in range(n-1, 0, -1): - j = int.from_bytes(os.urandom(1), 'big') % (i+1) - chars[i], chars[j] = chars[j], chars[i] - return ''.join(chars) - - def _generate_random_digit_mapping(self): - digits = list("0123456789") - pool = list("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz") - n = len(pool) - for i in range(n-1, 0, -1): - j = int.from_bytes(os.urandom(1), 'big') % (i+1) - pool[i], pool[j] = pool[j], pool[i] - return {d: pool[i] for i, d in enumerate(digits)} - - def _generate_random_equal_mapping(self): - chars = list("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz") - n = len(chars) - for i in range(n-1, 0, -1): - j = int.from_bytes(os.urandom(1), 'big') % (i+1) - chars[i], chars[j] = chars[j], chars[i] - return {'0': chars[0], '1': chars[1], '2': chars[2], '3': chars[3]} - - def _generate_random_flip_pattern(self): - return [int.from_bytes(os.urandom(1), 'big') % 2 for _ in range(10)] - - def _generate_short_key(self, length=512): - chars = "0123456789abcdef" - return ''.join(chars[int.from_bytes(os.urandom(1), 'big') % 16] for _ in range(length)) - - def _build_maps(self, upper_mapping, lower_mapping, digit_mapping, equal_mapping): - upper_orig = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - lower_orig = "abcdefghijklmnopqrstuvwxyz" - enc = {} - dec = {} - for i in range(26): - enc[upper_orig[i]] = upper_mapping[i] - enc[lower_orig[i]] = lower_mapping[i] - dec[upper_mapping[i]] = upper_orig[i] - dec[lower_mapping[i]] = lower_orig[i] - digit_rev = {v: k for k, v in digit_mapping.items()} - equal_rev = {v: k for k, v in equal_mapping.items()} - return enc, dec, digit_rev, equal_rev - - def _ensure_printable(self, text): - res = [] - for c in text: - v = ord(c) - if v == 124: - res.append('|') - elif v < 32 or v > 126: - v = v % 95 + 32 - res.append(chr(v)) - else: - res.append(c) - return ''.join(res) - - def _mix_keys(self, user_password, short_key, target_length): - mixed = [] - max_len = max(len(user_password), len(short_key)) - for i in range(max_len): - if i < len(user_password): - mixed.append(ord(user_password[i])) - if i < len(short_key): - mixed.append(ord(short_key[i])) - for i in range(len(mixed)): - if i % 3 == 0: - mixed[i] = (mixed[i] << 1) & 0xFF - elif i % 3 == 1: - mixed[i] = (mixed[i] >> 1) & 0xFF - else: - mixed[i] = mixed[i] ^ 0x5A - for i in range(0, len(mixed)-3, 4): - mixed[i], mixed[i+3] = mixed[i+3], mixed[i] - mixed[i+1], mixed[i+2] = mixed[i+2], mixed[i+1] - mixed.reverse() - res = [] - for x in mixed: - if x < 32 or x > 126: - x = x % 95 + 32 - res.append(chr(x)) - res_str = ''.join(res) - if len(res_str) < target_length: - base = res_str - final = base - it = 0 - while len(final) < target_length: - if it % 3 == 0: - chunk = base[::-1] - elif it % 3 == 1: - chunk = base[::-1] - chunk = ''.join([chr((ord(c) + it) % 95 + 32) for c in chunk]) - else: - chunk = base[::-1] - chunk = ''.join([chr((ord(c) ^ it) % 95 + 32) for c in chunk]) - final += chunk - it += 1 - res_str = final[:target_length] - return self._ensure_printable(res_str) - - def _derive_final_key(self, user_password, short_key, text_length): - mixed = self._mix_keys(user_password, short_key, text_length * 2) - hex_key = ''.join([f"{ord(c):02x}" for c in mixed]) - rev_hex = hex_key[::-1] - final = [] - for i in range(0, len(rev_hex), 2): - if i+1 < len(rev_hex): - byte = rev_hex[i:i+2] - try: - val = int(byte, 16) - if val < 32 or val > 126: - val = val % 95 + 32 - final.append(chr(val)) - except Exception: - final.append('x') - final_str = ''.join(final) - if len(final_str) < text_length: - base = final_str - it = 0 - while len(final_str) < text_length: - if it % 3 == 0: - chunk = base[::-1] - elif it % 3 == 1: - chunk = base[::-1] - chunk = ''.join([chr((ord(c) + it) % 95 + 32) for c in chunk]) - else: - chunk = base[::-1] - chunk = ''.join([chr((ord(c) ^ it) % 95 + 32) for c in chunk]) - final_str += chunk - it += 1 - final_str = final_str[:text_length] - return self._ensure_printable(final_str) - - def _apply_flip(self, text, flip_pattern): - res = [] - for i, ch in enumerate(text): - idx = i % len(flip_pattern) - if ch.isalpha() and flip_pattern[idx] == 1: - res.append(ch.swapcase()) - else: - res.append(ch) - return ''.join(res) - - def _xor_encrypt_to_hex(self, text, key): - key_len = len(key) - res = [] - for i, ch in enumerate(text): - res.append(f"{ord(ch) ^ ord(key[i % key_len]):02x}") - return ''.join(res) - - def _xor_decrypt_to_string(self, hex_text, key): - try: - key_len = len(key) - res = [] - for i in range(0, len(hex_text), 2): - if i+1 < len(hex_text): - byte = hex_text[i:i+2] - val = int(byte, 16) ^ ord(key[(i//2) % key_len]) - if val < 32 or val > 126: - val = val % 95 + 32 - res.append(chr(val)) - return ''.join(res) - except Exception: - return None - - def _substitute_letters(self, text, enc_map): - return ''.join([enc_map.get(c, c) for c in text]) - - def _inverse_substitute(self, text, dec_map): - return ''.join([dec_map.get(c, c) for c in text]) - - def encrypt(self, plaintext, session_key, params): - b64 = base64.b64encode(plaintext.encode('utf-8')).decode('ascii') - processed = b64 - for old, new in self.special_encrypt.items(): - processed = processed.replace(old, new) - processed = processed.rstrip('=') - enc_map, _, _, _ = self._build_maps( - params['upper_mapping'], - params['lower_mapping'], - params['digit_mapping'], - params['equal_mapping'] - ) - sub = self._substitute_letters(processed, enc_map) - flipped = self._apply_flip(sub, params['flip_pattern']) - rev = flipped[::-1] - eq_count = b64.count('=') - eq_char = params['equal_mapping'][str(eq_count)] - with_equal = f"{rev}|{eq_char}" - final_key = self._derive_final_key( - session_key[:16], - params['short_key_fragment'], - len(with_equal) - ) - return self._xor_encrypt_to_hex(with_equal, final_key) - - def decrypt(self, ciphertext, session_key, params): - try: - final_key = self._derive_final_key( - session_key[:16], - params['short_key_fragment'], - len(ciphertext) // 2 - ) - decrypted = self._xor_decrypt_to_string(ciphertext, final_key) - if decrypted is None: - return None - if '|' in decrypted: - main, eq_char = decrypted.split('|') - eq_rev = {v: k for k, v in params['equal_mapping'].items()} - eq_count = int(eq_rev.get(eq_char, '0')) - else: - main = decrypted - eq_count = 0 - rev = main[::-1] - flipped = self._apply_flip(rev, params['flip_pattern']) - _, dec_map, _, _ = self._build_maps( - params['upper_mapping'], - params['lower_mapping'], - params['digit_mapping'], - params['equal_mapping'] - ) - sub = self._inverse_substitute(flipped, dec_map) - for old, new in self.special_decrypt.items(): - sub = sub.replace(old, new) - b64_str = sub + '=' * eq_count - return base64.b64decode(b64_str.encode('ascii')).decode('utf-8') - except Exception: - return None - - -# ==================== 会话密钥 (共享加密) ==================== -class SecureSession: - """基于 ChaosCryptCore 的共享会话加密 (群聊同密钥)""" - - def __init__(self): - self.core = ChaosCryptCore() - self.session_key = None - self.params = None - - def generate(self): - self.session_key = os.urandom(32).hex() - self.params = { - 'upper_mapping': self.core._generate_random_alphabet(False), - 'lower_mapping': self.core._generate_random_alphabet(True), - 'digit_mapping': self.core._generate_random_digit_mapping(), - 'equal_mapping': self.core._generate_random_equal_mapping(), - 'flip_pattern': self.core._generate_random_flip_pattern(), - 'short_key_fragment': self.core._generate_short_key(32), - 'generated_at': datetime.now().isoformat() - } - return self.session_key - - def export_key(self): - data = json.dumps({'session_key': self.session_key, 'params': self.params}, ensure_ascii=False) - return base64.urlsafe_b64encode(data.encode('utf-8')).decode('ascii') - - def import_key(self, key_str): - try: - raw = base64.urlsafe_b64decode(key_str.encode('ascii')) - data = json.loads(raw.decode('utf-8')) - self.session_key = data['session_key'] - self.params = data['params'] - return True - except Exception: - return False - - def has_key(self): - return self.session_key is not None and self.params is not None - - def encrypt(self, plaintext): - if not self.has_key(): - raise ValueError("会话密钥未建立") - nonce = os.urandom(16).hex() - msg_key = hashlib.sha256((self.session_key + nonce).encode('utf-8')).hexdigest() - cipher = self.core.encrypt(plaintext, msg_key, self.params) - hmac = hashlib.sha256((cipher + self.session_key).encode('utf-8')).hexdigest()[:16] - return json.dumps({ - 'nonce': nonce, 'ciphertext': cipher, 'hmac': hmac, 'ts': int(time.time()) - }, ensure_ascii=False) - - def decrypt(self, packet_json): - try: - pkt = json.loads(packet_json) - hmac_calc = hashlib.sha256((pkt['ciphertext'] + self.session_key).encode('utf-8')).hexdigest()[:16] - if hmac_calc != pkt['hmac']: - return None - msg_key = hashlib.sha256((self.session_key + pkt['nonce']).encode('utf-8')).hexdigest() - return self.core.decrypt(pkt['ciphertext'], msg_key, self.params) - except Exception: - return None - - # ---- 二进制数据加密 (文件/图片/语音) ---- - def _keystream(self, nonce, length): - return hashlib.shake_256((self.session_key + nonce).encode('utf-8')).digest(length) - - @staticmethod - def _fast_xor(a, b, chunk=1 << 20): - out = bytearray() - n = len(a) - for i in range(0, n, chunk): - size = min(chunk, n - i) - x = int.from_bytes(a[i:i+size], 'big') ^ int.from_bytes(b[i:i+size], 'big') - out += x.to_bytes(size, 'big') - return bytes(out) - - def encrypt_bytes(self, data): - if not self.has_key(): - raise ValueError("会话密钥未建立") - nonce = os.urandom(16).hex() - ks = self._keystream(nonce, len(data)) - cipher = self._fast_xor(data, ks) - hmac = hashlib.sha256( - b'BIN|' + self.session_key.encode('utf-8') + b'|' + - nonce.encode('utf-8') + b'|' + cipher).hexdigest() - return json.dumps({'alg': 'xor', 'nonce': nonce, - 'data': base64.b64encode(cipher).decode('ascii'), - 'hmac': hmac}, ensure_ascii=False) - - def decrypt_bytes(self, packet): - try: - pkt = json.loads(packet) - nonce = pkt['nonce'] - cipher = base64.b64decode(pkt['data']) - hmac_calc = hashlib.sha256( - b'BIN|' + self.session_key.encode('utf-8') + b'|' + - nonce.encode('utf-8') + b'|' + cipher).hexdigest() - if hmac_calc != pkt['hmac']: - return None - ks = self._keystream(nonce, len(cipher)) - return self._fast_xor(cipher, ks) - except Exception: - return None - - def auth_secret(self): - """从会话密钥派生的群认证密钥 (证明是群成员)""" - return hashlib.sha256(b'CHAOS_AUTH|' + self.session_key.encode('utf-8')).hexdigest() - - def user_key_enc(self): - """用于加密下发每用户密钥的密钥 (客户端/服务器各自计算一致)""" - return hashlib.sha256(b'CHAOS_USERKEY_ENC|' + self.session_key.encode('utf-8')).hexdigest() - - -# ==================== 传输协议 (帧封装) ==================== -MAX_FRAME = 256 * 1024 * 1024 - -def send_msg(sock, obj): - payload = json.dumps(obj, ensure_ascii=False).encode('utf-8') - sock.sendall(struct.pack('>I', len(payload)) + payload) - - -def recv_exact(sock, n): - data = b'' - while len(data) < n: - try: - chunk = sock.recv(n - len(data)) - except socket.timeout: - continue - except Exception: - return None - if not chunk: - return None - data += chunk - return data - - -def recv_msg(sock): - header = recv_exact(sock, 4) - if header is None: - return None - length = struct.unpack('>I', header)[0] - if length <= 0 or length > MAX_FRAME: - return None - payload = recv_exact(sock, length) - if payload is None: - return None - try: - return json.loads(payload.decode('utf-8')) - except Exception: - return None - - -# ==================== 通用工具 ==================== -def stream_xor(data, key_bytes): - """shake256 密钥流异或 (用于加密下发每用户密钥)""" - ks = hashlib.shake_256(key_bytes).digest(len(data)) - out = bytearray() - n = len(data) - chunk = 1 << 20 - for i in range(0, n, chunk): - size = min(chunk, n - i) - x = int.from_bytes(data[i:i+size], 'big') ^ int.from_bytes(ks[i:i+size], 'big') - out += x.to_bytes(size, 'big') - return bytes(out) - - -def gen_mid(): - return f"{int(time.time()*1000)}-{os.urandom(4).hex()}" - - -def fmt_time(ts): - return datetime.fromtimestamp(ts).strftime('%H:%M:%S') - - -# ==================== 文件类型识别 ==================== -FILE_ICONS = { - 'image': '🖼️', 'audio': '🎵', 'video': '🎬', - 'archive': '📦', 'exe': '🛠️', 'lnk': '🔗', 'link': '🔗', - 'doc': '📝', 'sheet': '📊', 'slide': '📽️', 'pdf': '📃', - 'code': '💻', 'text': '📄', 'default': '📄', -} - - -def file_icon(ext): - """按扩展名返回可识别图标""" - e = (ext or '').lower().lstrip('.') - if e in ('png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp', 'ico'): - return FILE_ICONS['image'] - if e in ('wav', 'mp3', 'ogg', 'flac', 'aac', 'm4a'): - return FILE_ICONS['audio'] - if e in ('mp4', 'avi', 'mkv', 'mov', 'wmv', 'flv'): - return FILE_ICONS['video'] - if e in ('zip', 'rar', '7z', 'tar', 'gz', 'bz2'): - return FILE_ICONS['archive'] - if e in ('exe', 'msi', 'bat', 'cmd'): - return FILE_ICONS['exe'] - if e == 'lnk': - return FILE_ICONS['lnk'] - if e in ('doc', 'docx', 'rtf', 'odt'): - return FILE_ICONS['doc'] - if e in ('xls', 'xlsx', 'csv', 'ods'): - return FILE_ICONS['sheet'] - if e in ('ppt', 'pptx', 'odp'): - return FILE_ICONS['slide'] - if e == 'pdf': - return FILE_ICONS['pdf'] - if e in ('py', 'js', 'html', 'css', 'c', 'cpp', 'java', 'go', 'rs', 'json', 'xml'): - return FILE_ICONS['code'] - if e in ('txt', 'md', 'log'): - return FILE_ICONS['text'] - return FILE_ICONS['default'] - - -# ==================== 媒体持久存储 ==================== -def save_media(data, ext='.bin'): - """保存媒体文件到 文档/ChaosChat/media, 返回绝对路径""" - fname = f"{int(time.time()*1000)}-{os.urandom(4).hex()}{ext}" - path = os.path.join(MEDIA_DIR, fname) - try: - with open(path, 'wb') as f: - f.write(data) - return path - except Exception: - return '' - - -def delete_media(path): - try: - if path and os.path.exists(path): - os.remove(path) - except Exception: - pass - - -def clear_media_cache(): - """清空媒体缓存目录 (数据不可恢复)""" - if not os.path.isdir(MEDIA_DIR): - return 0 - count = 0 - for name in os.listdir(MEDIA_DIR): - p = os.path.join(MEDIA_DIR, name) - try: - if os.path.isfile(p): - os.remove(p) - count += 1 - except Exception: - pass - return count - - -# ==================== 账户数据库 (SQLite) ==================== -class AccountDB: - """账户 + 会话 + 已保存群""" - - def __init__(self, db_path=USERS_DB): - self.path = db_path - self.conn = sqlite3.connect(db_path, check_same_thread=False) - self.conn.row_factory = sqlite3.Row - self.lock = threading.Lock() - self._init() - - def _init(self): - with self.lock: - cur = self.conn.cursor() - cur.execute('''CREATE TABLE IF NOT EXISTS accounts( - id INTEGER PRIMARY KEY AUTOINCREMENT, - username TEXT UNIQUE NOT NULL, - nickname TEXT, - salt TEXT NOT NULL, - pass_hash TEXT NOT NULL, - created_at REAL)''') - cur.execute('''CREATE TABLE IF NOT EXISTS sessions( - id INTEGER PRIMARY KEY AUTOINCREMENT, - account_id INTEGER NOT NULL, - token TEXT UNIQUE NOT NULL, - history_key TEXT, - created_at REAL)''') - scols = [r[1] for r in cur.execute('PRAGMA table_info(sessions)').fetchall()] - if 'history_key' not in scols: - cur.execute('ALTER TABLE sessions ADD COLUMN history_key TEXT') - cur.execute('''CREATE TABLE IF NOT EXISTS saved_groups( - id INTEGER PRIMARY KEY AUTOINCREMENT, - account_id INTEGER NOT NULL, - group_key TEXT NOT NULL, - host TEXT, port INTEGER, - session_key TEXT, - nickname TEXT, - is_host INTEGER DEFAULT 0, - user_key TEXT, - UNIQUE(account_id, group_key))''') - cols = [r[1] for r in cur.execute('PRAGMA table_info(saved_groups)').fetchall()] - if 'user_key' not in cols: - cur.execute('ALTER TABLE saved_groups ADD COLUMN user_key TEXT') - self.conn.commit() - - # ---- 密码哈希 (PBKDF2) ---- - @staticmethod - def hash_password(password, salt_hex): - salt = bytes.fromhex(salt_hex) - return hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), salt, 120000).hex() - - def register(self, username, password): - salt = os.urandom(16).hex() - ph = self.hash_password(password, salt) - try: - with self.lock: - cur = self.conn.cursor() - cur.execute('INSERT INTO accounts(username, nickname, salt, pass_hash, created_at) VALUES(?,?,?,?,?)', - (username, username, salt, ph, time.time())) - self.conn.commit() - return True, 'ok' - except sqlite3.IntegrityError: - return False, '该用户名已被注册' - - def login(self, username, password): - with self.lock: - cur = self.conn.cursor() - row = cur.execute('SELECT * FROM accounts WHERE username=?', (username,)).fetchone() - if row is None: - return None, '用户不存在' - ph = self.hash_password(password, row['salt']) - if ph != row['pass_hash']: - return None, '密码错误' - return row, 'ok' - - def create_session(self, account_id): - token = os.urandom(32).hex() - with self.lock: - cur = self.conn.cursor() - cur.execute('DELETE FROM sessions WHERE account_id=?', (account_id,)) - cur.execute('INSERT INTO sessions(account_id, token, created_at) VALUES(?,?,?)', - (account_id, token, time.time())) - self.conn.commit() - return token - - def validate_session(self, token): - with self.lock: - cur = self.conn.cursor() - row = cur.execute('''SELECT a.* FROM sessions s - JOIN accounts a ON a.id = s.account_id - WHERE s.token=?''', (token,)).fetchone() - return row - - def update_nickname(self, account_id, nickname): - with self.lock: - cur = self.conn.cursor() - cur.execute('UPDATE accounts SET nickname=? WHERE id=?', (nickname, account_id)) - self.conn.commit() - - # ---- 已保存的群 ---- - def save_group(self, account_id, group_key, host, port, session_key, nickname, is_host, user_key=''): - with self.lock: - cur = self.conn.cursor() - cur.execute('''INSERT INTO saved_groups(account_id, group_key, host, port, session_key, nickname, is_host, user_key) - VALUES(?,?,?,?,?,?,?,?) - ON CONFLICT(account_id, group_key) DO UPDATE SET - host=excluded.host, port=excluded.port, session_key=excluded.session_key, - nickname=excluded.nickname, is_host=excluded.is_host, - user_key=excluded.user_key''', - (account_id, group_key, host, port, session_key, nickname, - 1 if is_host else 0, user_key or '')) - self.conn.commit() - - def load_groups(self, account_id): - with self.lock: - cur = self.conn.cursor() - return cur.execute('SELECT * FROM saved_groups WHERE account_id=?', (account_id,)).fetchall() - - def remove_group(self, account_id, group_key): - with self.lock: - cur = self.conn.cursor() - cur.execute('DELETE FROM saved_groups WHERE account_id=? AND group_key=?', (account_id, group_key)) - self.conn.commit() - - -# ==================== 历史记录数据库 (SQLite) ==================== -class HistoryDB: - """群聊记录: 文本存内容, 文件/语音只存路径""" - - def __init__(self, db_path=HISTORY_DB): - self.conn = sqlite3.connect(db_path, check_same_thread=False) - self.conn.row_factory = sqlite3.Row - self.lock = threading.Lock() - self._init() - - def _init(self): - with self.lock: - cur = self.conn.cursor() - cur.execute('''CREATE TABLE IF NOT EXISTS messages( - id INTEGER PRIMARY KEY AUTOINCREMENT, - account_id INTEGER NOT NULL, - group_key TEXT NOT NULL, - mid TEXT, - sender TEXT, - mtype TEXT, - content TEXT, - ts REAL, - is_mine INTEGER DEFAULT 0, - withdrawn INTEGER DEFAULT 0)''') - cur.execute('CREATE INDEX IF NOT EXISTS idx_msg ON messages(account_id, group_key, id)') - self.conn.commit() - - @staticmethod - def serialize_content(msg): - if msg.type in ('text', 'system'): - return str(msg.content) - if isinstance(msg.content, dict): - d = dict(msg.content) - d.pop('raw', None) # 不入库: 数据存文档目录, 库中只记路径 - return json.dumps(d, ensure_ascii=False) - return str(msg.content) - - @staticmethod - def deserialize_content(mtype, content): - if mtype in ('text', 'system'): - return content - try: - return json.loads(content) - except Exception: - return content - - def save(self, account_id, group_key, msg): - with self.lock: - cur = self.conn.cursor() - cur.execute('''INSERT INTO messages(account_id, group_key, mid, sender, mtype, content, ts, is_mine, withdrawn) - VALUES(?,?,?,?,?,?,?,?,?)''', - (account_id, group_key, msg.mid, msg.sender, msg.type, - self.serialize_content(msg), msg.timestamp, - 1 if msg.is_mine else 0, 1 if msg.withdrawn else 0)) - self.conn.commit() - - def load(self, account_id, group_key, limit=500): - with self.lock: - cur = self.conn.cursor() - return cur.execute('''SELECT * FROM ( - SELECT * FROM messages - WHERE account_id=? AND group_key=? - ORDER BY id DESC LIMIT ?) - ORDER BY id ASC''', - (account_id, group_key, limit)).fetchall() - - def delete_by_mid(self, account_id, group_key, mid): - with self.lock: - cur = self.conn.cursor() - cur.execute('DELETE FROM messages WHERE account_id=? AND group_key=? AND mid=?', - (account_id, group_key, mid)) - self.conn.commit() - - def clear_group(self, account_id, group_key): - with self.lock: - cur = self.conn.cursor() - cur.execute('DELETE FROM messages WHERE account_id=? AND group_key=?', (account_id, group_key)) - self.conn.commit() - - -# ==================== 语音管理 ==================== -class VoiceManager: - def __init__(self, on_status=None): - self.on_status = on_status - self.rate = 44100 - self.channels = 1 - self.recording = False - self._thread = None - self._frames = [] - self._result = None - self.last_voice = None - self.last_voice_from = '' - - def _status(self, text): - if self.on_status: - try: - self.on_status(text) - except Exception: - pass - - def _make_wav(self, pcm_bytes): - buf = io.BytesIO() - with wave.open(buf, 'wb') as wf: - wf.setnchannels(self.channels) - wf.setsampwidth(2) - wf.setframerate(self.rate) - wf.writeframes(pcm_bytes) - return buf.getvalue() - - def _record_worker(self): - self._result = None - try: - if RECORDER == 'sounddevice': - self._frames = [] - - def callback(indata, frames, time_info, status): - if self.recording: - self._frames.append(indata.copy()) - - with sd.InputStream(samplerate=self.rate, channels=1, - callback=callback, dtype='float32'): - while self.recording: - time.sleep(0.05) - if self._frames: - audio = np.concatenate(self._frames, axis=0) - pcm = (np.clip(audio, -1.0, 1.0) * 32767).astype(np.int16).tobytes() - self._result = self._make_wav(pcm) - elif RECORDER == 'pyaudio': - p = pyaudio.PyAudio() - stream = p.open(format=pyaudio.paInt16, channels=1, rate=self.rate, - input=True, frames_per_buffer=1024) - frames = [] - while self.recording: - data = stream.read(1024, exception_on_overflow=False) - frames.append(data) - stream.stop_stream() - stream.close() - p.terminate() - if frames: - self._result = self._make_wav(b''.join(frames)) - if self._result: - self._status(f"✅ 录音完成 ({len(self._result) // 1024} KB)") - except Exception as e: - self._result = None - self._status(f"❌ 录音失败: {e}") - - def start_recording(self): - if RECORDER is None: - self._status("⚠️ 请安装 sounddevice 或 pyaudio 才能录音") - return False - if self.recording: - return False - self.recording = True - self._thread = threading.Thread(target=self._record_worker, daemon=True) - self._thread.start() - self._status("🎤 录音中... 再点一次停止并发送") - return True - - def stop_recording(self): - if not self.recording: - return None - self.recording = False - if self._thread: - self._thread.join(timeout=10) - result = self._result - self._result = None - if result: - self.last_voice = result - self.last_voice_from = '' - return result - - def play(self, wav_bytes, from_user=''): - if not wav_bytes: - return False - if not PYGAME_AVAILABLE: - self._status("⚠️ 未安装 pygame,无法播放语音") - return False - try: - if not pygame.mixer.get_init(): - pygame.mixer.init(frequency=self.rate, size=-16, channels=self.channels) - fd, path = tempfile.mkstemp(suffix='.wav') - with os.fdopen(fd, 'wb') as f: - f.write(wav_bytes) - sound = pygame.mixer.Sound(path) - sound.play() - - def _cleanup(): - for _ in range(300): - if not pygame.mixer.get_busy(): - break - time.sleep(0.1) - try: - os.remove(path) - except Exception: - pass - - threading.Thread(target=_cleanup, daemon=True).start() - self.last_voice = wav_bytes - self.last_voice_from = from_user - if from_user: - self._status(f"🔊 播放来自 {from_user} 的语音") - return True - except Exception as e: - self._status(f"❌ 播放失败: {e}") - return False - - -# ==================== 消息模型 ==================== -class Message: - def __init__(self, mid, group, sender, msg_type, content, timestamp, is_mine=False): - self.mid = mid - self.group = group - self.sender = sender - self.type = msg_type # text / image / voice / audio / file / system - self.content = content # 文本 str, 或 {'filename','size','path','ext'} - self.timestamp = timestamp - self.is_mine = is_mine - self.read = False - self.withdrawn = False - - def is_withdrawable(self, now=None): - now = now or time.time() - return self.is_mine and not self.withdrawn and (now - self.timestamp) <= 120 - - def get_data_bytes(self): - """返回文件/图片/语音的原始字节 (从磁盘路径读取)""" - if isinstance(self.content, dict): - p = self.content.get('path') - if p and os.path.isfile(p): - try: - with open(p, 'rb') as f: - return f.read() - except Exception: - return b'' - return b'' - - - -# ==================== 服务器状态数据库 (踢人标记/群名/公告) ==================== -class ServerDB: - """服务器级持久状态: 被踢账户 + 群名 + 公告 (重启不丢)""" - - def __init__(self, db_path=SERVER_DB): - self.conn = sqlite3.connect(db_path, check_same_thread=False) - self.conn.row_factory = sqlite3.Row - self.lock = threading.Lock() - self._init() - - def _init(self): - with self.lock: - cur = self.conn.cursor() - cur.execute("""CREATE TABLE IF NOT EXISTS kicked( - server_key TEXT NOT NULL, - account TEXT NOT NULL, - kicked_at REAL, - PRIMARY KEY(server_key, account))""") - cur.execute("""CREATE TABLE IF NOT EXISTS server_info( - server_key TEXT PRIMARY KEY, - group_name TEXT, - announcement TEXT)""") - cur.execute("""CREATE TABLE IF NOT EXISTS user_keys( - server_key TEXT NOT NULL, - account TEXT NOT NULL, - user_key TEXT, - PRIMARY KEY(server_key, account))""") - self.conn.commit() - - def is_kicked(self, server_key, account): - with self.lock: - cur = self.conn.cursor() - row = cur.execute('SELECT 1 FROM kicked WHERE server_key=? AND account=?', - (server_key, account)).fetchone() - return row is not None - - def add_kicked(self, server_key, account): - with self.lock: - cur = self.conn.cursor() - cur.execute('INSERT OR REPLACE INTO kicked(server_key, account, kicked_at) VALUES(?,?,?)', - (server_key, account, time.time())) - self.conn.commit() - - def remove_kicked(self, server_key, account): - with self.lock: - cur = self.conn.cursor() - cur.execute('DELETE FROM kicked WHERE server_key=? AND account=?', (server_key, account)) - self.conn.commit() - - # ---- 每用户密钥 (身份认证) ---- - def get_user_key(self, server_key, account): - with self.lock: - cur = self.conn.cursor() - row = cur.execute('SELECT user_key FROM user_keys WHERE server_key=? AND account=?', - (server_key, account)).fetchone() - return row['user_key'] if row else None - - def set_user_key(self, server_key, account, user_key): - with self.lock: - cur = self.conn.cursor() - cur.execute('INSERT OR REPLACE INTO user_keys(server_key, account, user_key) VALUES(?,?,?)', - (server_key, account, user_key)) - self.conn.commit() - - def get_info(self, server_key): - with self.lock: - cur = self.conn.cursor() - row = cur.execute('SELECT * FROM server_info WHERE server_key=?', (server_key,)).fetchone() - if row: - return row['group_name'] or '', row['announcement'] or '' - return '', '' - - def save_info(self, server_key, group_name, announcement): - with self.lock: - cur = self.conn.cursor() - cur.execute("""INSERT INTO server_info(server_key, group_name, announcement) VALUES(?,?,?) - ON CONFLICT(server_key) DO UPDATE SET - group_name=excluded.group_name, announcement=excluded.announcement""", - (server_key, group_name or '', announcement or '')) - self.conn.commit() - - -# ==================== 多用户服务器 v5 ==================== -class ChatServer: - """多用户聊天服务器: 群主管理(踢人/群名/公告) + 消息广播""" - - def __init__(self, on_status=None, server_key='default', server_db=None, - auth_secret=None, server_secret=None): - self.sock = None - self.running = False - self.clients = {} # cid -> {socket, nickname, account, addr, lock, is_host, pending, user_key} - self.next_id = 1 - self.lock = threading.Lock() - self.on_status = on_status - self.host = '0.0.0.0' - self.port = 8888 - self.host_cid = None # 第一个加入的客户端 = 群主 - self.announcement = '' - self.group_name = '' - self.server_key = server_key - self.server_db = server_db - self.auth_secret = auth_secret - self.user_key_enc = None - if server_secret: - self.auth_secret = hashlib.sha256( - b'CHAOS_AUTH|' + server_secret.encode('utf-8')).hexdigest() - self.user_key_enc = hashlib.sha256( - b'CHAOS_USERKEY_ENC|' + server_secret.encode('utf-8')).hexdigest() - self.mid_owner = {} # mid -> (account, ts) 消息归属, 用于撤回校验 - - def _status(self, text): - if self.on_status: - try: - self.on_status(text) - except Exception: - pass - - def start(self, port=8888): - try: - if self.server_db: - gn, an = self.server_db.get_info(self.server_key) - self.group_name = gn or '' - self.announcement = an or '' - self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - self.sock.bind((self.host, port)) - self.sock.listen(10) - self.running = True - self.port = port - threading.Thread(target=self._accept_loop, daemon=True).start() - self._status(f"🔄 服务器已启动,端口 {port},等待连接...") - return True - except Exception as e: - self._status(f"❌ 服务器启动失败: {e}") - return False - - def stop(self): - self.running = False - if self.sock: - try: - self.sock.close() - except Exception: - pass - self.sock = None - with self.lock: - socks = [c['socket'] for c in self.clients.values()] - self.clients.clear() - for s in socks: - try: - s.close() - except Exception: - pass - - def _accept_loop(self): - while self.running: - try: - client, addr = self.sock.accept() - with self.lock: - cid = self.next_id - self.next_id += 1 - self.clients[cid] = { - 'socket': client, - 'nickname': f'用户{cid}', - 'account': '', - 'addr': addr, - 'lock': threading.Lock(), - 'is_host': False - } - self._status(f"✅ 新连接: {addr[0]}:{addr[1]}") - threading.Thread(target=self._client_handler, args=(cid,), daemon=True).start() - except Exception: - break - - def _client_handler(self, cid): - client = self.clients[cid]['socket'] - - # 第一步: join (含账户 + 昵称) - try: - msg = recv_msg(client) - if msg and msg.get('type') == 'join': - account = str(msg.get('account', f'用户{cid}'))[:24] - nickname = str(msg.get('nickname') or msg.get('username') or account)[:20] - with self.lock: - if cid in self.clients: - c = self.clients[cid] - c['account'] = account - c['nickname'] = nickname - if self.host_cid is None: - self.host_cid = cid - c['is_host'] = True - # 加入认证 ①: 必须持有群密钥 (证明是群成员) - if self.auth_secret: - expect = hmac.new(self.auth_secret.encode('utf-8'), - account.encode('utf-8'), hashlib.sha256).hexdigest() - if msg.get('auth') != expect: - self._status(f"⚠️ 拒绝未认证的加入请求: {account}") - self._remove_client(cid) - return - # 加入认证 ②: 每用户密钥 (防止成员冒充他人) - user_key = None - if self.server_db: - user_key = self.server_db.get_user_key(self.server_key, account) - if user_key: - expect2 = hmac.new(user_key.encode('utf-8'), - ('JOIN:' + account).encode('utf-8'), - hashlib.sha256).hexdigest() - if msg.get('user_auth') != expect2: - self._status(f"⚠️ 拒绝身份认证失败(冒充): {account}") - self._remove_client(cid) - return - else: - # 新账户: 签发本人密钥并加密下发 - if self.user_key_enc: - user_key = os.urandom(16).hex() - if self.server_db: - self.server_db.set_user_key(self.server_key, account, user_key) - enc = base64.b64encode( - stream_xor(user_key.encode('utf-8'), - bytes.fromhex(self.user_key_enc))).decode('ascii') - self._send_to(cid, {'type': 'user_key_issued', 'data': enc}) - if user_key: - with self.lock: - if cid in self.clients: - self.clients[cid]['user_key'] = user_key - # 被踢过的账户: 需群主同意 - if self.server_db and self.server_db.is_kicked(self.server_key, account): - with self.lock: - if cid in self.clients: - self.clients[cid]['pending'] = True - self._status(f"⏳ {nickname} 曾被移出, 等待群主同意") - self._send_to(cid, {'type': 'need_approval', - 'reason': '你曾被移出本群,需群主同意后才能加入'}) - if self.host_cid is not None: - self._send_to(self.host_cid, {'type': 'approval_request', - 'account': account, 'nickname': nickname}) - if not self._wait_approval(cid): - self._remove_client(cid) - return - with self.lock: - if cid in self.clients: - self.clients[cid]['pending'] = False - self._send_to(cid, {'type': 'approval_granted'}) - self._status(f"✅ {nickname} 经群主同意重新加入") - self._broadcast({'type': 'system', - 'text': f"✅ {nickname} 经群主同意重新加入"}, exclude=cid) - self._broadcast_users() - # 给成员发群信息 - self._send_to(cid, {'type': 'group_info', - 'group_name': self.group_name, - 'announcement': self.announcement}) - self._status(f"👋 {nickname} 加入了聊天室") - self._broadcast({'type': 'system', 'text': f"👋 {nickname} 加入了聊天室"}, exclude=cid) - self._broadcast_users() - else: - self._remove_client(cid) - return - except Exception: - self._remove_client(cid) - return - - # 第二步: 消息循环 - while self.running: - if cid not in self.clients: - break - try: - msg = recv_msg(client) - if msg is None: - break - self._handle_msg(cid, msg) - except Exception: - break - - self._remove_client(cid) - - def _handle_msg(self, cid, msg): - mtype = msg.get('type') - with self.lock: - if cid not in self.clients: - return - c = self.clients[cid] - uname = c['nickname'] - account = c.get('account', '') - is_host = c.get('is_host', False) - user_key = c.get('user_key') - - # 来源认证: 校验每用户签名 + 账户绑定 (服务器只转发真实用户的消息) - secret = user_key or self.auth_secret - if secret and not self._verify_sig(msg, account, secret): - self._status(f"⚠️ 拒绝未认证的消息 (来自 {uname})") - return - - if mtype == 'rename': - new_name = str(msg.get('new_name', uname))[:20] - with self.lock: - if cid in self.clients: - self.clients[cid]['nickname'] = new_name - self._status(f"✏️ {uname} 改名为 {new_name}") - self._broadcast({'type': 'system', 'text': f"✏️ {uname} 改名为 {new_name}"}, exclude=cid) - self._send_to(cid, {'type': 'system', 'text': f"✅ 你已改名为 {new_name}"}) - self._broadcast_users() - - elif mtype == 'set_announcement': - if not is_host: - return - self.announcement = str(msg.get('text', ''))[:500] - if self.server_db: - self.server_db.save_info(self.server_key, self.group_name, self.announcement) - self._broadcast({'type': 'announcement', 'text': self.announcement, - 'ts': int(time.time())}, exclude=None) - self._status("📢 公告已更新") - - elif mtype == 'set_group_name': - if not is_host: - return - self.group_name = str(msg.get('name', ''))[:30] - if self.server_db: - self.server_db.save_info(self.server_key, self.group_name, self.announcement) - self._broadcast({'type': 'group_name', 'name': self.group_name}, exclude=None) - self._status(f"🏷️ 群名更新: {self.group_name}") - - elif mtype == 'kick': - if not is_host: - return - target = str(msg.get('target', msg.get('account', ''))) - kick_cid = None - with self.lock: - for cid2, cc in self.clients.items(): - if cc.get('account') == target and cid2 != cid: - kick_cid = cid2 - break - if kick_cid is not None: - if self.server_db: - self.server_db.add_kicked(self.server_key, target) - self._send_to(kick_cid, {'type': 'kick', 'reason': '你已被群主移出群'}) - self._broadcast({'type': 'system', 'text': f"🚫 {target} 已被群主移出群"}, exclude=None) - self._remove_client(kick_cid) - - elif mtype == 'approve': - if not is_host: - return - target = str(msg.get('target', msg.get('account', ''))) - decision = msg.get('decision', 'deny') - with self.lock: - target_cid = None - for cid2, cc in self.clients.items(): - if cc.get('account') == target and cc.get('pending'): - target_cid = cid2 - break - if target_cid is not None: - with self.lock: - if target_cid in self.clients: - self.clients[target_cid]['approve_decision'] = decision - if decision == 'grant': - self._status(f"✅ 群主同意 {target} 加入") - else: - self._status(f"❌ 群主拒绝 {target} 加入") - - elif mtype == 'withdraw': - # 只有消息原作者才能撤回 - mid = msg.get('mid', '') - owner = self.mid_owner.get(mid) - if owner and owner[0] == account: - msg['from'] = uname - self._broadcast(msg, exclude=cid) - else: - self._status(f"⚠️ 拒绝他人消息的撤回: {uname}") - - else: - # 普通消息 (chat / file / voice 等): 记录归属并转发 - mid = msg.get('mid') - if mid: - self.mid_owner[mid] = (account, time.time()) - self._prune_mid_owner() - msg['from'] = uname - msg['ts'] = msg.get('ts', int(time.time())) - self._broadcast(msg, exclude=cid) - - def _verify_sig(self, msg, account, secret): - """校验消息 HMAC 签名 + 账户绑定 (secret 为每用户密钥或群密钥)""" - try: - sig = msg.get('sig') - if not sig or not secret: - return False - canonical = json.dumps( - {k: v for k, v in msg.items() if k not in ('sig', 'from', 'ts')}, - sort_keys=True, ensure_ascii=False) - expect = hmac.new(secret.encode('utf-8'), - canonical.encode('utf-8'), hashlib.sha256).hexdigest() - return (sig == expect) and (msg.get('account') == account) - except Exception: - return False - - def _prune_mid_owner(self): - now = time.time() - expired = [m for m, (a, t) in self.mid_owner.items() if now - t > 300] - for m in expired: - self.mid_owner.pop(m, None) - - def _wait_approval(self, cid): - """等待群主同意; 返回 True=同意, False=拒绝/断开""" - client = self.clients[cid]['socket'] - try: - client.settimeout(0.5) - except Exception: - pass - try: - while self.running and cid in self.clients: - with self.lock: - decision = self.clients[cid].get('approve_decision') if cid in self.clients else None - if decision == 'grant': - return True - if decision == 'deny': - self._send_to(cid, {'type': 'approval_denied', 'reason': '群主拒绝了你的加入'}) - return False - try: - data = client.recv(1024) - if not data: - return False - except socket.timeout: - continue - except Exception: - return False - return False - finally: - try: - client.settimeout(None) - except Exception: - pass - - def _send_to(self, cid, msg): - with self.lock: - c = self.clients.get(cid) - if c: - try: - with c['lock']: - send_msg(c['socket'], msg) - except Exception: - pass - - def _remove_client(self, cid): - with self.lock: - entry = self.clients.pop(cid, None) - if cid == self.host_cid: - self.host_cid = None - if entry: - try: - entry['socket'].close() - except Exception: - pass - uname = entry['nickname'] - self._status(f"🔌 {uname} 已断开") - self._broadcast({'type': 'system', 'text': f"👋 {uname} 离开了聊天室"}, exclude=cid) - self._broadcast_users() - - def _broadcast_users(self): - with self.lock: - users = [{'name': c['nickname'], 'account': c.get('account', '')} - for c in self.clients.values()] - self._broadcast({'type': 'users', 'users': users}, exclude=None) - - def _broadcast(self, msg, exclude=None): - with self.lock: - targets = [c for cid, c in self.clients.items() if cid != exclude] - for c in targets: - try: - with c['lock']: - send_msg(c['socket'], msg) - except Exception: - pass - - -# ==================== 聊天客户端 v5 ==================== -class ChatClient: - def __init__(self, on_message=None, on_status=None, on_users=None, - on_file=None, on_voice=None, on_system=None, on_withdraw=None, - on_announcement=None, on_group_name=None, on_kick=None, - on_group_info=None, on_need_approval=None, on_approval_granted=None, - on_approval_denied=None, on_approval_request=None, on_user_key_issued=None, - on_read=None): - self.sock = None - self.username = '' - self.running = False - self.connected = False - self.user_key = None - self.user_key_enc = None - self.on_message = on_message - self.on_status = on_status - self.on_users = on_users - self.on_file = on_file - self.on_voice = on_voice - self.on_system = on_system - self.on_withdraw = on_withdraw - self.on_announcement = on_announcement - self.on_group_name = on_group_name - self.on_kick = on_kick - self.on_group_info = on_group_info - self.on_need_approval = on_need_approval - self.on_approval_granted = on_approval_granted - self.on_approval_denied = on_approval_denied - self.on_approval_request = on_approval_request - self.on_user_key_issued = on_user_key_issued - self.on_read = on_read - self.account = '' - self.auth_secret = None - - def _emit_status(self, text): - if self.on_status: - try: - self.on_status(text) - except Exception: - pass - - def connect(self, host, port, username, nickname=None, account=None, - auth_secret=None, user_key=None, user_key_enc=None): - try: - self.sock = socket.create_connection((host, port), timeout=10) - self.sock.settimeout(None) - self.username = username - self.account = account or username - self.auth_secret = auth_secret - self.user_key = user_key - self.user_key_enc = user_key_enc - nick = nickname or username - acc = account or username - join_payload = {'type': 'join', 'username': nick, - 'nickname': nick, 'account': acc} - if auth_secret: - join_payload['auth'] = hmac.new(auth_secret.encode('utf-8'), - acc.encode('utf-8'), - hashlib.sha256).hexdigest() - if user_key: - join_payload['user_auth'] = hmac.new( - user_key.encode('utf-8'), ('JOIN:' + acc).encode('utf-8'), - hashlib.sha256).hexdigest() - send_msg(self.sock, join_payload) - self.running = True - self.connected = True - threading.Thread(target=self._recv_loop, daemon=True).start() - return True - except Exception as e: - self._emit_status(f"❌ 连接失败: {e}") - return False - - def _sign(self, payload): - """为消息附加账户身份 + 每用户 HMAC 签名 (服务器校验, 防冒充)""" - payload['account'] = self.account or self.username - secret = self.user_key or self.auth_secret - if secret: - canonical = json.dumps( - {k: v for k, v in payload.items() if k not in ('sig', 'from', 'ts')}, - sort_keys=True, ensure_ascii=False) - payload['sig'] = hmac.new(secret.encode('utf-8'), - canonical.encode('utf-8'), - hashlib.sha256).hexdigest() - return payload - - def _recv_loop(self): - while self.running: - try: - msg = recv_msg(self.sock) - if msg is None: - break - self._dispatch(msg) - except Exception: - break - self.connected = False - if self.running: - self._emit_status("🔌 连接已断开") - if self.on_system: - try: - self.on_system("🔌 与服务器的连接已断开") - except Exception: - pass - - def _dispatch(self, msg): - t = msg.get('type') - try: - if t == 'chat': - if self.on_message: - self.on_message(msg.get('from', '?'), msg.get('text', ''), msg.get('mid', '')) - elif t == 'system': - if self.on_system: - self.on_system(msg.get('text', '')) - elif t == 'users': - if self.on_users: - self.on_users(msg.get('users', [])) - elif t == 'file': - if self.on_file: - self.on_file(msg) - elif t == 'voice': - if self.on_voice: - self.on_voice(msg) - elif t == 'withdraw': - if self.on_withdraw: - self.on_withdraw(msg.get('mid', '')) - elif t == 'read': - if self.on_read: - self.on_read(msg.get('mid', '')) - elif t == 'announcement': - if self.on_announcement: - self.on_announcement(msg.get('text', '')) - elif t == 'group_name': - if self.on_group_name: - self.on_group_name(msg.get('name', '')) - elif t == 'group_info': - if self.on_group_info: - self.on_group_info(msg.get('group_name', ''), msg.get('announcement', '')) - elif t == 'kick': - if self.on_kick: - self.on_kick(msg.get('reason', '你已被移出群')) - elif t == 'need_approval': - if self.on_need_approval: - self.on_need_approval(msg.get('reason', '等待群主同意')) - elif t == 'approval_granted': - if self.on_approval_granted: - self.on_approval_granted() - elif t == 'approval_denied': - if self.on_approval_denied: - self.on_approval_denied(msg.get('reason', '群主拒绝你加入')) - elif t == 'approval_request': - if self.on_approval_request: - self.on_approval_request(msg.get('account', ''), msg.get('nickname', '')) - elif t == 'user_key_issued': - try: - if self.user_key_enc: - uk = stream_xor(base64.b64decode(msg.get('data', '')), - bytes.fromhex(self.user_key_enc)).decode('utf-8') - self.user_key = uk - if self.on_user_key_issued: - self.on_user_key_issued(uk) - except Exception: - pass - except Exception: - pass - - # ---- 发送 ---- - def send_chat(self, text, mid=None): - if not self.connected: - return False - try: - payload = {'type': 'chat', 'text': text, 'ts': int(time.time())} - if mid: - payload['mid'] = mid - send_msg(self.sock, self._sign(payload)) - return True - except Exception as e: - self._emit_status(f"❌ 发送失败: {e}") - return False - - def send_file(self, filename, data_bytes, mid=None, mime='file'): - if not self.connected: - return False - try: - payload = {'type': 'file', 'filename': filename, 'size': len(data_bytes), - 'data': base64.b64encode(data_bytes).decode('ascii'), - 'mime': mime, 'ts': int(time.time())} - if mid: - payload['mid'] = mid - send_msg(self.sock, self._sign(payload)) - return True - except Exception as e: - self._emit_status(f"❌ 发送文件失败: {e}") - return False - - def send_voice(self, wav_bytes, mid=None): - if not self.connected: - return False - try: - payload = {'type': 'voice', 'data': base64.b64encode(wav_bytes).decode('ascii'), - 'size': len(wav_bytes), 'ts': int(time.time())} - if mid: - payload['mid'] = mid - send_msg(self.sock, self._sign(payload)) - return True - except Exception as e: - self._emit_status(f"❌ 发送语音失败: {e}") - return False - - def send_withdraw(self, mid): - if not self.connected: - return False - try: - send_msg(self.sock, self._sign({'type': 'withdraw', 'mid': mid})) - return True - except Exception: - return False - - def send_rename(self, new_name): - if not self.connected: - return False - try: - send_msg(self.sock, self._sign({'type': 'rename', 'new_name': new_name})) - return True - except Exception: - return False - - def send_read(self, mid): - """发送已读回执""" - if not self.connected: - return False - try: - send_msg(self.sock, self._sign({'type': 'read', 'mid': mid})) - return True - except Exception: - return False - - def send_announcement(self, text): - if not self.connected: - return False - try: - send_msg(self.sock, self._sign({'type': 'set_announcement', 'text': text})) - return True - except Exception: - return False - - def send_set_group_name(self, name): - if not self.connected: - return False - try: - send_msg(self.sock, self._sign({'type': 'set_group_name', 'name': name})) - return True - except Exception: - return False - - def send_kick(self, account): - if not self.connected: - return False - try: - send_msg(self.sock, self._sign({'type': 'kick', 'target': account})) - return True - except Exception: - return False - - def send_approval(self, account, decision='grant'): - if not self.connected: - return False - try: - send_msg(self.sock, self._sign({'type': 'approve', 'target': account, 'decision': decision})) - return True - except Exception: - return False - - def disconnect(self): - self.running = False - self.connected = False - if self.sock: - try: - self.sock.close() - except Exception: - pass - self.sock = None - - - -# ==================== 中央服务器连接 (解决 NAT) ==================== -class ServerConnection: - """连接到中央服务器: 认证 + 群管理 + 消息中继 (密钥永不上传)""" - - def __init__(self, on_status=None, on_groups=None, on_message=None, on_members=None, - on_system=None, on_group_name=None, on_announcement=None, on_group_info=None): - self.sock = None - self.running = False - self.connected = False - self.token = '' - self.username = '' - self.addr = '' - self.on_status = on_status - self.on_groups = on_groups - self.on_message = on_message - self.on_members = on_members - self.on_system = on_system - self.on_group_name = on_group_name - self.on_announcement = on_announcement - self.on_group_info = on_group_info - - def _emit(self, text): - if self.on_status: - try: - self.on_status(text) - except Exception: - pass - - def connect(self, host, port): - try: - self.sock = socket.create_connection((host, port), timeout=10) - self.sock.settimeout(None) - self.addr = f"{host}:{port}" - self.connected = True - return True - except Exception as e: - self._emit(f"❌ 连接中央服务器失败: {e}") - return False - - def register(self, username, password): - send_msg(self.sock, {'type': 'register', 'username': username, 'password': password}) - return self._wait_login() - - def login(self, username, password): - send_msg(self.sock, {'type': 'login', 'username': username, 'password': password}) - return self._wait_login() - - def _wait_login(self): - try: - self.sock.settimeout(6) - msg = recv_msg(self.sock) - except Exception: - return False, '服务器无响应' - finally: - try: - self.sock.settimeout(None) - except Exception: - pass - if msg and msg.get('type') == 'login_ok': - self.token = msg.get('token', '') - self.username = msg.get('username', '') - self.running = True - threading.Thread(target=self._recv_loop, daemon=True).start() - return True, 'ok' - if msg and msg.get('type') == 'error': - return False, msg.get('msg', '认证失败') - return False, '服务器返回异常' - - def _recv_loop(self): - while self.running: - try: - msg = recv_msg(self.sock) - if msg is None: - break - self._dispatch(msg) - except Exception: - break - self.connected = False - if self.running: - self._emit("🔌 与中央服务器断开") - - def _dispatch(self, msg): - t = msg.get('type') - try: - if t == 'groups': - if self.on_groups: - self.on_groups(msg.get('groups', [])) - elif t == 'group_message': - if self.on_message: - self.on_message(msg.get('group_id', ''), msg.get('from', '?'), - msg.get('payload')) - elif t == 'members': - if self.on_members: - self.on_members(msg.get('group_id', ''), msg.get('members', [])) - elif t == 'system': - if self.on_system: - self.on_system(msg.get('group_id', ''), msg.get('text', '')) - elif t == 'group_name': - if self.on_group_name: - self.on_group_name(msg.get('group_id', ''), msg.get('name', '')) - elif t == 'announcement': - if self.on_announcement: - self.on_announcement(msg.get('group_id', ''), msg.get('text', '')) - elif t == 'group_info': - if self.on_group_info: - self.on_group_info(msg.get('group_id', ''), msg.get('name', ''), - msg.get('announcement', '')) - except Exception: - pass - - def create_group(self, group_id, name): - send_msg(self.sock, {'type': 'create_group', 'group_id': group_id, 'name': name}) - - def list_groups(self): - send_msg(self.sock, {'type': 'list_groups'}) - - def join_group(self, group_id): - send_msg(self.sock, {'type': 'join_group', 'group_id': group_id}) - - def leave_group(self, group_id): - send_msg(self.sock, {'type': 'leave_group', 'group_id': group_id}) - - def set_group_name(self, group_id, name): - send_msg(self.sock, {'type': 'set_group_name', 'group_id': group_id, 'name': name}) - - def set_announcement(self, group_id, text): - send_msg(self.sock, {'type': 'set_announcement', 'group_id': group_id, 'text': text}) - - def group_members(self, group_id): - send_msg(self.sock, {'type': 'group_members', 'group_id': group_id}) - - def send_message(self, group_id, payload): - if not self.connected: - return False - try: - send_msg(self.sock, {'type': 'group_message', 'group_id': group_id, - 'payload': payload}) - return True - except Exception: - return False - - def disconnect(self): - self.running = False - self.connected = False - if self.sock: - try: - self.sock.close() - except Exception: - pass - self.sock = None - - -# ==================== 会话文件 (记住登录) ==================== -def save_session(token): - try: - with open(SESSION_FILE, 'w', encoding='utf-8') as f: - f.write(token) - except Exception: - pass - - -def load_session(): - try: - with open(SESSION_FILE, 'r', encoding='utf-8') as f: - return f.read().strip() - except Exception: - return '' - - -def clear_session(): - try: - if os.path.exists(SESSION_FILE): - os.remove(SESSION_FILE) - except Exception: - pass - - -# ==================== 服务器账号记住我 + 群本地缓存 ==================== -SERVER_CRED_FILE = os.path.join(DATA_DIR, 'server_cred.dat') -SERVER_GROUPS_CACHE = os.path.join(DATA_DIR, 'server_groups_cache.json') - - -def _cred_key(pass_hash): - """用本地账号密码哈希派生密钥 (记住服务器账号用)""" - return hashlib.sha256(pass_hash.encode('utf-8') + b'|SERVER_CRED').digest() - - -def save_server_cred(pass_hash, addr, username, password): - """记住服务器账号: 加密存储 (密钥=本地账号密码哈希派生)""" - try: - key = _cred_key(pass_hash) - nonce = os.urandom(16) - k = hashlib.sha256(key + nonce).digest() - ct = stream_xor(f"{addr}\n{username}\n{password}".encode('utf-8'), k) - h = hmac.new(key, nonce + ct, hashlib.sha256).hexdigest() - blob = base64.b64encode(b'CRED' + nonce + h.encode('ascii') + ct).decode('ascii') - with open(SERVER_CRED_FILE, 'w', encoding='utf-8') as f: - f.write(blob) - return True - except Exception: - return False - - -def load_server_cred(pass_hash): - """读取记住的服务器账号; 密钥不符返回 None""" - try: - with open(SERVER_CRED_FILE, 'r', encoding='utf-8') as f: - b64 = f.read().strip() - key = _cred_key(pass_hash) - blob = base64.b64decode(b64) - if not blob.startswith(b'CRED'): - return None - nonce = blob[4:20] - h = blob[20:84] - ct = blob[84:] - if hmac.new(key, nonce + ct, hashlib.sha256).hexdigest() != h.decode('ascii'): - return None - k = hashlib.sha256(key + nonce).digest() - text = stream_xor(ct, k).decode('utf-8') - addr, username, password = text.split('\n', 2) - return (addr, username, password) - except Exception: - return None - - -def save_server_groups_cache(server_addr, groups): - """本地缓存服务器群列表 (离线也能显示)""" - try: - data = {} - if os.path.exists(SERVER_GROUPS_CACHE): - with open(SERVER_GROUPS_CACHE, 'r', encoding='utf-8') as f: - data = json.load(f) - data[server_addr] = groups - with open(SERVER_GROUPS_CACHE, 'w', encoding='utf-8') as f: - json.dump(data, f, ensure_ascii=False) - except Exception: - pass - - -def load_server_groups_cache(server_addr): - try: - if os.path.exists(SERVER_GROUPS_CACHE): - with open(SERVER_GROUPS_CACHE, 'r', encoding='utf-8') as f: - data = json.load(f) - return data.get(server_addr, []) - except Exception: - pass - return [] - - -import warnings -warnings.filterwarnings('ignore', message='sipPyTypeDict.*') -# PyQt5 -from PyQt5 import QtCore, QtGui, QtWidgets - -# 复用后端 (dvs_enc.py) -from dvs_enc import ( - AccountDB, HistoryDB, ServerDB, SecureSession, ChatClient, ChatServer, - ServerConnection, VoiceManager, Message, gen_mid, save_media, - delete_media, clear_media_cache, save_session, load_session, clear_session, - MEDIA_DIR -) - -APP_NAME = "🔐 混沌加密聊天" - -DOWNLOAD_DIR = os.path.join(os.path.expanduser('~'), 'Downloads', 'ChaosChat') -try: - os.makedirs(DOWNLOAD_DIR, exist_ok=True) -except Exception: - pass - - -# ==================== 现代化样式 (QSS) ==================== -QSS = """ -QMainWindow, QDialog { background: #ffffff; } -QLabel { color: #2c3e50; } -QListWidget { - background: #ffffff; border: 1px solid #e0e4ea; border-radius: 8px; - padding: 4px; font-size: 13px; -} -QListWidget::item { padding: 6px; border-radius: 6px; margin: 2px; } -QListWidget::item:selected { background: #dbe7ff; color: #1a73e8; } -QListWidget::item:hover { background: #f0f4ff; } -QTextEdit, QLineEdit { - background: #ffffff; border: 1px solid #e0e4ea; border-radius: 8px; padding: 6px; - font-size: 13px; -} -QPushButton { - background: #eef1f6; border: none; border-radius: 8px; padding: 7px 14px; - font-size: 13px; color: #2c3e50; -} -QPushButton:hover { background: #e2e7f0; } -QPushButton:disabled { background: #f0f0f0; color: #aaa; } -QPushButton.primary { background: #4CAF50; color: white; } -QPushButton.primary:hover { background: #43a047; } -QPushButton.info { background: #2196F3; color: white; } -QPushButton.info:hover { background: #1e88e5; } -QPushButton.danger { background: #e74c3c; color: white; } -QPushButton.danger:hover { background: #c0392b; } -QToolBar { background: #ffffff; border-bottom: 1px solid #e0e4ea; spacing: 4px; padding: 4px; } -QMenuBar { background: #ffffff; border-bottom: 1px solid #e0e4ea; } -QMenuBar::item { padding: 6px 10px; border-radius: 6px; } -QMenuBar::item:selected { background: #dbe7ff; } -QMenu { background: #ffffff; border: 1px solid #e0e4ea; border-radius: 8px; padding: 6px; } -QMenu::item { padding: 6px 24px; border-radius: 6px; } -QMenu::item:selected { background: #dbe7ff; color: #1a73e8; } -QScrollBar:vertical { background: transparent; width: 8px; } -QScrollBar::handle:vertical { background: #c5cbd6; border-radius: 4px; min-height: 30px; } -QScrollBar::add-line, QScrollBar::sub-line { height: 0; } -QStatusBar { background: #ffffff; border-top: 1px solid #e0e4ea; } -""" - - -# ==================== 消息项组件 ==================== -class MessageItem(QtWidgets.QWidget): - """单条消息: 我的靠左, 别人靠右; 整条可选中, 右键菜单""" - - def __init__(self, msg, actions, parent=None): - super().__init__(parent) - self.msg = msg - self.mid = msg.mid - self.actions = actions - self._selected = False - self._notify_select = None - self._status_lab = None - self.setCursor(QtCore.Qt.PointingHandCursor) - # 关键: 自定义 QWidget 必须开 WA_StyledBackground, 否则 QSS 背景不绘制 - self.setAttribute(QtCore.Qt.WA_StyledBackground, True) - self.setStyleSheet("MessageItem{background:#ffffff; border-radius:12px;}") - - lay = QtWidgets.QVBoxLayout(self) - lay.setContentsMargins(10, 6, 10, 6) - lay.setSpacing(3) - - # 头部: 发送者 + 时间 (我的靠左, 别人靠右; 我的显示已读/未读) - head_row = QtWidgets.QHBoxLayout() - head = QtWidgets.QLabel(f"👤 {msg.sender} {datetime.fromtimestamp(msg.timestamp).strftime('%H:%M:%S')}") - head.setStyleSheet("font-weight:bold; color:%s;" % ('#1a73e8' if msg.is_mine else '#7a5af8')) - if msg.is_mine: - head_row.addWidget(head) - head_row.addStretch() - self._status_lab = QtWidgets.QLabel("已读" if msg.read else "未读") - self._status_lab.setStyleSheet("color:#999; font-size:11px;") - head_row.addWidget(self._status_lab) - else: - head_row.addStretch() - head_row.addWidget(head) - lay.addLayout(head_row) - - # 内容 - if msg.withdrawn: - lab = QtWidgets.QLabel("🚫 此消息已撤回") - lab.setStyleSheet("color:#999; font-style:italic;") - self._align(lay, lab) - elif msg.type == 'text': - lab = QtWidgets.QLabel(msg.content) - lab.setWordWrap(True) - lab.setMaximumWidth(560) - lab.setStyleSheet("background:#f0f2f5; border-radius:14px; padding:10px 14px;") - lab.setSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Preferred) - self._align(lay, lab) - elif msg.type == 'image': - self._add_image(lay) - elif msg.type in ('voice', 'audio'): - self._add_audio(lay) - elif msg.type == 'file': - self._add_file(lay) - else: - lab = QtWidgets.QLabel(str(msg.content)) - lab.setStyleSheet("color:#666;") - self._align(lay, lab) - - # 关键: 按钮不装过滤器且不透明(保证可点击); 其他子控件(文字/气泡)装过滤器 → 点击选中 - self.installEventFilter(self) - for ch in self.findChildren(QtWidgets.QWidget): - if not isinstance(ch, QtWidgets.QPushButton): - ch.installEventFilter(self) - - def _align(self, lay, w): - """我的消息靠左, 别人的靠右""" - if self.msg.is_mine: - lay.addWidget(w, 0, QtCore.Qt.AlignLeft) - else: - lay.addWidget(w, 0, QtCore.Qt.AlignRight) - - def _align_row(self, row, bubble): - if self.msg.is_mine: - row.addWidget(bubble) - row.addStretch() - else: - row.addStretch() - row.addWidget(bubble) - - def mousePressEvent(self, event): - # 点击消息自身背景 → 选中 - if event.button() == QtCore.Qt.LeftButton and self._notify_select: - self._notify_select() - super().mousePressEvent(event) - - def eventFilter(self, obj, event): - # 点击文字/气泡等子控件(按钮除外) → 选中本消息; 按钮保持自身功能 - if event.type() == QtCore.QEvent.MouseButtonPress and event.button() == QtCore.Qt.LeftButton: - if not isinstance(obj, QtWidgets.QPushButton) and self._notify_select: - self._notify_select() - return False - - def set_selected(self, sel): - self._selected = sel - if sel: - self.setStyleSheet("MessageItem{background:#9cc6ff; border-left:6px solid #1a73e8; border-radius:12px;}") - else: - self.setStyleSheet("MessageItem{background:#ffffff; border-radius:12px;}") - - def set_read_status(self, read): - if self._status_lab: - self._status_lab.setText("已读" if read else "未读") - - def _act(self, key, *args): - fn = self.actions.get(key) - if fn: - try: - fn(*args) - except Exception as e: - print(f" [ACT] 操作 {key} 失败: {e}") - - def _add_file(self, lay): - c = self.msg.content if isinstance(self.msg.content, dict) else {} - fname = c.get('filename', '文件') - size = c.get('size', 0) - ext = c.get('ext', os.path.splitext(fname)[1]) - icon = file_icon(ext) - bubble = QtWidgets.QFrame() - bubble.setStyleSheet("QFrame{background:#e8f0fe; border-radius:14px;}") - blay = QtWidgets.QHBoxLayout(bubble) - blay.setContentsMargins(16, 10, 10, 10) - blay.setSpacing(10) - lab = QtWidgets.QLabel(f"{icon} {fname} ({size // 1024} KB)") - lab.setStyleSheet("background:transparent; color:#202124; font-size:13px;") - lab.setMaximumWidth(360) - blay.addWidget(lab) - dl = QtWidgets.QPushButton("💾 下载") - dl.setStyleSheet("background:#d3e0fb; color:#1a73e8; border-radius:8px; padding:5px 12px;") - dl.clicked.connect(lambda: self._act('on_download', self.mid)) - blay.addWidget(dl) - row = QtWidgets.QHBoxLayout() - self._align_row(row, bubble) - lay.addLayout(row) - - def _add_audio(self, lay): - c = self.msg.content if isinstance(self.msg.content, dict) else {} - fname = c.get('filename', '') - label = "🔊 语音" if self.msg.type == 'voice' else f"🎵 音频 {fname}" - size = c.get('size', 0) - bubble = QtWidgets.QFrame() - bubble.setStyleSheet("QFrame{background:#efe9ff; border-radius:14px;}") - blay = QtWidgets.QHBoxLayout(bubble) - blay.setContentsMargins(12, 10, 10, 10) - blay.setSpacing(10) - play = QtWidgets.QPushButton("▶ 播放") - play.setStyleSheet("background:#7a5af8; color:#fff; border-radius:10px; padding:7px 16px;") - play.clicked.connect(lambda: self._act('on_play', self.mid)) - blay.addWidget(play) - lab = QtWidgets.QLabel(f"{label} ({size // 1024} KB)") - lab.setStyleSheet("background:transparent; color:#5a4a9a; font-size:13px;") - blay.addWidget(lab) - dl = QtWidgets.QPushButton("💾") - dl.setStyleSheet("background:#ddd4f7; color:#5a4a9a; border-radius:8px; padding:5px 10px;") - dl.clicked.connect(lambda: self._act('on_download', self.mid)) - blay.addWidget(dl) - row = QtWidgets.QHBoxLayout() - self._align_row(row, bubble) - lay.addLayout(row) - - def _add_image(self, lay): - c = self.msg.content if isinstance(self.msg.content, dict) else {} - data = self.msg.get_data_bytes() - bubble = QtWidgets.QFrame() - bubble.setStyleSheet("QFrame{background:#ffffff; border-radius:14px; border:1px solid #e0e4ea;}") - blay = QtWidgets.QHBoxLayout(bubble) - blay.setContentsMargins(8, 8, 8, 8) - blay.setSpacing(8) - if data: - try: - from PIL import Image, ImageTk - img = Image.open(io.BytesIO(data)) - img.thumbnail((220, 220)) - img = img.convert("RGBA") - qimg = QtGui.QImage(img.tobytes(), img.width, img.height, QtGui.QImage.Format_RGBA8888) - pix = QtGui.QPixmap.fromImage(qimg) - lab = QtWidgets.QLabel() - lab.setPixmap(pix) - lab.setCursor(QtCore.Qt.PointingHandCursor) - lab.mousePressEvent = lambda e: self._act('on_preview', self.mid) - blay.addWidget(lab) - except Exception: - lab = QtWidgets.QLabel("🖼️ 图片(无法预览)") - blay.addWidget(lab) - else: - lab = QtWidgets.QLabel("🖼️ 图片(文件已清理)") - blay.addWidget(lab) - dl = QtWidgets.QPushButton("💾 下载") - dl.setStyleSheet("background:#eef1f6; color:#2c3e50; border-radius:8px; padding:5px 12px;") - dl.clicked.connect(lambda: self._act('on_download', self.mid)) - blay.addWidget(dl) - row = QtWidgets.QHBoxLayout() - self._align_row(row, bubble) - lay.addLayout(row) - - -class MessageList(QtWidgets.QScrollArea): - """自适应消息列表 (QScrollArea + VBox): 每条消息按内容自动调高""" - - def __init__(self, on_menu=None, on_selected=None, parent=None): - super().__init__(parent) - self.setWidgetResizable(True) - self.setFrameShape(QtWidgets.QFrame.NoFrame) - self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) - self._container = QtWidgets.QWidget() - self._container.setStyleSheet("background:#ffffff;") - self._layout = QtWidgets.QVBoxLayout(self._container) - self._layout.setContentsMargins(6, 6, 6, 6) - self._layout.setSpacing(6) - self._layout.addStretch(1) # 消息从顶部排列, 底部弹性 - self.setWidget(self._container) - self._items = {} # mid -> MessageItem - self.selected_mid = None - self._on_menu = on_menu - self._on_selected = on_selected - self.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) - self.customContextMenuRequested.connect(self._on_right_click) - # 点击空白处 → 取消选中 - self._container.installEventFilter(self) - self.viewport().installEventFilter(self) - self.installEventFilter(self) - - def eventFilter(self, obj, event): - """点击消息区空白处 → 自动取消选中""" - if event.type() == QtCore.QEvent.MouseButtonPress and event.button() == QtCore.Qt.LeftButton: - if obj in (self._container, self.viewport(), self): - self._deselect() - return False - - def _deselect(self): - self.selected_mid = None - for w in self._items.values(): - w.set_selected(False) - if self._on_selected: - self._on_selected(None) - - def _select(self, mid): - self.selected_mid = mid - for m, w in self._items.items(): - w.set_selected(m == mid) - if self._on_selected: - self._on_selected(mid) - - def _on_right_click(self, pos): - item = self._message_at(pos) - if not item: - self._deselect() - return - self._select(item.mid) - if self._on_menu: - self._on_menu(item.mid, self.mapToGlobal(pos)) - - def _message_at(self, pos): - global_pos = self.mapToGlobal(pos) - w = self._container.childAt(self._container.mapFromGlobal(global_pos)) - while w is not None: - if isinstance(w, MessageItem): - return w - w = w.parentWidget() - return None - - def add_message(self, msg, actions): - wid = MessageItem(msg, actions) - wid._notify_select = lambda m=msg.mid: self._select(m) - wid.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred) - self._layout.insertWidget(self._layout.count() - 1, wid) # 插到 stretch 之前 - self._items[msg.mid] = wid - # 等宽度确定后再滚到底部 - QtCore.QTimer.singleShot(0, self._scroll_bottom) - return wid - - def update_message(self, mid, msg): - """就地更新某条消息 (已读/未读状态)""" - wid = self._items.get(mid) - if wid: - wid.set_read_status(msg.read) - - def _scroll_bottom(self): - bar = self.verticalScrollBar() - bar.setValue(bar.maximum()) - - def remove_message(self, mid): - wid = self._items.pop(mid, None) - if wid: - self._layout.removeWidget(wid) - wid.deleteLater() - if self.selected_mid == mid: - self.selected_mid = None - - def clear_all(self): - for w in self._items.values(): - self._layout.removeWidget(w) - w.deleteLater() - self._items.clear() - self.selected_mid = None - - -# ==================== 登录对话框 ==================== -class LoginDialog(QtWidgets.QDialog): - """本地账号 注册/登录""" - - def __init__(self, db, parent=None): - super().__init__(parent) - self.db = db - self.result = None - self.mode = 'login' - self.setWindowTitle(f"{APP_NAME} - 登录") - self.setFixedSize(380, 420) - self._build() - - def _build(self): - lay = QtWidgets.QVBoxLayout(self) - lay.setSpacing(10) - title = QtWidgets.QLabel("🔐 混沌加密聊天") - title.setAlignment(QtCore.Qt.AlignCenter) - title.setStyleSheet("font-size:20px; font-weight:bold; color:#1a73e8;") - lay.addWidget(title) - - self.mode_lab = QtWidgets.QLabel("本地账号登录") - self.mode_lab.setAlignment(QtCore.Qt.AlignCenter) - self.mode_lab.setStyleSheet("font-size:13px; color:#555;") - lay.addWidget(self.mode_lab) - - self.u = QtWidgets.QLineEdit() - self.u.setPlaceholderText("账户名") - lay.addWidget(self.u) - self.p = QtWidgets.QLineEdit() - self.p.setPlaceholderText("密码") - self.p.setEchoMode(QtWidgets.QLineEdit.Password) - lay.addWidget(self.p) - self.p2 = QtWidgets.QLineEdit() - self.p2.setPlaceholderText("确认密码") - self.p2.setEchoMode(QtWidgets.QLineEdit.Password) - self.p2.setVisible(False) - lay.addWidget(self.p2) - - self.msg = QtWidgets.QLabel("") - self.msg.setStyleSheet("color:#e74c3c;") - lay.addWidget(self.msg) - - row = QtWidgets.QHBoxLayout() - self.btn_main = QtWidgets.QPushButton("登 录") - self.btn_main.setProperty("class", "primary") - self.btn_main.clicked.connect(self._submit) - row.addWidget(self.btn_main) - self.btn_switch = QtWidgets.QPushButton("没有账号?注册") - self.btn_switch.clicked.connect(self._toggle) - row.addWidget(self.btn_switch) - lay.addLayout(row) - - lay.addStretch() - - def _toggle(self): - if self.mode == 'login': - self.mode = 'register' - self.mode_lab.setText("注册本地账号") - self.btn_main.setText("注 册") - self.btn_switch.setText("已有账号?登录") - self.p2.setVisible(True) - else: - self.mode = 'login' - self.mode_lab.setText("本地账号登录") - self.btn_main.setText("登 录") - self.btn_switch.setText("没有账号?注册") - self.p2.setVisible(False) - self.msg.setText("") - - def _submit(self): - user = self.u.text().strip() - pwd = self.p.text() - if not user or not pwd: - self.msg.setText("请输入账户名和密码") - return - if self.mode == 'login': - row, err = self.db.login(user, pwd) - if row is None: - self.msg.setText(err) - return - self.result = row - self.accept() - else: - if len(pwd) < 6: - self.msg.setText("密码至少 6 位") - return - if pwd != self.p2.text(): - self.msg.setText("两次密码不一致") - return - ok, err = self.db.register(user, pwd) - if not ok: - self.msg.setText(err) - return - row, _ = self.db.login(user, pwd) - self.result = row - self.accept() - - -# ==================== 主窗口 ==================== -class MainWindow(QtWidgets.QMainWindow): - def __init__(self, account): - super().__init__() - self.account = dict(account) if account else {'id': 1, 'username': 'user', 'nickname': '用户'} - self.account_db = AccountDB() - self.history = HistoryDB() - self.server_db = ServerDB() - self.voice = VoiceManager(on_status=self._on_status) - - self.groups = {} # gid -> dict - self.order = [] - self.active_gid = None - self.selected_mid = None - self._gid_counter = 0 - - self.server_conn = None - self.server_addr = '' - self.server_username = '' - - self._ui_queue = [] - self._relogin = False - - self.setWindowTitle(f"{APP_NAME} - {self._my_nick()}") - self.resize(1120, 720) - self._build_ui() - - # UI 轮询 - self._timer = QtCore.QTimer(self) - self._timer.timeout.connect(self._poll_ui) - self._timer.start(60) - - # 启动自动加入 (本地P2P群) - QtCore.QTimer.singleShot(500, self._start_auto_join) - # 服务器: 先显示本地缓存, 再记住我自动登录实时同步 - QtCore.QTimer.singleShot(800, self._load_cached_server_groups) - QtCore.QTimer.singleShot(1500, self._auto_connect_server) - - # ---------- 线程安全 ---------- - def _post(self, fn): - self._ui_queue.append(fn) - - def _poll_ui(self): - if self._ui_queue: - tasks = self._ui_queue[:] - self._ui_queue = [] - for fn in tasks: - try: - fn() - except Exception: - pass - - def _my_nick(self): - return self.account.get('nickname') or self.account.get('username', '用户') - - def _on_status(self, text): - self._post(lambda: self.statusBar().showMessage(text, 5000)) - - # ---------- 界面 ---------- - def _build_ui(self): - # 工具栏 - tb = QtWidgets.QToolBar("主工具栏") - tb.setMovable(False) - self.addToolBar(tb) - - def btn(text, fn, cls=''): - b = QtWidgets.QPushButton(text) - if cls: - b.setProperty("class", cls) - b.clicked.connect(fn) - tb.addWidget(b) - return b - - btn("📡 创建群", self._create_group, 'primary') - btn("📥 加入群", self._join_group, 'info') - tb.addSeparator() - btn("☁️ 服务器", self._connect_server) - btn("☁️ 建群", self._create_server_group) - btn("☁️ 加群", self._join_server_group) - tb.addSeparator() - btn("🔑 密钥", self._copy_active_key) - btn("✏️ 改名", self._rename) - btn("📢 公告", self._set_announcement) - btn("🏷️ 群名", self._set_group_name) - btn("🚫 撤回", self._withdraw_selected) - btn("📤 分享", self._share_selected) - - # 菜单 - mb = self.menuBar() - gm = mb.addMenu("群") - gm.addAction("📡 创建群", self._create_group) - gm.addAction("📥 加入群", self._join_group) - gm.addAction("❌ 离开该群", self._leave_active_group) - sm = mb.addMenu("服务器") - sm.addAction("☁️ 连接服务器", self._connect_server) - sm.addAction("☁️ 服务器建群", self._create_server_group) - sm.addAction("☁️ 服务器加群", self._join_server_group) - mm = mb.addMenu("消息") - mm.addAction("🚫 撤回所选", self._withdraw_selected) - mm.addAction("📤 分享所选", self._share_selected) - mm.addAction("💾 下载所选", self._download_selected) - mm.addAction("📋 复制所选", self._copy_selected) - um = mb.addMenu("工具") - um.addAction("🗑️ 清理媒体缓存", self._clear_media_cache) - um.addAction("📂 打开下载目录", self._open_download_dir) - um.addAction("🔓 退出登录", self._logout) - um.addAction("❌ 退出程序", self._quit) - - # 中央区域 - central = QtWidgets.QWidget() - self.setCentralWidget(central) - root = QtWidgets.QHBoxLayout(central) - root.setContentsMargins(8, 8, 8, 8) - root.setSpacing(8) - - # 左: 群列表 - left = QtWidgets.QVBoxLayout() - left.addWidget(QtWidgets.QLabel("👥 群列表")) - self.group_list = QtWidgets.QListWidget() - self.group_list.setFixedWidth(240) - self.group_list.itemClicked.connect(self._on_group_click) - self.group_list.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) - self.group_list.customContextMenuRequested.connect(self._on_group_menu) - left.addWidget(self.group_list) - left_w = QtWidgets.QWidget() - left_w.setLayout(left) - root.addWidget(left_w) - - # 中: 公告横幅 + 消息 + 输入 - center = QtWidgets.QVBoxLayout() - self.banner = QtWidgets.QFrame() - self.banner.setStyleSheet("background:#fff3cd; border-radius:8px;") - b_lay = QtWidgets.QHBoxLayout(self.banner) - self.banner_label = QtWidgets.QLabel("") - self.banner_label.setStyleSheet("color:#8a6d3b;") - b_lay.addWidget(self.banner_label, 1) - b_close = QtWidgets.QPushButton("✕ 关闭") - b_close.setFixedWidth(60) - b_close.clicked.connect(self._hide_banner) - b_lay.addWidget(b_close) - self.banner.setVisible(False) - center.addWidget(self.banner) - - self.message_list = MessageList(on_menu=self._show_context_menu, - on_selected=lambda mid: self._on_msg_selected(mid)) - center.addWidget(self.message_list, 1) - - # 输入区: 多行输入 + 发送 + 图片/文件/语音按钮 - in_area = QtWidgets.QVBoxLayout() - in_row = QtWidgets.QHBoxLayout() - self.input = QtWidgets.QTextEdit() - self.input.setFixedHeight(56) - self.input.setPlaceholderText("输入消息... (Ctrl+Enter 发送)") - QtWidgets.QShortcut(QtGui.QKeySequence("Ctrl+Return"), self.input, - activated=self._send_text) - send = QtWidgets.QPushButton("发 送") - send.setProperty("class", "primary") - send.setFixedHeight(44) - send.clicked.connect(self._send_text) - in_row.addWidget(self.input, 1) - in_row.addWidget(send) - in_area.addLayout(in_row) - - btn_row = QtWidgets.QHBoxLayout() - self.img_btn = QtWidgets.QPushButton("📷 图片") - self.img_btn.clicked.connect(self._send_image) - self.file_btn = QtWidgets.QPushButton("📁 文件") - self.file_btn.clicked.connect(self._send_file) - self.record_btn = QtWidgets.QPushButton("🎤 录音") - self.record_btn.clicked.connect(self._toggle_record) - self.play_btn = QtWidgets.QPushButton("▶ 播放") - self.play_btn.clicked.connect(self._play_voice) - for b in (self.img_btn, self.file_btn, self.record_btn, self.play_btn): - b.setFixedHeight(28) - btn_row.addWidget(b) - btn_row.addStretch() - in_area.addLayout(btn_row) - center.addLayout(in_area) - center_w = QtWidgets.QWidget() - center_w.setLayout(center) - root.addWidget(center_w, 1) - - # 右: 用户列表 - right = QtWidgets.QVBoxLayout() - right.addWidget(QtWidgets.QLabel("🟢 在线用户")) - self.users_list = QtWidgets.QListWidget() - self.users_list.setFixedWidth(180) - self.users_list.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) - self.users_list.customContextMenuRequested.connect(self._on_user_menu) - right.addWidget(self.users_list) - right_w = QtWidgets.QWidget() - right_w.setLayout(right) - root.addWidget(right_w) - - self.statusBar().showMessage("就绪") - self._add_system(None, "📌 点击工具栏或菜单开始;消息可点击选中,右键有更多操作") - - # ---------- 公告横幅 ---------- - def _show_banner(self, text): - if not text: - return - self.banner_label.setText(f"📢 群公告: {text}") - self.banner.setVisible(True) - - def _hide_banner(self): - self.banner.setVisible(False) - - # ---------- 群管理 ---------- - def _new_gid(self): - self._gid_counter += 1 - return f"g{self._gid_counter}" - - def _group_connected(self, group): - if group.get('mode') == 'server': - return bool(group.get('server_conn') and group['server_conn'].connected) - return bool(group.get('client') and group['client'].connected) - - def _build_group(self, gid, host, port, nick, is_host, server, client, session): - return { - 'gid': gid, 'host': host, 'port': port, - 'group_key': f"{host}:{port}", - 'name': nick, 'my_username': nick, - 'my_account': self.account.get('username', ''), - 'is_host': is_host, 'server': server, 'client': client, 'session': session, - 'users': [], 'messages': {}, 'order': [], - 'announcement': '', 'group_name': '', 'mode': 'p2p', 'user_key': None - } - - def _register_group(self, gid, group): - if gid in self.groups: - return - for g in list(self.groups.values()): - if g['group_key'] == group['group_key']: - if group.get('client'): - try: - group['client'].disconnect() - except Exception: - pass - if group.get('server'): - try: - group['server'].stop() - except Exception: - pass - return - self.groups[gid] = group - self.order.append(gid) - self._load_history(gid) - self._refresh_groups() - self._switch_group(gid) - - def _refresh_groups(self): - self.group_list.clear() - for i, gid in enumerate(self.order): - g = self.groups[gid] - tag = '[群主]' if g['is_host'] else '' - prefix = '☁️' if g.get('mode') == 'server' else '🔗' - status = '🟢' if self._group_connected(g) else '🔴' - addr = f"{g['host']}:{g['port']}" - u = g.get('unread', 0) - badge = f" 🔴{u}" if u else "" - item = QtWidgets.QListWidgetItem(f"{status}{prefix}{tag} {g['name']} {addr}{badge}") - item.setData(QtCore.Qt.UserRole, gid) - self.group_list.addItem(item) - - def _on_group_click(self, item): - gid = item.data(QtCore.Qt.UserRole) - if gid and gid != self.active_gid: - self._switch_group(gid) - - def _switch_group(self, gid): - self.active_gid = gid - self.selected_mid = None - group = self.groups.get(gid) - if group: - group['unread'] = 0 - for mid, msg in list(group['messages'].items()): - if not msg.is_mine and not msg.read: - msg.read = True - self._send_read(gid, mid) - self._render_group(gid) - self._refresh_groups() - - def _render_group(self, gid): - self.message_list.clear_all() - group = self.groups.get(gid) - self._render_users(gid) - if not group: - return - for mid in group['order']: - msg = group['messages'][mid] - self.message_list.add_message(msg, self._panel_actions()) - if group.get('announcement'): - self._show_banner(group['announcement']) - else: - self._hide_banner() - - def _render_users(self, gid): - self.users_list.clear() - group = self.groups.get(gid) - if not group: - return - for u in group['users']: - name = u.get('name', '?') - mark = ' (我)' if name == group['my_username'] else '' - self.users_list.addItem(f"👤 {name}{mark}") - - def _panel_actions(self): - return { - 'on_download': self._on_download, - 'on_play': self._on_play, - 'on_preview': self._on_preview, - } - - def _add_message(self, gid, mid, sender, mtype, content, ts, is_mine=False, persist=True): - group = self.groups.get(gid) - if not group: - return - if mid and mid in group['messages']: - return - msg = Message(mid, gid, sender, mtype, content, ts, is_mine) - group['messages'][mid] = msg - group['order'].append(mid) - # 已读/未读: 他人消息, 当前群立即已读+回执; 非当前群计未读 - if not is_mine and mtype != 'system': - if gid == self.active_gid: - msg.read = True - self._send_read(gid, mid) - else: - group['unread'] = group.get('unread', 0) + 1 - self._refresh_groups() - if persist: - try: - self.history.save(self.account['id'], group['group_key'], msg) - except Exception: - pass - if gid == self.active_gid: - self.message_list.add_message(msg, self._panel_actions()) - - def _add_local_message(self, gid, mid, mtype, content): - group = self.groups.get(gid) - if group: - self._add_message(gid, mid, group['my_username'], mtype, content, time.time(), is_mine=True) - - def _add_system(self, gid, text): - if gid is None: - if self.active_gid: - gid = self.active_gid - else: - return - self._add_message(gid, gen_mid(), '系统', 'system', text, time.time(), persist=False) - - def _delete_message(self, gid, mid): - group = self.groups.get(gid) - if not group: - return False - msg = group['messages'].pop(mid, None) - if not msg: - return False - if isinstance(msg.content, dict): - delete_media(msg.content.get('path')) - try: - self.history.delete_by_mid(self.account['id'], group['group_key'], mid) - except Exception: - pass - if mid in group['order']: - group['order'].remove(mid) - if gid == self.active_gid: - self.message_list.remove_message(mid) - return True - - def _load_history(self, gid): - group = self.groups.get(gid) - if not group: - return - try: - rows = self.history.load(self.account['id'], group['group_key']) - except Exception: - rows = [] - for row in rows: - mid = row['mid'] - if not mid or mid in group['messages']: - continue - content = HistoryDB.deserialize_content(row['mtype'], row['content']) - msg = Message(mid, gid, row['sender'], row['mtype'], content, row['ts'], bool(row['is_mine'])) - msg.withdrawn = bool(row['withdrawn']) - group['messages'][mid] = msg - group['order'].append(mid) - - - # ---------- 客户端工厂 ---------- - def _make_client(self, gid): - return ChatClient( - on_message=lambda s, t, m, g=gid: self._post(lambda: self._on_chat(g, s, t, m)), - on_status=lambda t, g=gid: self._post(lambda: self._on_status(t)), - on_users=lambda u, g=gid: self._post(lambda: self._on_users(g, u)), - on_file=lambda m, g=gid: self._on_file(g, m), - on_voice=lambda m, g=gid: self._on_voice(g, m), - on_system=lambda t, g=gid: self._post(lambda: self._add_system(g, t)), - on_withdraw=lambda m, g=gid: self._post(lambda: self._on_withdraw(g, m)), - on_announcement=lambda t, g=gid: self._post(lambda: self._on_announcement(g, t)), - on_group_name=lambda n, g=gid: self._post(lambda: self._on_group_name(g, n)), - on_kick=lambda r, g=gid: self._post(lambda: self._on_kick(g, r)), - on_group_info=lambda gn, an, g=gid: self._post(lambda: self._on_group_info(g, gn, an)), - on_need_approval=lambda r, g=gid: self._post(lambda: self._add_system(g, f"⏳ {r}")), - on_approval_granted=lambda g=gid: self._post(lambda: self._add_system(g, "✅ 群主已同意,你已加入")), - on_approval_denied=lambda r, g=gid: self._post(lambda: self._on_approval_denied(g, r)), - on_approval_request=lambda a, n, g=gid: self._post(lambda: self._on_approval_request(g, a, n)), - on_user_key_issued=lambda uk, g=gid: self._post(lambda: self._on_user_key_issued(g, uk)), - on_read=lambda m, g=gid: self._post( - lambda: self._on_read(g, m)), - ) - - # ---------- P2P 建群/加群 ---------- - def _create_group(self): - from PyQt5.QtWidgets import QInputDialog - port, ok = QInputDialog.getInt(self, "端口", "请输入端口号:", value=8888) - if not ok: - return - gid = self._new_gid() - session = SecureSession(); session.generate() - group_key = f"127.0.0.1:{port}" - server = ChatServer(on_status=lambda t, g=gid: self._post(lambda: self._on_status(t)), - server_key=group_key, server_db=self.server_db, - server_secret=session.session_key) - if not server.start(port): - self._on_status("❌ 服务器启动失败(端口被占用?)") - return - client = self._make_client(gid) - saved_uk = self._get_saved_user_key(group_key) - if not client.connect('127.0.0.1', port, self._my_nick(), nickname=self._my_nick(), - account=self.account.get('username', ''), - auth_secret=session.auth_secret(), - user_key=saved_uk, user_key_enc=session.user_key_enc()): - server.stop() - return - group = self._build_group(gid, '127.0.0.1', port, self._my_nick(), True, server, client, session) - group['user_key'] = saved_uk - self._register_group(gid, group) - self._save_group(gid) - self._add_system(gid, "✅ 群已创建(端到端),你是群主") - self._show_key_dialog(gid) - - def _join_group(self): - from PyQt5.QtWidgets import QInputDialog - host, ok1 = QInputDialog.getText(self, "服务器地址", "服务器IP:", text="127.0.0.1") - if not ok1: - return - port, ok2 = QInputDialog.getInt(self, "端口", "端口号:", value=8888) - if not ok2: - return - key, ok3 = QInputDialog.getText(self, "密钥", "会话密钥(创建者分享):") - if not ok3 or not key: - return - session = SecureSession() - if not session.import_key(key): - self._on_status("❌ 密钥无效") - return - gid = self._new_gid() - client = self._make_client(gid) - saved_uk = self._get_saved_user_key(f"{host}:{port}") - if not client.connect(host, port, self._my_nick(), nickname=self._my_nick(), - account=self.account.get('username', ''), - auth_secret=session.auth_secret(), - user_key=saved_uk, user_key_enc=session.user_key_enc()): - return - group = self._build_group(gid, host, port, self._my_nick(), False, None, client, session) - group['user_key'] = saved_uk - self._register_group(gid, group) - self._save_group(gid) - - def _save_group(self, gid): - group = self.groups.get(gid) - if not group: - return - try: - self.account_db.save_group(self.account['id'], group['group_key'], group['host'], - group['port'], group['session'].export_key(), - self._my_nick(), group['is_host'], group.get('user_key', '')) - except Exception: - pass - - def _get_saved_user_key(self, group_key): - try: - for r in self.account_db.load_groups(self.account['id']): - if r['group_key'] == group_key: - return r['user_key'] or None - except Exception: - pass - return None - - # ---------- 发送辅助 ---------- - def _send_chat_to(self, group, enc, mid): - if group.get('mode') == 'server': - return group['server_conn'].send_message(group['group_id'], - {'kind': 'chat', 'text': enc, 'mid': mid, 'ts': int(time.time())}) - return group['client'].send_chat(enc, mid) - - def _send_file_to(self, group, fname, enc_bytes, mid, mime): - if group.get('mode') == 'server': - return group['server_conn'].send_message(group['group_id'], { - 'kind': 'file', 'filename': fname, 'size': len(enc_bytes), - 'data': base64.b64encode(enc_bytes).decode('ascii'), - 'mime': mime, 'mid': mid, 'ts': int(time.time())}) - return group['client'].send_file(fname, enc_bytes, mid, mime=mime) - - def _send_voice_to(self, group, enc_bytes, mid): - if group.get('mode') == 'server': - return group['server_conn'].send_message(group['group_id'], { - 'kind': 'voice', 'data': base64.b64encode(enc_bytes).decode('ascii'), - 'size': len(enc_bytes), 'mid': mid, 'ts': int(time.time())}) - return group['client'].send_voice(enc_bytes, mid) - - def _send_withdraw_to(self, group, mid): - if group.get('mode') == 'server': - return group['server_conn'].send_message(group['group_id'], {'kind': 'withdraw', 'mid': mid}) - return group['client'].send_withdraw(mid) - - # ---------- 发送 ---------- - def _send_text(self): - gid, group = self._current_group() - if group is None: - self._on_status("请先创建或加入一个群") - return - if not self._group_connected(group): - self._on_status("该群未连接") - return - if not group['session'].has_key(): - self._on_status("该群没有会话密钥") - return - text = self.input.toPlainText().strip() - if not text: - return - try: - mid = gen_mid() - enc = group['session'].encrypt(text) - if self._send_chat_to(group, enc, mid): - self._add_local_message(gid, mid, 'text', text) - self.input.clear() - except Exception as e: - self._add_system(gid, f"❌ 加密失败: {e}") - - def _send_image(self): - gid, group = self._current_group() - if group is None or not self._group_connected(group): - return - path, _ = QtWidgets.QFileDialog.getOpenFileName(self, "选择图片", "", "图片 (*.png *.jpg *.jpeg *.gif *.bmp *.webp)") - if not path: - return - try: - with open(path, 'rb') as f: - data = f.read() - fname = os.path.basename(path) - ext = os.path.splitext(fname)[1].lower() - mid = gen_mid() - enc = group['session'].encrypt_bytes(data) - media_path = save_media(data, ext) - content = {'filename': fname, 'size': len(data), 'path': media_path, 'ext': ext} - if self._send_file_to(group, fname, enc.encode('utf-8'), mid, 'image'): - self._add_local_message(gid, mid, 'image', content) - except Exception as e: - self._add_system(gid, f"❌ 图片读取失败: {e}") - - def _send_file(self): - gid, group = self._current_group() - if group is None or not self._group_connected(group): - return - path, _ = QtWidgets.QFileDialog.getOpenFileName(self, "选择文件") - if not path: - return - try: - with open(path, 'rb') as f: - data = f.read() - fname = os.path.basename(path) - ext = os.path.splitext(fname)[1].lower() - mid = gen_mid() - enc = group['session'].encrypt_bytes(data) - media_path = save_media(data, ext) - content = {'filename': fname, 'size': len(data), 'path': media_path, 'ext': ext} - if self._send_file_to(group, fname, enc.encode('utf-8'), mid, 'file'): - self._add_local_message(gid, mid, 'file', content) - except Exception as e: - self._add_system(gid, f"❌ 文件读取失败: {e}\n (可能是文件被占用/权限/或 .lnk 快捷方式问题)") - - # ---------- 语音 ---------- - def _toggle_record(self): - """录音: 点一次开始, 再点停止并发送""" - gid, group = self._current_group() - if self.voice.recording: - wav = self.voice.stop_recording() - self.record_btn.setText("🎤 录音") - if wav: - if group and self._group_connected(group): - mid = gen_mid() - enc = group['session'].encrypt_bytes(wav) - media_path = save_media(wav, '.wav') - content = {'filename': 'voice.wav', 'size': len(wav), - 'path': media_path, 'ext': '.wav'} - if self._send_voice_to(group, enc.encode('utf-8'), mid): - self._add_local_message(gid, mid, 'voice', content) - else: - self._add_system(gid, "未连接,语音未发送") - else: - if group is None or not self._group_connected(group): - self._on_status("请先加入一个已连接的群") - return - if self.voice.start_recording(): - self.record_btn.setText("⏹ 停止录音") - - def _play_voice(self): - if self.voice.last_voice: - self.voice.play(self.voice.last_voice, self.voice.last_voice_from) - else: - self._on_status("没有可播放的语音") - - # ---------- 接收 ---------- - def _on_chat(self, gid, sender, text, mid): - group = self.groups.get(gid) - if not group: - return - if not group['session'].has_key(): - self._add_system(gid, f"⚠️ 无密钥无法解密 {sender} 的消息") - return - plain = group['session'].decrypt(text) - if plain: - self._add_message(gid, mid or gen_mid(), sender, 'text', plain, int(time.time())) - else: - self._add_system(gid, f"⚠️ {sender} 的消息解密失败") - - def _on_users(self, gid, users): - group = self.groups.get(gid) - if group: - group['users'] = list(users) - if gid == self.active_gid: - self._render_users(gid) - - def _on_file(self, gid, msg): - group = self.groups.get(gid) - if not group: - return - fname = os.path.basename(str(msg.get('filename', '文件'))) - ext = os.path.splitext(fname)[1].lower() - mime = msg.get('mime', 'file') - raw = b'' - try: - eb = base64.b64decode(msg.get('data', '')) - if eb: - raw = group['session'].decrypt_bytes(eb.decode('utf-8')) or b'' - except Exception: - raw = b'' - path = save_media(raw, ext) if raw else '' - content = {'filename': fname, 'size': len(raw), 'path': path, 'ext': ext} - if mime == 'image' or ext in ('.png', '.jpg', '.jpeg', '.gif', '.bmp', '.webp'): - mtype = 'image' - elif mime in ('voice', 'audio') or ext in ('.wav', '.mp3', '.ogg', '.flac'): - mtype = 'audio' - else: - mtype = 'file' - mid = msg.get('mid', gen_mid()) - from_user = msg.get('from', '?') - ts = int(msg.get('ts', time.time())) - self._post(lambda: self._add_message(gid, mid, from_user, mtype, content, ts)) - - def _on_voice(self, gid, msg): - group = self.groups.get(gid) - if not group: - return - raw = b'' - try: - eb = base64.b64decode(msg.get('data', '')) - if eb: - raw = group['session'].decrypt_bytes(eb.decode('utf-8')) or b'' - except Exception: - raw = b'' - path = save_media(raw, '.wav') if raw else '' - content = {'filename': 'voice.wav', 'size': len(raw), 'path': path, 'ext': '.wav'} - mid = msg.get('mid', gen_mid()) - from_user = msg.get('from', '?') - ts = int(msg.get('ts', time.time())) - self._post(lambda: self._add_message(gid, mid, from_user, 'voice', content, ts)) - if raw: - self.voice.play(raw, from_user) - - def _on_withdraw(self, gid, mid): - if self._delete_message(gid, mid): - self._add_system(gid, "🚫 有一条消息已被撤回") - - def _on_announcement(self, gid, text): - group = self.groups.get(gid) - if group: - group['announcement'] = text - if gid == self.active_gid: - self._show_banner(text) - self._add_system(gid, f"📢 群公告更新: {text}") - - def _on_group_name(self, gid, name): - group = self.groups.get(gid) - if group: - group['group_name'] = name or '' - group['name'] = f"{name or group['my_username']}" - self._refresh_groups() - - def _on_group_info(self, gid, gn, an): - if gn: - self._on_group_name(gid, gn) - if an: - self._on_announcement(gid, an) - - def _on_kick(self, gid, reason): - group = self.groups.get(gid) - if group: - try: - group['client'].disconnect() - except Exception: - pass - self._refresh_groups() - self._add_system(gid, f"🚫 {reason}") - - def _on_approval_denied(self, gid, reason): - group = self.groups.get(gid) - if group: - try: - group['client'].disconnect() - except Exception: - pass - self._refresh_groups() - self._add_system(gid, f"❌ {reason}") - - def _on_approval_request(self, gid, account, nickname): - ret = QtWidgets.QMessageBox.question(self, "入群申请", - f"{nickname} ({account}) 曾被移出本群,申请重新加入。是否同意?", - QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No) - group = self.groups.get(gid) - if group: - group['client'].send_approval(account, 'grant' if ret == QtWidgets.QMessageBox.Yes else 'deny') - - def _on_user_key_issued(self, gid, user_key): - group = self.groups.get(gid) - if group: - group['user_key'] = user_key - self._save_group(gid) - - def _send_read(self, gid, mid): - """发送已读回执 (P2P 或 服务器群); 未连接时跳过""" - group = self.groups.get(gid) - if not group: - return - if group.get('mode') == 'server': - sc = group.get('server_conn') - if sc and sc.connected: - sc.send_message(group['group_id'], {'kind': 'read', 'mid': mid}) - elif group.get('client'): - group['client'].send_read(mid) - - def _on_read(self, gid, mid): - """收到已读回执: 自己的消息标记为已读""" - group = self.groups.get(gid) - if not group: - return - msg = group['messages'].get(mid) - if msg and msg.is_mine: - msg.read = True - if gid == self.active_gid: - self.message_list.update_message(mid, msg) - - def _current_group(self): - gid = self.active_gid - if gid is None or gid not in self.groups: - return None, None - return gid, self.groups[gid] - - - # ---------- 中央服务器 (解决 NAT) ---------- - def _connect_server(self): - from PyQt5.QtWidgets import QInputDialog - addr, ok = QInputDialog.getText(self, "中央服务器", "服务器地址 (如 服务器IP:8666):", text="127.0.0.1:8666") - if not ok or not addr: - return - try: - host, port = addr.rsplit(':', 1) - port = int(port) - except Exception: - self._on_status("地址格式应为 主机:端口") - return - # 后台线程连接, 避免卡死 GUI - self._on_status(f"☁️ 正在连接 {host}:{port} ...") - threading.Thread(target=self._do_manual_connect, args=(host, port), daemon=True).start() - - def _do_manual_connect(self, host, port): - """后台连接服务器, 成功后在主线程弹登录框; 已连接则复用""" - if self.server_conn and self.server_conn.connected: - self._post(lambda: self._server_auth_dialog(self.server_conn, host, port)) - return - conn = ServerConnection( - on_status=self._on_status, - on_groups=lambda gl: self._post(lambda: self._on_server_groups(gl)), - on_message=lambda gid, frm, pl: self._post(lambda: self._on_server_group_message(gid, frm, pl)), - on_members=lambda gid, mems: self._post(lambda: self._on_server_members(gid, mems)), - on_system=lambda gid, t: self._post(lambda: self._on_server_system(gid, t)), - on_group_name=lambda gid, n: self._post(lambda: self._on_server_group_name(gid, n)), - on_announcement=lambda gid, t: self._post(lambda: self._on_server_announcement(gid, t)), - on_group_info=lambda gid, n, a: self._post(lambda: self._on_server_group_info(gid, n, a))) - if not conn.connect(host, port): - self._post(lambda: self._on_status(f"❌ 连接 {host}:{port} 失败")) - return - self._post(lambda: self._server_auth_dialog(conn, host, port)) - - def _server_auth_dialog(self, conn, host, port): - dlg = QtWidgets.QDialog(self) - dlg.setWindowTitle(f"☁️ 服务器账号 - {host}:{port}") - dlg.setFixedSize(380, 330) - lay = QtWidgets.QVBoxLayout(dlg) - lay.addWidget(QtWidgets.QLabel(f"连接到 {host}:{port}")) - u = QtWidgets.QLineEdit(); u.setPlaceholderText("服务器用户名") - p = QtWidgets.QLineEdit(); p.setPlaceholderText("密码"); p.setEchoMode(QtWidgets.QLineEdit.Password) - lay.addWidget(u); lay.addWidget(p) - lab = QtWidgets.QLabel(""); lab.setStyleSheet("color:#e74c3c;") - lay.addWidget(lab) - row = QtWidgets.QHBoxLayout() - b1 = QtWidgets.QPushButton("登录"); b1.setProperty("class", "info") - b2 = QtWidgets.QPushButton("注册(服务器建号)"); b2.setProperty("class", "primary") - b3 = QtWidgets.QPushButton("取消") - row.addWidget(b1); row.addWidget(b2); row.addWidget(b3) - lay.addLayout(row) - lay.addWidget(QtWidgets.QLabel("🔐 登录成功后会自动记住,下次启动自动登录服务器")) - lay.addWidget(QtWidgets.QLabel("如需清除,删除 data\\server_cred.dat")) - - def finish(ok, err, uname, upass): - if not ok: - lab.setText(err) - return - dlg.accept() - self.server_conn = conn - self.server_addr = f"{host}:{port}" - self.server_username = conn.username - self._bind_server_conn() - self._update_title() - # 登录即自动记住服务器账号 - save_server_cred(self._get_pass_hash(), f"{host}:{port}", uname, upass) - self._on_status("🔐 已记住服务器账号,下次启动自动登录") - self._on_status(f"☁️ 已连接中央服务器 {host}:{port} (用户: {conn.username})") - self._add_system(None, f"☁️ 已连接中央服务器 {host}:{port},正在加载你的群...") - conn.list_groups() - - def do_auth(action): - uname = u.text().strip() - upass = p.text() - if not uname or not upass: - lab.setText("请输入用户名和密码") - return - b1.setEnabled(False); b2.setEnabled(False) - lab.setText("连接中... 请稍候") - - def run(): - if action == 'login': - ok, err = conn.login(uname, upass) - else: - ok, err = conn.register(uname, upass) - self._post(lambda: finish(ok, err, uname, upass)) - - threading.Thread(target=run, daemon=True).start() - - b1.clicked.connect(lambda: do_auth('login')) - b2.clicked.connect(lambda: do_auth('register')) - b3.clicked.connect(dlg.reject) - dlg.exec_() - - def _get_pass_hash(self): - """取本地账号密码哈希 (解密服务器凭据用); 缺失时查库兜底""" - ph = self.account.get('pass_hash', '') or '' - if not ph: - try: - cur = self.account_db.conn.cursor() - r = cur.execute("SELECT pass_hash FROM accounts WHERE id=?", (self.account.get('id', -1),)).fetchone() - if r: - ph = r[0] or '' - except Exception: - pass - return ph - - def _auto_connect_server(self): - """记住我的服务器账号: 自动登录 (后台线程)""" - try: - cred = load_server_cred(self._get_pass_hash()) - except Exception: - cred = None - if not cred: - return - addr, username, password = cred - try: - host, port = addr.rsplit(':', 1) - port = int(port) - except Exception: - return - threading.Thread(target=self._do_auto_connect, - args=(host, port, username, password, 3), daemon=True).start() - - def _do_auto_connect(self, host, port, username, password, attempts=3): - for attempt in range(attempts): - if self.server_conn and self.server_conn.connected: - return - conn = ServerConnection( - on_status=self._on_status, - on_groups=lambda gl: self._post(lambda: self._on_server_groups(gl)), - on_message=lambda gid, frm, pl: self._post(lambda: self._on_server_group_message(gid, frm, pl)), - on_members=lambda gid, mems: self._post(lambda: self._on_server_members(gid, mems)), - on_system=lambda gid, t: self._post(lambda: self._on_server_system(gid, t)), - on_group_name=lambda gid, n: self._post(lambda: self._on_server_group_name(gid, n)), - on_announcement=lambda gid, t: self._post(lambda: self._on_server_announcement(gid, t)), - on_group_info=lambda gid, n, a: self._post(lambda: self._on_server_group_info(gid, n, a))) - if not conn.connect(host, port): - if attempt < attempts - 1: - time.sleep(2) - continue - self._post(lambda: self._on_status("☁️ 服务器自动连接失败(重试3次),请手动「☁️服务器」登录")) - return - ok, err = conn.login(username, password) - if ok: - self._post(lambda: self._on_auto_server_logged_in(conn, host, port)) - return - if attempt < attempts - 1: - time.sleep(2) - continue - self._post(lambda: self._on_status(f"☁️ 服务器自动登录失败: {err},请手动「☁️服务器」登录")) - - def _update_title(self): - """窗口标题显示当前身份: 有服务器账号就显示服务器账号""" - if self.server_username: - self.setWindowTitle(f"{APP_NAME} - {self.server_username} ☁️服务器 [{self._my_nick()}]") - else: - self.setWindowTitle(f"{APP_NAME} - {self._my_nick()}") - - def _bind_server_conn(self): - """把已有服务器群绑定到当前连接 + 更新群内身份为服务器账号""" - for g in self.groups.values(): - if g.get('mode') == 'server': - g['server_conn'] = self.server_conn - if self.server_username: - g['my_username'] = self.server_username - self._refresh_groups() - - def _on_auto_server_logged_in(self, conn, host, port): - self.server_conn = conn - self.server_addr = f"{host}:{port}" - self.server_username = conn.username - self._bind_server_conn() - self._update_title() - self._on_status(f"☁️ 已自动登录中央服务器 {host}:{port} (用户: {conn.username})") - self._add_system(None, "☁️ 服务器自动登录成功,正在实时同步群...") - conn.list_groups() - - def _load_cached_server_groups(self): - """启动时从本地缓存显示服务器群 (离线也能看到), 连接后实时同步""" - try: - cred = load_server_cred(self._get_pass_hash()) - except Exception: - cred = None - if not cred: - return - addr = cred[0] - self.server_addr = addr # 先设服务器地址, 供密钥查找/群去重 - groups = load_server_groups_cache(addr) - if groups: - self._apply_groups_to_ui(groups) - self._on_status(f"☁️ 已从本地缓存显示 {len(groups)} 个服务器群") - - def _on_server_groups(self, groups): - """服务器实时返回群列表 → 刷新UI + 写本地缓存""" - self._apply_groups_to_ui(groups) - save_server_groups_cache(self.server_addr, groups) - self._on_status(f"☁️ 已实时同步 {len(groups)} 个服务器群") - - def _apply_groups_to_ui(self, groups): - for g in groups: - gid = g.get('id', '') - gname = g.get('name', '') or gid - owner = g.get('owner', '') - key = self._get_saved_server_key(self.server_addr, gid) - if key: - session = SecureSession() - try: - session.import_key(key) - except Exception: - session = None - if session: - if not self._server_group_exists(gid): - self._add_server_group(gid, gname, owner, session) - ex = self._gid_for_server_group(gid) - if ex: - self.groups[ex]['server_conn'] = self.server_conn - self._on_group_name(ex, gname or gid) - ann = g.get('announcement', '') - if ann: - self.groups[ex]['announcement'] = ann - if ex == self.active_gid: - self._show_banner(ann) - self._refresh_groups() - else: - self._add_system(None, f"☁️ 群 [{gname}] ({gid}) 需要密钥,点「☁️ 加群」输入群ID和密钥") - - def _server_group_exists(self, group_id): - key = f"server@{self.server_addr}@{group_id}" - return any(g['group_key'] == key for g in self.groups.values()) - - def _gid_for_server_group(self, group_id): - for gid, g in self.groups.items(): - if g.get('mode') == 'server' and g.get('group_id') == group_id: - return gid - return None - - def _add_server_group(self, group_id, group_name, owner, session): - gid = self._new_gid() - try: - srv_host = self.server_addr.split(':')[0] - srv_port = int(self.server_addr.split(':')[1]) - except Exception: - srv_host, srv_port = '127.0.0.1', 8666 - group = { - 'gid': gid, 'mode': 'server', - 'group_key': f"server@{self.server_addr}@{group_id}", - 'host': srv_host, 'port': srv_port, 'group_id': group_id, - 'server_conn': self.server_conn, - 'name': group_name or group_id, 'my_username': self.server_username or self._my_nick(), - 'my_account': self.account.get('username', ''), - 'is_host': owner == (self.server_username or self.account.get('username', '')), - 'server': None, 'client': None, 'session': session, - 'users': [], 'messages': {}, 'order': [], - 'announcement': '', 'group_name': group_name or '', 'user_key': None - } - self._register_group(gid, group) - self._save_server_group(gid) - return gid - - def _save_server_group(self, gid): - group = self.groups.get(gid) - if group: - try: - self.account_db.save_group(self.account['id'], group['group_key'], group['host'], - group['port'], group['session'].export_key(), group['name'], 0) - except Exception: - pass - - def _get_saved_server_key(self, server_addr, group_id): - gkey = f"server@{server_addr}@{group_id}" - try: - for r in self.account_db.load_groups(self.account['id']): - if r['group_key'] == gkey: - return r['session_key'] or None - except Exception: - pass - return None - - def _create_server_group(self): - if not self.server_conn or not self.server_conn.connected: - self._on_status("请先连接中央服务器 (☁️ 服务器)") - return - name, ok = QtWidgets.QInputDialog.getText(self, "☁️ 服务器建群", "群名:", text="新群") - if not ok or not name: - return - group_id = f"sg{int(time.time()*1000)}-{os.urandom(3).hex()}" - session = SecureSession(); session.generate() - self.server_conn.create_group(group_id, name) - gid = self._add_server_group(group_id, name, self.server_username, session) - self._add_system(gid, f"✅ 已在服务器创建群 [{name}]") - self._show_server_group_info(gid) # 显示并复制 群ID + 服务器 + 密钥 - self.server_conn.group_members(group_id) - - def _join_server_group(self): - if not self.server_conn or not self.server_conn.connected: - self._on_status("请先连接中央服务器 (☁️ 服务器)") - return - gid2, ok1 = QtWidgets.QInputDialog.getText(self, "☁️ 服务器加群", "群ID (创建者分享):") - if not ok1 or not gid2: - return - key, ok2 = QtWidgets.QInputDialog.getText(self, "☁️ 服务器加群", "群密钥 (创建者分享):") - if not ok2 or not key: - return - session = SecureSession() - if not session.import_key(key): - self._on_status("密钥无效!") - return - self.server_conn.join_group(gid2) - gid = self._add_server_group(gid2, gid2, '', session) - self._add_system(gid, f"✅ 已加入服务器群 [{gid2}]") - self.server_conn.group_members(gid2) - - def _on_server_group_message(self, group_id, sender, payload): - gid = self._gid_for_server_group(group_id) - if not gid or not isinstance(payload, dict): - return - kind = payload.get('kind') - if kind == 'chat': - self._on_chat(gid, sender, payload.get('text', ''), payload.get('mid', '')) - elif kind == 'file': - self._on_file(gid, {'filename': payload.get('filename', '文件'), 'size': payload.get('size', 0), - 'data': payload.get('data', ''), 'mime': payload.get('mime', 'file'), - 'mid': payload.get('mid', ''), 'ts': payload.get('ts', int(time.time())), - 'from': sender}) - elif kind == 'voice': - self._on_voice(gid, {'data': payload.get('data', ''), 'size': payload.get('size', 0), - 'mid': payload.get('mid', ''), 'ts': payload.get('ts', int(time.time())), - 'from': sender}) - elif kind == 'withdraw': - self._on_withdraw(gid, payload.get('mid', '')) - elif kind == 'read': - self._on_read(gid, payload.get('mid', '')) - - def _on_server_system(self, group_id, text): - gid = self._gid_for_server_group(group_id) - if gid: - self._add_system(gid, text) - if '加入' in text or '离开' in text: - self.server_conn.group_members(group_id) - - def _on_server_members(self, group_id, members): - for gid, g in self.groups.items(): - if g.get('mode') == 'server' and g.get('group_id') == group_id: - g['users'] = [{'name': m, 'account': m} for m in members] - if gid == self.active_gid: - self._render_users(gid) - break - - def _on_server_group_name(self, group_id, name): - gid = self._gid_for_server_group(group_id) - if gid: - self._on_group_name(gid, name) - self._add_system(gid, f"🏷️ 群名更新为: {name}") - - def _on_server_group_info(self, group_id, name, announcement): - """服务器推送的群信息(加入时): 同步群名/公告""" - gid = self._gid_for_server_group(group_id) - if not gid: - return - if name: - self._on_group_name(gid, name) - if announcement: - self._on_announcement(gid, announcement) - - def _on_server_announcement(self, group_id, text): - gid = self._gid_for_server_group(group_id) - if gid: - self._on_announcement(gid, text) - - # ---------- 消息操作 ---------- - def _on_download(self, mid): - gid = self.active_gid - group = self.groups.get(gid) - if not group: - return - msg = group['messages'].get(mid) - if not msg: - return - data = msg.get_data_bytes() - if not data: - self._on_status("文件已清理或不存在") - return - c = msg.content if isinstance(msg.content, dict) else {} - path, _ = QtWidgets.QFileDialog.getSaveFileName(self, "保存文件", os.path.join(DOWNLOAD_DIR, c.get('filename', 'download.bin'))) - if not path: - return - try: - with open(path, 'wb') as f: - f.write(data) - self._add_system(gid, f"✅ 已保存: {path}") - except Exception as e: - self._add_system(gid, f"❌ 保存失败: {e}") - - def _on_play(self, mid): - """播放语音: 优先读媒体文件; 文件缺失时回退到内存缓存, 保证点了就有声""" - gid = self.active_gid - group = self.groups.get(gid) - msg = group['messages'].get(mid) if group else None - if not msg: - self._on_status("消息不存在") - return - data = msg.get_data_bytes() - if data: - self.voice.last_voice = data - self.voice.last_voice_from = msg.sender - self.voice.play(data, msg.sender) - elif self.voice.last_voice: - # 媒体文件缺失 → 用最近一次缓存的语音 - self.voice.play(self.voice.last_voice, self.voice.last_voice_from) - self._on_status("⚠️ 媒体文件缺失,已用缓存语音播放") - else: - self._on_status("文件已清理或不存在") - - def _on_preview(self, mid): - gid = self.active_gid - group = self.groups.get(gid) - msg = group['messages'].get(mid) if group else None - if not msg: - return - data = msg.get_data_bytes() - if not data: - return - try: - from PIL import Image - img = Image.open(io.BytesIO(data)) - img.thumbnail((900, 700)) - img = img.convert("RGBA") - qimg = QtGui.QImage(img.tobytes(), img.width, img.height, QtGui.QImage.Format_RGBA8888) - pix = QtGui.QPixmap.fromImage(qimg) - dlg = QtWidgets.QDialog(self) - dlg.setWindowTitle(f"图片预览 - {msg.sender}") - lab = QtWidgets.QLabel() - lab.setPixmap(pix) - lay = QtWidgets.QVBoxLayout(dlg) - lay.addWidget(lab) - close = QtWidgets.QPushButton("关闭") - close.clicked.connect(dlg.accept) - lay.addWidget(close) - dlg.exec_() - except Exception as e: - self._on_status(f"预览失败: {e}") - - def _on_msg_selected(self, mid): - """消息列表选中/取消回调 → 同步到主窗口 (None=取消选中)""" - self.selected_mid = mid - - def _show_context_menu(self, mid, pos): - gid = self.active_gid - group = self.groups.get(gid) - if not group: - return - msg = group['messages'].get(mid) - if not msg: - return - self.selected_mid = mid - menu = QtWidgets.QMenu(self) - if msg.type == 'text': - menu.addAction("📋 复制文字", lambda: self._copy_msg(msg)) - if msg.type in ('image', 'file', 'audio', 'voice'): - menu.addAction("💾 下载", lambda: self._on_download(mid)) - if msg.type == 'image': - menu.addAction("🔍 查看原图", lambda: self._on_preview(mid)) - if msg.type in ('voice', 'audio'): - menu.addAction("▶ 播放", lambda: self._on_play(mid)) - menu.addSeparator() - if msg.is_withdrawable(): - menu.addAction("🚫 撤回", lambda: self._withdraw(mid)) - menu.addAction("📤 分享到...", lambda: self._share(mid)) - menu.exec_(pos) - - def _copy_msg(self, msg): - if msg.type == 'text': - QtWidgets.QApplication.clipboard().setText(msg.content) - self._on_status("📋 已复制文字") - - def _withdraw(self, mid): - gid = self.active_gid - group = self.groups.get(gid) - if not group: - return - msg = group['messages'].get(mid) - if not msg or not msg.is_withdrawable(): - self._on_status("只能撤回自己 2 分钟内的消息") - return - self._send_withdraw_to(group, mid) - self._delete_message(gid, mid) - self._add_system(gid, "🚫 你撤回了一条消息") - - def _share(self, mid): - gid = self.active_gid - group = self.groups.get(gid) - msg = group['messages'].get(mid) if group else None - if not msg or msg.withdrawn: - return - targets = [g for g in self.order if g != gid] - if not targets: - self._on_status("没有其他群可以分享") - return - name, ok = QtWidgets.QInputDialog.getItem(self, "📤 分享到", "选择目标群:", - [self.groups[g]['name'] for g in targets], 0, False) - if not ok: - return - g2 = targets[[self.groups[g]['name'] for g in targets].index(name)] - group2 = self.groups.get(g2) - if not group2 or not self._group_connected(group2): - self._on_status("目标群未连接") - return - mid2 = gen_mid() - if msg.type == 'text': - enc = group2['session'].encrypt(msg.content) - if self._send_chat_to(group2, enc, mid2): - self._add_local_message(g2, mid2, 'text', msg.content) - elif msg.type in ('image', 'file', 'audio'): - c = msg.content - raw = msg.get_data_bytes() - mime = 'image' if msg.type == 'image' else ('file' if msg.type == 'file' else 'audio') - enc = group2['session'].encrypt_bytes(raw) - new_path = save_media(raw, c.get('ext', '')) - content = {'filename': c.get('filename', 'file'), 'size': len(raw), 'path': new_path, 'ext': c.get('ext', '')} - if self._send_file_to(group2, content['filename'], enc.encode('utf-8'), mid2, mime): - self._add_local_message(g2, mid2, msg.type, content) - elif msg.type == 'voice': - raw = msg.get_data_bytes() - enc = group2['session'].encrypt_bytes(raw) - new_path = save_media(raw, '.wav') - content = {'filename': 'voice.wav', 'size': len(raw), 'path': new_path, 'ext': '.wav'} - if self._send_voice_to(group2, enc.encode('utf-8'), mid2): - self._add_local_message(g2, mid2, 'voice', content) - self._switch_group(g2) - self._add_system(g2, f"📤 已分享一条来自 {msg.sender} 的消息") - - - # ---------- 密钥 / 管理 / 工具 ---------- - def _show_key_dialog(self, gid): - group = self.groups.get(gid) - if not group or not group['session'].has_key(): - return - data = group['session'].export_key() - dlg = QtWidgets.QDialog(self) - dlg.setWindowTitle("🔑 会话密钥") - dlg.setFixedSize(460, 200) - lay = QtWidgets.QVBoxLayout(dlg) - lay.addWidget(QtWidgets.QLabel("复制此密钥分享给加入该群的人")) - te = QtWidgets.QTextEdit() - te.setPlainText(data) - te.setReadOnly(True) - lay.addWidget(te) - row = QtWidgets.QHBoxLayout() - b1 = QtWidgets.QPushButton("📋 复制全部") - b1.setProperty("class", "primary") - b1.clicked.connect(lambda: (QtWidgets.QApplication.clipboard().setText(data), dlg.accept())) - b2 = QtWidgets.QPushButton("关闭") - b2.clicked.connect(dlg.reject) - row.addWidget(b1); row.addWidget(b2) - lay.addLayout(row) - dlg.exec_() - - def _show_server_group_info(self, gid): - """服务器建群: 显示并复制 群ID + 服务器地址 + 群密钥 (加入需要)""" - group = self.groups.get(gid) - if not group: - return - gid2 = group.get('group_id', '') - key = group['session'].export_key() if group['session'].has_key() else '' - addr = self.server_addr or '' - - dlg = QtWidgets.QDialog(self) - dlg.setWindowTitle("☁️ 服务器群邀请信息") - dlg.setFixedSize(500, 340) - lay = QtWidgets.QVBoxLayout(dlg) - lay.addWidget(QtWidgets.QLabel("把下面 3 项分享给朋友,让他们点「☁️ 加群」输入后加入")) - - def make_row(label, value, long=False): - lay.addWidget(QtWidgets.QLabel(label)) - row = QtWidgets.QHBoxLayout() - if long: - te = QtWidgets.QTextEdit(value); te.setFixedHeight(56) - row.addWidget(te, 1) - else: - te = QtWidgets.QLineEdit(value); te.setReadOnly(True) - row.addWidget(te, 1) - btn = QtWidgets.QPushButton("📋 复制") - btn.clicked.connect(lambda: (QtWidgets.QApplication.clipboard().setText(value), dlg.accept())) - row.addWidget(btn) - lay.addLayout(row) - - make_row("🆔 群ID:", gid2) - make_row("🌐 服务器:", addr) - make_row("🔑 群密钥:", key, long=True) - lay.addWidget(QtWidgets.QLabel("⚠️ 密钥请私下发给成员,勿在公开渠道泄露")) - close = QtWidgets.QPushButton("关闭") - close.clicked.connect(dlg.reject) - lay.addWidget(close) - dlg.exec_() - - def _copy_active_key(self): - gid, group = self._current_group() - if group and group['session'].has_key(): - QtWidgets.QApplication.clipboard().setText(group['session'].export_key()) - self._on_status(f"🔑 已复制「{group['name']}」的密钥") - else: - self._on_status("请先选择一个群") - - def _rename(self): - nick, ok = QtWidgets.QInputDialog.getText(self, "改名", "新昵称:", text=self._my_nick()) - if not ok or not nick: - return - nick = nick[:20] - try: - self.account_db.update_nickname(self.account['id'], nick) - except Exception: - pass - self.account = dict(self.account) - self.account['nickname'] = nick - for gid in list(self.order): - g = self.groups[gid] - g['my_username'] = nick - if g.get('mode') == 'server': - pass - elif g.get('client'): - g['client'].send_rename(nick) - self._add_system(gid, f"✏️ 你已改名为 {nick}") - self._refresh_groups() - self._render_users(self.active_gid) - self._on_status(f"✅ 已改名为 {nick}") - - def _set_announcement(self): - gid, group = self._current_group() - if not group: - return - if not group['is_host']: - self._on_status("仅群主可设置公告") - return - text, ok = QtWidgets.QInputDialog.getText(self, "群公告", "输入公告内容:", text=group.get('announcement', '')) - if not ok: - return - if group.get('mode') == 'server': - group['server_conn'].set_announcement(group['group_id'], text) - elif group.get('client'): - group['client'].send_announcement(text) - group['announcement'] = text - if gid == self.active_gid: - self._show_banner(text) - - def _set_group_name(self): - gid, group = self._current_group() - if not group: - return - if not group['is_host']: - self._on_status("仅群主可设置群名") - return - cur = group.get('group_name', '') or group.get('group_id', '') - name, ok = QtWidgets.QInputDialog.getText(self, "群名", "输入群名:", text=cur) - if not ok or not name: - return - if group.get('mode') == 'server': - group['server_conn'].set_group_name(group['group_id'], name) - elif group.get('client'): - group['client'].send_set_group_name(name) - self._on_group_name(gid, name) - - def _withdraw_selected(self): - if self.selected_mid: - self._withdraw(self.selected_mid) - else: - self._on_status("请先点击选择一条消息") - - def _share_selected(self): - if self.selected_mid: - self._share(self.selected_mid) - else: - self._on_status("请先点击选择一条消息") - - def _download_selected(self): - if self.selected_mid: - self._on_download(self.selected_mid) - else: - self._on_status("请先点击选择一条消息") - - def _copy_selected(self): - gid = self.active_gid - group = self.groups.get(gid) - msg = group['messages'].get(self.selected_mid) if group and self.selected_mid else None - if msg: - self._copy_msg(msg) - else: - self._on_status("请先点击选择一条消息") - - def _leave_active_group(self): - if self.active_gid: - self._leave_group(self.active_gid) - - def _leave_group(self, gid): - group = self.groups.get(gid) - if not group: - return - if group.get('mode') == 'server': - try: - group['server_conn'].leave_group(group['group_id']) - except Exception: - pass - else: - try: - group['client'].disconnect() - except Exception: - pass - if group['server']: - try: - group['server'].stop() - except Exception: - pass - if gid in self.order: - self.order.remove(gid) - del self.groups[gid] - try: - self.account_db.remove_group(self.account['id'], group['group_key']) - except Exception: - pass - if self.active_gid == gid: - self.active_gid = self.order[-1] if self.order else None - self._render_group(self.active_gid) - self._refresh_groups() - - def _on_group_menu(self, pos): - item = self.group_list.itemAt(pos) - if not item: - return - gid = item.data(QtCore.Qt.UserRole) - menu = QtWidgets.QMenu(self) - menu.addAction("🔑 复制密钥", lambda: self._copy_group_key(gid)) - menu.addAction("💾 导出密钥文件", lambda: self._save_key_file(gid)) - menu.addAction("📤 分享密钥到其他群", lambda: self._share_key_to(gid)) - menu.addAction("📋 群属性", lambda: self._group_properties(gid)) - menu.addSeparator() - menu.addAction("切换到此群", lambda: self._switch_group(gid)) - menu.addAction("❌ 离开该群", lambda: self._leave_group(gid)) - menu.exec_(self.group_list.mapToGlobal(pos)) - - def _copy_group_key(self, gid): - group = self.groups.get(gid) - if group and group['session'].has_key(): - QtWidgets.QApplication.clipboard().setText(group['session'].export_key()) - self._on_status(f"🔑 已复制「{group['name']}」的密钥") - - def _save_key_file(self, gid): - group = self.groups.get(gid) - if not group or not group['session'].has_key(): - return - data = group['session'].export_key() - path, _ = QtWidgets.QFileDialog.getSaveFileName(self, "导出密钥", f"群密钥_{gid}.txt", "文本 (*.txt)") - if not path: - return - try: - with open(path, 'w', encoding='utf-8') as f: - f.write(data) - self._on_status(f"✅ 密钥已导出: {path}") - except Exception as e: - self._on_status(f"❌ 导出失败: {e}") - - def _share_key_to(self, gid): - group = self.groups.get(gid) - if not group or not group['session'].has_key(): - return - data = group['session'].export_key() - targets = [g for g in self.order if g != gid] - if not targets: - self._on_status("没有其他群可以分享") - return - name, ok = QtWidgets.QInputDialog.getItem(self, "📤 分享密钥到", "选择目标群:", - [self.groups[g]['name'] for g in targets], 0, False) - if not ok: - return - g2 = targets[[self.groups[g]['name'] for g in targets].index(name)] - QtWidgets.QApplication.clipboard().setText(data) - self._switch_group(g2) - self._add_system(g2, f"📤 已复制「{group['name']}」的密钥,可粘贴给群成员加入该群") - - def _group_properties(self, gid): - group = self.groups.get(gid) - if not group: - return - mode = group.get('mode', 'p2p') - mode_text = '🔗 端到端 (P2P)' if mode != 'server' else '☁️ 中央服务器' - gid_field = group.get('group_id', '(无)') if mode == 'server' else '(无)' - status = '🟢 在线' if self._group_connected(group) else '🔴 离线' - info = (f"📋 群名: {group.get('group_name', '') or group['name']}\n" - f"🏷️ 类型: {mode_text}\n" - f"🆔 群ID: {gid_field}\n" - f"🌐 地址: {group['host']}:{group['port']}\n" - f"📡 状态: {status}\n" - f"👑 身份: {'是 [群主]' if group['is_host'] else '否 [成员]'}\n" - f"🔑 加密: {'✅ 已加密' if group['session'].has_key() else '❌ 无密钥'}\n" - f"👥 成员: {len(group['users'])} 人") - QtWidgets.QMessageBox.information(self, "📋 群属性", info) - - def _on_user_menu(self, pos): - gid, group = self._current_group() - if not group: - return - item = self.users_list.itemAt(pos) - if not item: - return - if group.get('mode') == 'server': - self._on_status("服务器群由服务器管理成员") - return - if not group['is_host']: - self._on_status("仅群主可管理用户") - return - idx = self.users_list.row(item) - if idx < 0 or idx >= len(group['users']): - return - target = group['users'][idx] - if target.get('account') == self.account.get('username', ''): - return - if QtWidgets.QMessageBox.question(self, "踢人", f"确定将 {target.get('name','')} 移出群吗?", - QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No) == QtWidgets.QMessageBox.Yes: - group['client'].send_kick(target.get('account', '')) - - def _clear_media_cache(self): - if QtWidgets.QMessageBox.question(self, "清理媒体缓存", - "将删除「文档/ChaosChat/media」中所有文件/图片/语音,历史记录中的这些文件将无法打开。确定?", - QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No) == QtWidgets.QMessageBox.Yes: - n = clear_media_cache() - self._on_status(f"🗑️ 已清理 {n} 个媒体文件") - - def _open_download_dir(self): - try: - os.startfile(DOWNLOAD_DIR) - except Exception: - pass - - # ---------- 自动加入 ---------- - def _start_auto_join(self): - threading.Thread(target=self._auto_join_worker, daemon=True).start() - - def _auto_join_worker(self): - try: - rows = self.account_db.load_groups(self.account['id']) - except Exception: - rows = [] - for r in rows: - if r['group_key'] and str(r['group_key']).startswith('server@'): - continue - self._auto_join_one(r) - - def _auto_join_one(self, r, attempts=3): - host, port = r['host'], r['port'] - key = f"{host}:{port}" - for g in list(self.groups.values()): - if g['group_key'] == key and self._group_connected(g): - return - session = SecureSession() - try: - session.import_key(r['session_key']) - except Exception: - pass - gid = self._new_gid() - for attempt in range(attempts): - server = None - if r['is_host']: - server = ChatServer(on_status=lambda t: self._post(lambda: self._on_status(t)), - server_key=key, server_db=self.server_db, - server_secret=session.session_key) - if not server.start(port): - server = None - if attempt < attempts - 1: - time.sleep(2) - continue - return - client = self._make_client(gid) - saved_uk = r['user_key'] if 'user_key' in r.keys() else None - ok = client.connect(host, port, self._my_nick(), nickname=self._my_nick(), - account=self.account.get('username', ''), - auth_secret=session.auth_secret(), user_key=saved_uk, - user_key_enc=session.user_key_enc()) - if ok: - group = self._build_group(gid, host, port, self._my_nick(), - bool(r['is_host']), server, client, session) - group['user_key'] = saved_uk - self._post(lambda gid=gid, group=group: self._register_group(gid, group)) - return - if server: - try: - server.stop() - except Exception: - pass - if attempt < attempts - 1: - time.sleep(2) - - # ---------- 退出 ---------- - def _logout(self): - clear_session() - self._relogin = True - self._close_all() - - def _quit(self): - self._relogin = False - self._close_all() - - def _close_all(self): - try: - if self.server_conn: - self.server_conn.disconnect() - except Exception: - pass - for gid in list(self.order): - g = self.groups.get(gid) - if g: - try: - if g.get('client'): - g['client'].disconnect() - except Exception: - pass - if g.get('server'): - try: - g['server'].stop() - except Exception: - pass - try: - self.history.conn.close() - except Exception: - pass - try: - self.account_db.conn.close() - except Exception: - pass - self.close() - - def closeEvent(self, event): - self._close_all() - event.accept() - - -# ==================== 主入口 ==================== -def main(): - import sys - app = QtWidgets.QApplication(sys.argv) - app.setStyleSheet(QSS) - db = AccountDB() - - # 自动登录 (记住我) - account = None - token = load_session() - if token: - account = db.validate_session(token) - if account: - print(f"✅ 自动登录: {account['username']}") - - if account is None: - login = LoginDialog(db) - if login.exec_() != QtWidgets.QDialog.Accepted: - return - account = login.result - # 本地登录不强制记住; 保持简单 - token = db.create_session(account['id']) - save_session(token) - - win = MainWindow(account) - win.show() - app.exec_() - - -if __name__ == "__main__": - main() diff --git a/ChaosCryptChat/server.py b/ChaosCryptChat/server.py deleted file mode 100644 index 6318737..0000000 --- a/ChaosCryptChat/server.py +++ /dev/null @@ -1,418 +0,0 @@ -# -*- coding: utf-8 -*- -""" -☁️ 混沌加密聊天 - 中央服务器 (解决 NAT / 公网穿透) -==================================================== -- 服务器只负责: 用户认证 + 群成员管理 + 消息中继 -- 所有消息内容由客户端加密, 服务器【不持有群密钥】 -- 密钥只在客户端本地, 永不上传到服务器 -- 部署: 放到有公网IP的机器, python server.py [端口] -""" -import os -import sys -import json -import time -import base64 -import struct -import socket -import hashlib -import threading -import sqlite3 - -SERVER_HOST = '0.0.0.0' -SERVER_PORT = 8666 -DB_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'server_data', 'server.db') - -MAX_FRAME = 256 * 1024 * 1024 - - -# ==================== 帧协议 (与客户端一致) ==================== -def send_msg(sock, obj): - payload = json.dumps(obj, ensure_ascii=False).encode('utf-8') - sock.sendall(struct.pack('>I', len(payload)) + payload) - - -def recv_exact(sock, n): - data = b'' - while len(data) < n: - try: - chunk = sock.recv(n - len(data)) - except socket.timeout: - continue - except Exception: - return None - if not chunk: - return None - data += chunk - return data - - -def recv_msg(sock): - header = recv_exact(sock, 4) - if header is None: - return None - length = struct.unpack('>I', header)[0] - if length <= 0 or length > MAX_FRAME: - return None - payload = recv_exact(sock, length) - if payload is None: - return None - try: - return json.loads(payload.decode('utf-8')) - except Exception: - return None - - -# ==================== 服务器数据库 ==================== -class ServerDB: - def __init__(self, db_path=DB_PATH): - os.makedirs(os.path.dirname(db_path), exist_ok=True) - self.conn = sqlite3.connect(db_path, check_same_thread=False) - self.conn.row_factory = sqlite3.Row - self.lock = threading.Lock() - self._init() - - def _init(self): - with self.lock: - cur = self.conn.cursor() - cur.execute('''CREATE TABLE IF NOT EXISTS users( - id INTEGER PRIMARY KEY AUTOINCREMENT, - username TEXT UNIQUE NOT NULL, - salt TEXT NOT NULL, - pass_hash TEXT NOT NULL, - created_at REAL)''') - cur.execute('''CREATE TABLE IF NOT EXISTS groups( - id TEXT PRIMARY KEY, - owner TEXT NOT NULL, - name TEXT, - announcement TEXT, - created_at REAL)''') - cur.execute('''CREATE TABLE IF NOT EXISTS group_members( - group_id TEXT NOT NULL, - username TEXT NOT NULL, - joined_at REAL, - PRIMARY KEY(group_id, username))''') - self.conn.commit() - - def register(self, username, password): - salt = os.urandom(16).hex() - ph = hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), - bytes.fromhex(salt), 120000).hex() - try: - with self.lock: - cur = self.conn.cursor() - cur.execute('INSERT INTO users(username, salt, pass_hash, created_at) VALUES(?,?,?,?)', - (username, salt, ph, time.time())) - self.conn.commit() - return True, 'ok' - except sqlite3.IntegrityError: - return False, '该用户名已被注册' - - def login(self, username, password): - with self.lock: - cur = self.conn.cursor() - row = cur.execute('SELECT * FROM users WHERE username=?', (username,)).fetchone() - if row is None: - return None, '用户不存在' - ph = hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), - bytes.fromhex(row['salt']), 120000).hex() - if ph != row['pass_hash']: - return None, '密码错误' - return row, 'ok' - - def create_group(self, group_id, owner, name): - with self.lock: - cur = self.conn.cursor() - cur.execute('INSERT INTO groups(id, owner, name, created_at) VALUES(?,?,?,?)', - (group_id, owner, name, time.time())) - cur.execute('INSERT OR IGNORE INTO group_members(group_id, username, joined_at) VALUES(?,?,?)', - (group_id, owner, time.time())) - self.conn.commit() - - def add_member(self, group_id, username): - with self.lock: - cur = self.conn.cursor() - row = cur.execute('SELECT 1 FROM groups WHERE id=?', (group_id,)).fetchone() - if row is None: - return False - cur.execute('INSERT OR IGNORE INTO group_members(group_id, username, joined_at) VALUES(?,?,?)', - (group_id, username, time.time())) - self.conn.commit() - return True - - def remove_member(self, group_id, username): - with self.lock: - cur = self.conn.cursor() - cur.execute('DELETE FROM group_members WHERE group_id=? AND username=?', - (group_id, username)) - self.conn.commit() - - def get_group(self, group_id): - with self.lock: - cur = self.conn.cursor() - return cur.execute('SELECT id, name, announcement, owner FROM groups WHERE id=?', - (group_id,)).fetchone() - - def list_groups(self, username): - with self.lock: - cur = self.conn.cursor() - rows = cur.execute('''SELECT g.id, g.name, g.owner, g.announcement FROM groups g - JOIN group_members m ON m.group_id = g.id - WHERE m.username=?''', (username,)).fetchall() - return [{'id': r['id'], 'name': r['name'], 'owner': r['owner'], - 'announcement': r['announcement'] or ''} for r in rows] - - def is_owner(self, group_id, username): - with self.lock: - cur = self.conn.cursor() - row = cur.execute('SELECT owner FROM groups WHERE id=?', (group_id,)).fetchone() - return bool(row and row['owner'] == username) - - def set_group_name(self, group_id, name): - with self.lock: - cur = self.conn.cursor() - cur.execute('UPDATE groups SET name=? WHERE id=?', (name, group_id)) - self.conn.commit() - - def set_announcement(self, group_id, text): - with self.lock: - cur = self.conn.cursor() - cur.execute('UPDATE groups SET announcement=? WHERE id=?', (text, group_id)) - self.conn.commit() - - def members(self, group_id): - with self.lock: - cur = self.conn.cursor() - rows = cur.execute('SELECT username FROM group_members WHERE group_id=?', - (group_id,)).fetchall() - return [r['username'] for r in rows] - - -# ==================== 中央服务器 ==================== -class CentralServer: - def __init__(self, host=SERVER_HOST, port=SERVER_PORT, db=None): - self.host = host - self.port = port - self.db = db or ServerDB() - self.sock = None - self.running = False - self.clients = {} # cid -> {socket, username, token, addr, lock} - self.next_id = 1 - self.lock = threading.Lock() - - def start(self): - self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - self.sock.bind((self.host, self.port)) - self.sock.listen(50) - self.running = True - print(f"☁️ 中央服务器启动: {self.host}:{self.port}") - print(f" 数据库: {DB_PATH}") - threading.Thread(target=self._accept_loop, daemon=True).start() - - def stop(self): - self.running = False - if self.sock: - try: - self.sock.close() - except Exception: - pass - self.sock = None - with self.lock: - socks = [c['socket'] for c in self.clients.values()] - self.clients.clear() - for s in socks: - try: - s.close() - except Exception: - pass - - def _accept_loop(self): - while self.running: - try: - client, addr = self.sock.accept() - with self.lock: - cid = self.next_id - self.next_id += 1 - self.clients[cid] = {'socket': client, 'username': None, - 'token': None, 'addr': addr, - 'lock': threading.Lock()} - print(f" 📶 新连接: {addr[0]}:{addr[1]}") - threading.Thread(target=self._handler, args=(cid,), daemon=True).start() - except Exception: - break - - def _send(self, cid, msg): - with self.lock: - c = self.clients.get(cid) - if c: - try: - with c['lock']: - send_msg(c['socket'], msg) - except Exception: - pass - - def _handler(self, cid): - client = self.clients[cid]['socket'] - # 第一步: 认证 (register 自动登录 或 login) - try: - msg = recv_msg(client) - if msg and msg.get('type') == 'register': - username = str(msg.get('username', ''))[:24] - password = str(msg.get('password', '')) - ok, err = self.db.register(username, password) - if not ok: - self._send(cid, {'type': 'error', 'msg': err}) - self._remove(cid) - return - row, _ = self.db.login(username, password) - self._auth_ok(cid, row) - elif msg and msg.get('type') == 'login': - username = str(msg.get('username', ''))[:24] - password = str(msg.get('password', '')) - row, err = self.db.login(username, password) - if row is None: - self._send(cid, {'type': 'error', 'msg': err}) - self._remove(cid) - return - self._auth_ok(cid, row) - else: - self._remove(cid) - return - except Exception: - self._remove(cid) - return - - # 第二步: 业务消息循环 - while self.running: - if cid not in self.clients: - break - try: - msg = recv_msg(client) - if msg is None: - break - self._handle(cid, msg) - except Exception: - break - self._remove(cid) - - def _auth_ok(self, cid, row): - username = row['username'] - token = os.urandom(16).hex() - with self.lock: - if cid in self.clients: - self.clients[cid]['username'] = username - self.clients[cid]['token'] = token - print(f" 👤 {username} 已登录") - self._send(cid, {'type': 'login_ok', 'token': token, 'username': username}) - - def _handle(self, cid, msg): - with self.lock: - if cid not in self.clients: - return - username = self.clients[cid]['username'] - mtype = msg.get('type') - - if mtype == 'create_group': - group_id = str(msg.get('group_id') or f"g{int(time.time()*1000)}-{os.urandom(3).hex()}") - name = str(msg.get('name', ''))[:40] - self.db.create_group(group_id, username, name or group_id) - print(f" 📡 {username} 创建群 [{name}] ({group_id})") - self._send(cid, {'type': 'group_created', 'group_id': group_id, 'name': name}) - - elif mtype == 'list_groups': - groups = self.db.list_groups(username) - self._send(cid, {'type': 'groups', 'groups': groups}) - - elif mtype == 'join_group': - group_id = str(msg.get('group_id', '')) - if self.db.add_member(group_id, username): - self._send(cid, {'type': 'join_ok', 'group_id': group_id}) - # 推送当前群名/公告给新成员 - ginfo = self.db.get_group(group_id) - self._send(cid, {'type': 'group_info', 'group_id': group_id, - 'name': ginfo['name'] if ginfo else '', - 'announcement': ginfo['announcement'] if ginfo else ''}) - self._broadcast_group(group_id, - {'type': 'system', 'text': f"👋 {username} 加入了群", - 'group_id': group_id}, exclude=cid) - else: - self._send(cid, {'type': 'error', 'msg': '群不存在'}) - - elif mtype == 'set_group_name': - group_id = str(msg.get('group_id', '')) - name = str(msg.get('name', ''))[:40] - if self.db.is_owner(group_id, username): - self.db.set_group_name(group_id, name) - self._broadcast_group(group_id, {'type': 'group_name', 'group_id': group_id, - 'name': name}, exclude=None) - print(f" 🏷️ {username} 修改群名: {name}") - else: - self._send(cid, {'type': 'error', 'msg': '仅群主可修改群名'}) - - elif mtype == 'set_announcement': - group_id = str(msg.get('group_id', '')) - text = str(msg.get('text', ''))[:500] - if self.db.is_owner(group_id, username): - self.db.set_announcement(group_id, text) - self._broadcast_group(group_id, {'type': 'announcement', 'group_id': group_id, - 'text': text}, exclude=None) - print(f" 📢 {username} 设置公告: {text[:30]}") - else: - self._send(cid, {'type': 'error', 'msg': '仅群主可设置公告'}) - - elif mtype == 'leave_group': - group_id = str(msg.get('group_id', '')) - self.db.remove_member(group_id, username) - self._send(cid, {'type': 'leave_ok', 'group_id': group_id}) - self._broadcast_group(group_id, - {'type': 'system', 'text': f"👋 {username} 离开了群", - 'group_id': group_id}, exclude=cid) - - elif mtype == 'group_members': - group_id = str(msg.get('group_id', '')) - self._send(cid, {'type': 'members', 'group_id': group_id, - 'members': self.db.members(group_id)}) - - elif mtype == 'group_message': - group_id = str(msg.get('group_id', '')) - payload = msg.get('payload') - # 转发给同群其他成员 (服务器不解析加密内容) - self._broadcast_group(group_id, - {'type': 'group_message', 'group_id': group_id, - 'from': username, 'payload': payload}, exclude=cid) - - def _broadcast_group(self, group_id, msg, exclude=None): - members = set(self.db.members(group_id)) - with self.lock: - targets = [(cid2, c['socket'], c['lock']) for cid2, c in self.clients.items() - if c.get('username') in members and cid2 != exclude] - for cid2, sock, lk in targets: - try: - with lk: - send_msg(sock, msg) - except Exception: - pass - - def _remove(self, cid): - with self.lock: - entry = self.clients.pop(cid, None) - if entry: - try: - entry['socket'].close() - except Exception: - pass - if entry['username']: - print(f" 🔌 {entry['username']} 断开") - - -if __name__ == '__main__': - port = int(sys.argv[1]) if len(sys.argv) > 1 else SERVER_PORT - srv = CentralServer(port=port) - srv.start() - print("按 Ctrl+C 停止服务器") - try: - while True: - time.sleep(1) - except KeyboardInterrupt: - srv.stop() - print("\n☁️ 服务器已停止") diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..181fa5b --- /dev/null +++ b/LICENSE @@ -0,0 +1,41 @@ +MIT License + +Copyright (c) 2026 Dvs (DvsXT) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +--------------------------------------------------------------------------- + +ADDITIONAL SECURITY NOTICE / 附加安全声明 + +ChaosCrypt is NOT an audited cryptographic algorithm and is NOT a standard +(AES / ChaCha20 / RSA class) cipher. It may contain unknown weaknesses. + +It is intended ONLY for: + 1. Obfuscation encryption + 2. Personal use + 3. Research and teaching + +DO NOT use it in real products. The authors accept NO responsibility or +liability for any accident, data loss, or damage caused by misuse of this +software in production or safety-critical systems. + +ChaosCrypt 未经审计,不是标准密码学算法,可能存在未知风险。 +仅限用于:混淆式加密、个人自用、研究教学。 +请勿用于真实产品。因擅自用于真实产品导致的任何事故,开发者不承担责任。 diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..a769dc8 --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,26 @@ +# Files included in the source distribution. +# +# Note: the development directories (tests/, examples/, legacy/) are +# deliberately NOT listed here. They sit inside the package directory in the +# source tree, and MANIFEST.in entries under a package path are treated as +# package data, which would place them in the wheel as well. The source tree +# itself is the distribution for development purposes; the sdist carries the +# library and its documentation. + +include README.md +include LICENSE +include SECURITY.md +include CHANGELOG.md +include pyproject.toml +include .gitignore + +recursive-include docs *.md + +# The installable package. +include chaoscrypt/*.py +include chaoscrypt/py.typed + +global-exclude *.py[cod] +global-exclude __pycache__/* +global-exclude .DS_Store +global-exclude *.key diff --git a/README.md b/README.md index e263d3a..d00d747 100644 --- a/README.md +++ b/README.md @@ -1,1008 +1,433 @@ -\# 🔐 ChaosCrypt - 混沌加密系统(v2.0) +# ChaosCrypt +**A chaos-based obfuscation cipher with a bilingual TUI, a full CLI, and a clean Python API.** +[![Python](https://img.shields.io/badge/python-3.8%2B-blue)](https://www.python.org/) +[![License](https://img.shields.io/badge/license-MIT-green)](LICENSE) +[![Dependencies](https://img.shields.io/badge/dependencies-none-brightgreen)](#installation) -> \*\*一个完全自主设计的、抗量子、抗数学攻击的对称加密系统\*\* +--- -> \*不依赖 NIST、不依赖椭圆曲线、不依赖质数分解——只依赖随机性本身\* +## Scope -> \*\*v2.0 新增 💬 ChaosCryptChat:基于混沌加密的端到端加密聊天系统(文本/图片/文件/语音)\*\* +ChaosCrypt is an **unaudited, non-standardised** cipher. It is built for three +purposes: +| | Purpose | What it means in practice | +|---|---|---| +| 1 | **Obfuscation** | Making data unreadable to casual inspection | +| 2 | **Personal use** | Protecting your own notes, journals and backups | +| 3 | **Research & teaching** | Studying how layered obfuscation behaves | +**If you need standardised cryptography, use a standardised cipher.** AES-GCM +or ChaCha20-Poly1305 from a vetted library such as +[`cryptography`](https://cryptography.io) are the right tools for production +systems, regulated data, and long-lived secrets. ChaosCrypt is not a +replacement for them and does not claim to be. -\--- +See [SECURITY.md](SECURITY.md) for the complete design description, key-space +derivation, and attack analysis. +--- +## Why it is worth a look -\## 📖 目录 - - - -1\. \[项目简介](#项目简介) - -2\. \[设计哲学](#设计哲学) - -3\. \[核心特性](#核心特性) - -4\. \[加密流程详解](#加密流程详解) - -5\. \[安全性分析](#安全性分析) - -6\. \[为什么这玩意儿真的安全?(不服来辩版)](#为什么这玩意儿真的安全不服来辩版) - -7\. \[快速开始](#快速开始) - -8\. \[使用指南](#使用指南) - -9\. \[API 参考](#api-参考) - -10\. \[常见问题](#常见问题) - -11\. \[💬 ChaosCryptChat 混沌加密聊天](#-chaoscryptchat-混沌加密聊天) - -12\. \[项目结构](#项目结构) - -13\. \[免责声明](#免责声明) - - - -\--- - - - -\## 项目简介 - - - -\*\*ChaosCrypt\*\* 是一个完全自主设计的对称加密系统。它不依赖任何第三方加密库(仅使用 `base64` 做数据编码),全部加密逻辑均为原创。 - - - -\*\*核心思想\*\*:用\*\*随机性\*\*替代\*\*数学结构\*\*,用\*\*多层乱序\*\*替代\*\*代数方程\*\*,用\*\*超大密钥空间\*\*彻底扼杀暴力破解。 - - - -> 这不是对现有加密算法的改进,而是对"安全"这个概念的重新定义。 - -\*\*v2.0 新增\*\*:在混沌加密内核之上构建了 \*\*ChaosCryptChat\*\* 端到端加密聊天系统,让混沌加密真正走进实时通信场景。 - - - -\--- - - - -\## 设计哲学 - - - -当今加密世界有一个默认共识:\*\*"只有 NIST 认证的、数学优美的、学术界验证过的算法才算安全"\*\*。 - - - -ChaosCrypt 对此表示: - - - -> \*\*"你们说的都对,但我不信。"\*\* - - - -\- \*\*Dual\_EC\_DRBG\*\* 事件还历历在目——NIST 标准,NSA 后门,全世界被蒙在鼓里好几年。 - -\- \*\*RSA\*\* 数学优美吧?标准吧?\*\*Shor 一来直接秒死。\*\* - -\- \*\*AES\*\* 结构清晰吧?S‑Box 有理有据吧?\*\*Grover 直接给你开根号加速。\*\* - - - -\*\*ChaosCrypt 选择另一条路:\*\* - - - -> \*\*不要数学结构,不要可解释性,不要任何人给你背书。\*\* - -> \*\*你唯一能做的只有暴力枚举——而枚举空间大到宇宙都装不下。\*\* - - - -\--- - - - -\## 核心特性 - - - -| 特性 | 说明 | - -|------|------| - -| 🔑 \*\*双因素保护\*\* | 系统密钥文件 (`.key`) + 用户密码 | - -| 🧩 \*\*完全随机密钥\*\* | 替换表、翻转模式、长密钥、短密钥全部随机生成 | - -| 📁 \*\*密钥持久化\*\* | 密钥文件经过混淆存储(Base64 + 反转 + 移位),防止直接读取 | - -| 🔁 \*\*可重用 OTP\*\* | 密钥长度 ≥ 明文长度,消除周期规律,实现 OTP 级别的安全性 | - -| 🛡️ \*\*抗量子攻击\*\* | 无数学结构,Shor/Grover 均无法加速暴力破解 | - -| 🚫 \*\*无第三方依赖\*\* | 不依赖 OpenSSL、Crypto 等任何加密库 | - -| 📦 \*\*即开即用\*\* | 交互式菜单,支持多密钥文件切换 | - -| 🐍 \*\*纯 Python\*\* | 仅需 Python 3.6+,零额外依赖 | - -| 💬 \*\*加密聊天(v2.0)\*\* | ChaosCryptChat 端到端加密聊天:文本/图片/文件/语音,P2P + 中央服务器双模式 | - - - -\--- - - - -\## 加密流程详解 +The absence of an audit says nothing about the strength of the construction. +ChaosCrypt is deliberately built to remove every kind of structure that +classical cryptanalysis relies on, and the result is a design with real +substance behind it: +**A key space of roughly 10^5621.** The system key is the product of two +independent 26-letter bijections, a 10-into-62 injection, an ordered selection +of 4 padding symbols, a 10-bit flip pattern, a 4096-nibble long key and a +512-nibble short key. For comparison: AES-256 offers about 10^77, and the +observable universe contains about 10^80 atoms. +**Five layers, each removing a different class of structure.** ``` - -明文 - - ↓ - -① Base64 编码 - - ↓ - -② 随机替换表(大小写各26字母完全打乱) - - ↓ - -③ 大小写翻转(10位随机模式) - - ↓ - -④ 字符串反转 - - ↓ - -⑤ 动态异或(4096位长密钥) - - ↓ - -⑥ 最终异或(用户密码 + 512位短密钥 派生) - - ↓ - -密文(十六进制) - +plaintext + | Base64 lift arbitrary bytes into printable ASCII + | substitution destroy frequency structure + | conditional case flip remove linearity + | whole-message reversal destroy locality + | XOR with long key erase residual substituted structure + | XOR with derived key sever any link to the key file alone +ciphertext ``` +**No algebraic structure to attack.** The substitution tables are arbitrary +permutations stored as data, so there is no polynomial representation. +Differential, linear and algebraic cryptanalysis all require a compact +algebraic description that simply does not exist here. +**No number-theoretic structure either.** There is no modular arithmetic, no +group operation and no lattice, so Shor's algorithm has nothing to solve. +Grover's algorithm reduces the search to about 10^2810 — still far beyond any +physically realisable computation. -每一步使用的随机参数都来自 `.key` 文件,用户密码仅参与最后一步的密钥派生。 +**The two XOR layers shield each other.** An attacker who recovers the outer +keystream still faces the 4096-nibble long key, and no keystream recovered +from one message is reusable against another, because the derivation is +parameterised by message length. +**Lossless for arbitrary binary data.** Every stage is a bijection, so images, +archives and database dumps round-trip byte-for-byte. Verified in the test +suite from 0 to 100,000 bytes, including NUL bytes and invalid UTF-8. +**Zero third-party runtime dependencies.** Pure standard library. Nothing to +audit in your dependency tree, nothing to break on upgrade, and `pip install` +is immediately usable. -\### 密钥派生流程 +**A real interface.** A bilingual interactive TUI for interactive use, a +complete argument-driven CLI for automation, and a typed Python API for +embedding — all three backed by the same sixteen-code error hierarchy. +--- - -``` - -用户密码 + short\_key (512位) - - ↓ - -交替穿插 → 位运算混合 → 分组置换 → 反转 - - ↓ - -扩展至目标长度(三种变换模式循环) - - ↓ - -最终密钥(长度 >= 明文) - -``` - - - -\--- - - - -\## 安全性分析 - - - -\### 1. 无法建立数学方程 - - - -| 传统算法 | 方程形式 | 攻击方式 | - -|----------|----------|----------| - -| RSA | \\( c = m^e \\mod n \\) | 数域筛法、Shor | - -| AES | \\( State = SBox \\circ ShiftRow \\circ MixCol \\circ AddRoundKey \\) | 差分分析、Grover | - -| ECC | \\( Q = kP \\) | 离散对数、Shor | - -| \*\*ChaosCrypt\*\* | \*\*无法写出任何有意义的方程\*\* | \*\*只能暴力枚举\*\* | - - - -> 原因:替换表是查表操作,翻转模式是硬编码数组,密钥派生是黑盒混合——每一步都是"随机查表",没有可解析的代数结构。 - - - -\### 2. 密钥空间(暴力破解难度) - - - -| 组件 | 空间大小 | 数值 | - -|------|----------|------| - -| `upper\_mapping` | 26! | \~10²⁶ | - -| `lower\_mapping` | 26! | \~10²⁶ | - -| `digit\_mapping` | \~10! × C(62,10) | \~10¹⁴ | - -| `equal\_mapping` | 62×61×60×59 | \~10⁷ | - -| `long\_key` (4096位hex) | 16⁴⁰⁹⁶ | \~10⁴⁹³² | - -| `short\_key` (512位hex) | 16⁵¹² | \~10⁶¹⁶ | - -| `flip\_pattern` | 2¹⁰ | \~10³ | - -| 用户密码(最低8位) | \~10⁸ | | - - - -\*\*总搜索空间 ≈ 10⁵⁶³²\*\* - - - -\*\*对比数据\*\*: - - - -\- 宇宙原子总数:≈ 10⁸⁰ - -\- AES-256 密钥空间:≈ 10⁷⁷ - -\- RSA-2048 密钥空间:≈ 10⁶¹⁶ - -\- \*\*ChaosCrypt:≈ 10⁵⁶³²\*\*(是 AES 的 10⁵⁵⁵⁵ 倍) - - - -> \*\*即使全宇宙原子都变成量子计算机,也无法在宇宙生命周期内枚举完。\*\* - - - -\### 3. 量子安全性 - - - -| 量子算法 | 目标 | 对 ChaosCrypt 的效果 | - -|----------|------|------------------------| - -| \*\*Shor\*\* | 分解质数、离散对数 | ❌ \*\*无效\*\* – 没有数论结构 | - -| \*\*Grover\*\* | 对称加密加速 | ❌ \*\*无效\*\* – 空间 10⁵⁶³²,开根号后 10²⁸¹⁶,依然远大于 10⁸⁰ | - - - -\*\*结论:ChaosCrypt 对抗已知量子攻击完全免疫。\*\* - - - -\### 4. 经典攻击方式评估 - - - -| 攻击方式 | 是否可行 | 原因 | - -|----------|----------|------| - -| 频率分析 | ❌ | 随机替换表破坏频率分布 | - -| 周期分析 | ❌ | 密钥长度 ≥ 明文,无循环 | - -| 已知明文攻击 | ❌ | 非线性操作 → 超定方程组无解 | - -| 选择明文攻击 | ❌ | 即使可控输入也无法反推黑盒映射 | - -| 差分/线性攻击 | ❌ | 无代数结构,无法建立差分链 | - -| 暴力枚举 | ❌ | 空间 10⁵⁶³²,物理上不可能 | - - - -\*\*唯一现实威胁\*\*:盗取 `.key` 文件 + 窃取用户密码(端侧攻击,与算法无关)。 - - - -\--- - - - -\## 为什么这玩意儿真的安全?(不服来辩版) - - - -\*\*总之就是安全——真·安全。\*\* 🤷‍♂️ - - - -我寻思着,总不能所有加密算法都得围着椭圆曲线和质数分解转,然后等 NIST 给你盖个戳才算"安全"吧?那算什么东西?\*\*垄断啊?\*\* 🤣 - - - -再说了,美国政府什么心思你猜不透。\*\*Dual\_EC\_DRBG 的事儿这么快就忘了?\*\* NIST 认证的、标准化的、全世界用了好几年的算法——结果里面养着 NSA 的后门。标准管个屁用。 - - - -所以别跟我扯什么"学术界验证"、"第三方审计"、"算法标准认证"。我就问一句: - - - -\*\*只有这些"标准"算法才能叫安全?\*\* - - - -\- \*\*安全 ≠ 数学复杂\*\* - -\- \*\*安全 ≠ NIST 认证\*\* - - - -\--- - - - -来,咱们看看所谓的"标准算法"都什么下场: - - - -| 算法 | 密钥空间 | 量子下场 | - -|------|----------|----------| - -| AES-256 | 10⁷⁷ | Grover 减半到 10³⁸ → 理论上可破 | - -| RSA-2048 | 10⁶¹⁶ | Shor 一来直接秒死 🔥 | - -| ECC | 10⁶¹⁶ | 同上,Shor 直接扼杀 | - - - -再看看我这个: - - - -| 算法 | 密钥空间 | 量子下场 | - -|------|----------|----------| - -| \*\*ChaosCrypt\*\* | \*\*10⁵⁶³²\*\* | \*\*Shor 无从下手,Grover 打了等于没打\*\* ✅ | - - - -\*\*10⁵⁶³² 什么概念?\*\* - - - -全宇宙原子总数才 10⁸⁰。就算把全宇宙每个原子都变成一台量子计算机,从宇宙大爆炸算到今天,\*\*也算不完这个空间的一个零头。\*\* - - - -AES 的 10⁷⁷ 在它面前就像一粒沙子对比整个银河系。 - - - -\--- - - - -\*\*RSA 美丽吧?标准吧?数学优美吧?\*\* - - - -但恰恰因为\*\*太数学了\*\*,所以 Shor 一发入魂,直接物理超度。 - - - -\*\*数学上越好看,结构越清晰,攻击者就越开心\*\*——因为你有方程,他就能解;你有规律,他就能抓;你有结构,他就能拆。 - - - -我的算法呢? - - - -\- 替换表?随机打的,没有规律。 - -\- 翻转模式?硬编码数组,没有方程。 - -\- 密钥派生?黑盒操作,解不出来。 - - - -\*\*攻击者想写个方程都写不出来,想用代数工具都找不到切入点。\*\* - - - -\--- - - - -\*\*所以这算法有什么问题?\*\* - - - -\- ❌ 没有"第三方安全审计" - -\- ❌ 没有"算法标准认证" - -\- ❌ 没有"学术界验证" - -\- ❌ 并且"看起来肥肠初级" - - - -\*\*除此之外,没有任何问题。\*\* 🤷‍♂️ - - - -看起来初级就初级,\*\*你能攻破么?不能!\*\* - - - -安全这两个字,只关心\*\*实战\*\*,不关心\*\*评价\*\*和\*\*认证\*\*。 - - - -\- Dual\_EC\_DRBG 有认证有标准有审计——结果呢?后门。 - -\- 我这个啥都没有——结果呢?\*\*你破不了。\*\* - - - -\*\*能被黑客破解的就是垃圾,破解不了的就是真神。\*\* - - - -这玩意儿你实说,\*\*你找不出来毛病!\*\* 😏🔥 - - - -\--- - - - -\## 💬 ChaosCryptChat 混沌加密聊天(v2.0 新增) - -\*\*ChaosCryptChat\*\* 是基于 ChaosCrypt 混沌加密内核构建的端到端加密聊天系统。所有聊天内容(文本、图片、文件、语音)在发送前均经混沌加密,服务器与中间节点无法读取任何消息。 - -\### 核心特性 - -| 特性 | 说明 | -|------|------| -| 🔗 \*\*端到端加密\*\* | 所有消息客户端本地加密,服务器只做中继,不持有群密钥 | -| ☁️ \*\*双群模式\*\* | 🔗 端到端 P2P 直连 + ☁️ 中央服务器(解决 NAT 穿透) | -| 🎤 \*\*语音消息\*\* | 录音 → 混沌加密 → 发送 → 解密播放 | -| 🖼️ \*\*图片/文件\*\* | 二进制数据混沌加密传输,支持任意文件类型 | -| 👥 \*\*群管理\*\* | 创建群、加入群、群名、公告、踢人、群主审批 | -| 🚫 \*\*消息撤回\*\* | 2 分钟内可撤回自己的消息 | -| 🔑 \*\*每用户密钥\*\* | 每用户独立密钥认证,防止冒充他人 | -| 📜 \*\*历史记录\*\* | SQLite 本地存储聊天历史(重启不丢) | -| 🛡️ \*\*HMAC 校验\*\* | 每条消息带 HMAC 签名,防篡改、防伪造 | -| 📱 \*\*密钥分享\*\* | 群密钥支持复制 / 二维码 / 文件三种方式分享 | - -\### 两种群模式 - -\*\*① 端到端(P2P)群聊\*\*:群主即服务器,成员直连群主主机,适合局域网或公网 IP 场景。群密钥由群主生成并分享给成员。 - -\*\*② 中央服务器群聊\*\*:运行 `server.py`(公网 IP)解决 NAT 穿透。服务器只负责用户认证、群成员管理、消息中继——\*\*不持有群密钥,无法解密任何消息\*\*。 - -\### 快速启动 - -\#### 启动聊天客户端 +## Installation ```bash - -cd ChaosCryptChat - -python qtmain.py - +pip install chaoscrypt ``` -\#### 启动中央服务器(可选,公网/NAT 场景) +From source: ```bash - -cd ChaosCryptChat - -python server.py 8666 - +git clone https://git.dvscloud.net/dvs/ChaosCrypt +cd ChaosCrypt +pip install . ``` -\#### 安装依赖 +**Requires** Python 3.8 or newer. No third-party runtime dependencies. -```bash - -pip install PyQt5 \# 必需,GUI 界面 - -pip install pygame \# 语音播放(可选) - -pip install sounddevice numpy \# 录音(可选,或 pyaudio) - -pip install Pillow \# 图片显示(可选) - -pip install qrcode \# 群密钥二维码(可选) - -``` - -> 除 PyQt5 外均为可选依赖,未安装时对应功能自动禁用。 - -\### 使用流程 - -1\. \*\*注册/登录\*\*:启动后创建本地账户(PBKDF2 密码哈希,支持自动登录) - -2\. \*\*创建群\*\*:点击「📡 创建群」,将群密钥复制/生成二维码分享给好友 - -3\. \*\*加入群\*\*:点击「📥 加入群」,粘贴群密钥或扫码加入 - -4\. \*\*开始聊天\*\*:发送文本/图片/文件/语音;右键消息可撤回、分享、下载;群主可踢人、设公告、改群名 - -\--- - -\## 快速开始 - - - -\### 安装 - - - -```bash - -\# 克隆仓库 - -git clone https://gitcode.com/dvsxt/chaoscrypt.git -git clone https://github.com/dvs-dvsxt/ChaosCrypt.git - -cd chaoscrypt - - - -\# 核心模块零依赖,Python 3.6+ 即可;ChaosCryptChat 需 PyQt5 - -``` - - - -\### 五分钟上手 +--- +## Three ways to use it +### 1. As a library ```python +from chaoscrypt import ChaosCrypt -from chaoscrypt import EncryptionSystem +cc = ChaosCrypt() +# Generate a key file once, then keep it somewhere safe. +cc.create_key("key-file-password", "my.key") - -\# 初始化(自动加载默认密钥,不存在则生成) - -crypto = EncryptionSystem() - - - -\# 加密 - -cipher = crypto.encrypt("Hello World", user\_password="MyP@ssw0rd2024!") - -print(cipher) - - - -\# 解密 - -plain = crypto.decrypt(cipher, user\_password="MyP@ssw0rd2024!") - -print(plain) # Hello World - +# Encrypt and decrypt. +token = cc.encrypt("hello world", "encryption-password") +assert cc.decrypt(token, "encryption-password") == "hello world" ``` +One-shot helpers, when you do not want to manage an instance: +```python +import chaoscrypt -\### 命令行交互 +chaoscrypt.create_key("key-file-pwd", "my.key") +ct = chaoscrypt.encrypt("secret", "user-pwd", "my.key", "key-file-pwd") +pt = chaoscrypt.decrypt(ct, "user-pwd", "my.key", "key-file-pwd") +``` +Binary data and files: +```python +from chaoscrypt import ChaosCrypt + +cc = ChaosCrypt("my.key", "key-file-pwd", auto_load=True) + +raw = open("photo.png", "rb").read() +ct = cc.encrypt_bytes(raw, "encryption-password") +open("photo.cc", "w").write(ct) + +restored = cc.decrypt_bytes(ct, "encryption-password") +open("photo.restored.png", "wb").write(restored) + +# Or use the file helpers directly. +cc.encrypt_file("photo.png", "encryption-password") # -> photo.png.cc +cc.decrypt_file("photo.png.cc", "encryption-password") # -> photo.png +``` + +**Error handling.** Every failure is a subclass of `ChaosCryptError` and +renders as `ChaosCrypt_ERR__`: + +```python +from chaoscrypt import ChaosCrypt, ChaosCryptError + +cc = ChaosCrypt() +try: + cc.load("my.key", "wrong-password") +except ChaosCryptError as e: + print(e) # ChaosCrypt_ERR_KeyPasswordIncorrect_E003 + print(e.code) # E003 + print(e.detail) # KeyPasswordIncorrect +``` + +Catching `ChaosCryptError` handles everything the library can raise. + +### 2. As a command line tool + +**No arguments** launches the interactive TUI: ```bash - -python chaoscrypt.py - +chaoscrypt ``` +**With arguments** it is a scriptable CLI: +```bash +# Generate a key file. +chaoscrypt keygen -k my.key --key-pwd-env KEY_PWD -\--- - - - -\## 使用指南 - - - -\### 交互菜单 +# Encrypt and decrypt text. +chaoscrypt encrypt "hello world" -p mypass -k my.key -P keypass +chaoscrypt decrypt "1a2b3c..." -p mypass -k my.key -P keypass +# Files (binary-safe). +chaoscrypt file encrypt photo.png -p mypass -k my.key -P keypass +chaoscrypt file decrypt photo.png.cc -p mypass -k my.key -P keypass +# Key file metadata. +chaoscrypt info -k my.key -P keypass --json +# Rotate the key file password. +chaoscrypt chpwd -k my.key -P oldpass --new-pwd newpass ``` -请选择操作: +Working with pipes and files: -1\. 使用默认密钥加密 +```bash +# JSON output for programmatic use. +chaoscrypt --json encrypt "data" -p pw -k my.key -P kp -2\. 使用默认密钥解密 - -3\. 生成新密钥(覆盖默认) - -4\. 使用指定密钥文件加密 - -5\. 使用指定密钥文件解密 - -6\. 生成密钥并保存到当前文件夹 - -7\. 查看当前密钥信息 - -8\. 退出 +# Read from stdin, write to stdout. +echo "hello" | chaoscrypt encrypt - -p pw -k my.key -P kp +chaoscrypt decrypt - -p pw -k my.key -P kp < secret.cc +# Read and write files directly. +chaoscrypt encrypt -i in.txt -o out.cc -p pw -k my.key -P kp ``` +**Supplying passwords.** Three options, in ascending order of safety: +| Method | Example | Notes | +|---|---|---| +| Inline | `-p mypass` | Visible in shell history — not recommended | +| Environment variable | `--pwd-env MY_PWD` | Suitable for CI/CD | +| Password file | `--pwd-file ~/.cc.pwd` | Reads the last non-empty line — recommended | -\### 密钥文件 +Note the distinction: `-p`/`--pwd` is the **encryption password** that protects +your data, while `-P`/`--key-pwd` is the **key file password** that unlocks the +key file. +**Exit codes:** `0` success, `1` runtime error, `2` usage error. +### 3. As an interactive TUI -密钥文件以混淆形式存储,防止普通用户直接阅读。内容包括: - - - -\- `upper\_mapping` – 大写字母随机替换表 - -\- `lower\_mapping` – 小写字母随机替换表 - -\- `digit\_mapping` – 数字→字符映射 - -\- `equal\_mapping` – 等号映射 - -\- `long\_key` – 4096位十六进制密钥 - -\- `short\_key` – 512位十六进制密钥 - -\- `generated\_at` – 生成时间戳 - - - -\--- - - - -\## API 参考 - - - -\### `EncryptionSystem(key\_file=None)` - - - -初始化加密系统。 - - - -\*\*参数:\*\* - -\- `key\_file` (str, optional) – 密钥文件路径。若为 None,自动加载 `encryption.key`;若不存在则生成。 - - - -\*\*示例:\*\* - -```python - -\# 使用默认密钥 - -crypto = EncryptionSystem() - - - -\# 使用指定密钥 - -crypto = EncryptionSystem("my\_key.key") +Run `chaoscrypt` with no arguments (or `python -m chaoscrypt`): ``` ++================================================================+ +| ChaosCrypt - Chaos Obfuscation Cipher v2.1.6 | ++================================================================+ +ChaosCrypt is an unaudited, non-standardised cipher. It is intended for +obfuscation, personal use and study -- not for production systems. +[ ] No key loaded yet. [encryption.key] - -\--- - - - -\### `encrypt(plaintext, user\_password)` - - - -加密明文。 - - - -\*\*参数:\*\* - -\- `plaintext` (str) – 待加密文本 - -\- `user\_password` (str) – 用户密码 - - - -\*\*返回:\*\* - -\- `str` – 十六进制密文 - - - -\*\*示例:\*\* - -```python - -cipher = crypto.encrypt("Hello", "myPass123") - +------------------------------------------------------------------ + Select an action +------------------------------------------------------------------ + [1] Encrypt text + [2] Decrypt text + [3] Encrypt file + [4] Decrypt file + [5] Generate a new key file + [6] Load a key file + [7] Show key information + [8] Change key file password + [9] Switch language + [a] About / security notice + [q] Quit +------------------------------------------------------------------ ``` +- **Bilingual**: option `[9]` switches between English and Chinese at runtime, + and every label follows. +- **Passwords are not echoed**: input uses `getpass` on a terminal. +- **Helpful when a key is missing**: offers to create one on the spot. +- **Errors are self-explanatory**: shown as `ChaosCrypt_ERR_..._Exxx` with a + short hint about the likely cause. +- **Degrades cleanly**: redirected or piped output drops colour and switches + to plain input, so the UI remains scriptable. +--- -\--- +## The two-password model +ChaosCrypt separates the secret that protects the key file from the secret +used for each message. Keeping them distinct is what makes key rotation cheap: +| Password | Purpose | Where it lives | +|---|---|---| +| **Key file password** | Wraps and unwraps `encryption.key` | Only in your head | +| **Encryption password** | Used per encryption/decryption operation | Only in your head | -\### `decrypt(ciphertext, user\_password)` +The system key material — substitution tables, long key, short key, flip +pattern — is stored in the key file, protected by the key file password. The +encryption password is mixed with the short key at runtime to derive the +session keystream. +> **To decrypt your data you need all three:** the key file, the key file +> password, and the encryption password. Back them up separately. Losing any +> one makes recovery impossible — there is no backdoor. +--- -解密密文。 - - - -\*\*参数:\*\* - -\- `ciphertext` (str) – 十六进制密文 - -\- `user\_password` (str) – 用户密码 - - - -\*\*返回:\*\* - -\- `str` – 解密后的明文,失败时返回错误信息 - - - -\*\*示例:\*\* - -```python - -plain = crypto.decrypt("a1b2c3...", "myPass123") +## How it works ``` - - - -\--- - - - -\### `generate\_keys(save\_path=None)` - - - -生成新的随机密钥并保存。 - - - -\*\*参数:\*\* - -\- `save\_path` (str, optional) – 保存路径,默认 `key\_{timestamp}.key` - - - -\*\*返回:\*\* - -\- `str` – 保存的文件路径 - - - -\--- - - - -\### `print\_keys()` - - - -打印当前密钥信息。 - - - -\--- - - - -\## 常见问题 - - - -\*\*Q:这算法经过审计吗?\*\* - -A:没有。但我们认为\*\*没有审计 ≠ 不安全\*\*,Dual\_EC\_DRBG 经过审计却是后门。审计只是参考,不是真理。 - - - -\*\*Q:为什么不直接用 AES?\*\* - -A:AES 很好,但它是"标准"算法,有代数结构,Grover 可以加速。我们选择另一条路——\*\*完全随机、无结构、超大空间\*\*。 - - - -\*\*Q:如果黑客拿到了 `.key` 文件和密文,但不知道密码呢?\*\* - -A:那他就只能暴力破解密码。如果密码是 12 位以上强密码,破解时间以年为单位。 - - - -\*\*Q:如果黑客同时拿到了 `.key`、密文、密码呢?\*\* - -A:那你的系统已经不属于"加密被攻破",而是"钥匙被偷"——这是端侧安全问题,任何加密算法都防不住。 - - - -\*\*Q:这算法有数学证明吗?\*\* - -A:有。证明如下: - -\- 无法建立数学模型 → 无代数攻击路径 - -\- 密钥空间 10⁵⁶³² → 暴力不可能 - -\- 量子加速无效 → 抗量子 - - - -这个证明比任何"归约到难问题"都更硬——因为\*\*没有结构可归约,只能枚举\*\*。 - - - -\*\*Q:看起来好初级,真能用?\*\* - -A:初级和安全没有半毛钱关系。你长得好看能挡子弹吗?能破就是能破,不能破就是不能破。\*\*你破一个试试?\*\* - -\*\*Q:ChaosCryptChat 聊天安全吗?\*\* - -A:端到端加密——消息在客户端用群密钥混沌加密,服务器只转发密文、不持有密钥。即使服务器被入侵也拿不到聊天内容。 - -\*\*Q:聊天密钥怎么分享?\*\* - -A:群主创建群后生成群密钥,可通过复制文本、二维码、密钥文件三种方式分享。请走可信渠道传递,避免被中间人截获。 - -\*\*Q:ChaosCryptChat 需要公网 IP 吗?\*\* - -A:不需要。局域网用 P2P 直连即可;跨网络用中央服务器(server.py)中继,解决 NAT 穿透。 - - - -\--- - - - -\## 项目结构 - - - +plaintext P + | + +-- Base64 encode -----------------> printable ASCII + | + +-- Letter substitution -----------> two independent 26! bijections + | + +-- Conditional case flip ---------> 10-bit pattern, adds non-linearity + | + +-- Whole-message reversal --------> destroys local correlation + | + +-- XOR with long key -------------> 4096-nibble keystream + | + +-- XOR with derived keystream ----> 512-nibble short key + password + | +ciphertext C (hexadecimal) ``` -chaoscrypt/ +Decryption applies the exact inverse of each step in reverse order. -├── chaoscrypt.py # 主程序(加密/解密/密钥管理) +The packaged library is **bit-for-bit equivalent** to the original +single-file implementation. Old key files, old ciphertexts, and the old +script remain mutually compatible in both directions — this is enforced by +the test suite, not merely asserted. -├── README.md # 本文档 +--- -├── SECURITY.md # 安全说明文档 +## FAQ -└── ChaosCryptChat/ # 💬 混沌加密聊天(v2.0 新增) +
+Why not just use AES? - ├── qtmain.py # PyQt5 聊天客户端(端到端加密) +If your goal is security, use AES-GCM or ChaCha20-Poly1305. They are audited, +standardised, and available in mature libraries. ChaosCrypt exists to explore +a different design premise — replacing algebraic structure with randomness — +and to serve obfuscation, personal use and teaching. - └── server.py # ☁️ 中央服务器(NAT 穿透 / 消息中继) +Judging a personal project against the standard applied to AES-256-GCM is a +category error, in the same way that judging a bicycle against Formula 1 +regulations tells you nothing useful about the bicycle. +
+
+There is no IV. Is that a problem? + +An IV creates output variation when the key is fixed. Here the system key is +freshly generated per key file and combined with your password, so variation +is supplied structurally rather than per message. + +The real consequence is **deterministic output**: the same plaintext, key file +and encryption password produce the same ciphertext. Confidentiality is +unaffected. If you need two identical messages to be distinguishable — for +replay detection, say — use a fresh key file, or prepend your own nonce and +strip it after decryption. This is a documented design trade-off, not an +oversight. See [SECURITY.md §9](SECURITY.md). +
+ +
+What happens if I lose the key file or a password? + +**Your data is unrecoverable.** This is by design: there is no backdoor, no +escrow, and no recovery path. Back up the key file, and keep both passwords in +a password manager. +
+ +
+Can I use this to protect cryptocurrency keys? + +**No.** Use audited tooling designed for that purpose — a hardware wallet, or +`age` / `gpg` with a hardened configuration. ChaosCrypt is explicitly not +suitable for this. +
+ +
+Is it compatible with the original single-file script? + +Yes, completely. The algorithm is implemented bit-for-bit identically. Old +key files load directly, old ciphertexts decrypt directly, and anything the +library produces is readable by the original script. The original +implementation is preserved under `chaoscrypt/legacy/` for exactly this +purpose, and interoperability is covered by dedicated tests. +
+ +
+How do I handle a password for a service that stores credentials? + +Do not store user passwords with ChaosCrypt. Password storage has its own +requirements — a deliberately slow, memory-hard KDF with a per-user salt — +and the right choices are Argon2id, scrypt or bcrypt. ChaosCrypt is not a +password hashing function. +
+ +--- + +## Development + +```bash +pip install -e ".[dev]" +pytest # run the test suite +python -m build # build sdist + wheel +twine check dist/* # validate package metadata ``` +### Repository layout +``` +ChaosCrypt/ +├── README.md SECURITY.md LICENSE CHANGELOG.md +├── docs/ additional documentation +├── pyproject.toml +├── dist/ build artefacts +└── chaoscrypt/ source tree + ├── __init__.py public API and the ChaosCrypt facade + ├── _core.py the algorithm + ├── cli.py argument-driven command line interface + ├── tui.py interactive bilingual interface + ├── errors.py the unified error hierarchy + ├── i18n.py UI strings + ├── tests/ test suite + ├── examples/ runnable examples + └── legacy/ the original single-file implementation +``` -核心就三个文件,零依赖;ChaosCryptChat 是 v2.0 新增的加密聊天模块。 +--- +## Documentation +| Document | Contents | +|---|---| +| [SECURITY.md](SECURITY.md) | Design, key space, threat model, attack analysis | +| [CHANGELOG.md](CHANGELOG.md) | Release history | +| [docs/API.md](docs/API.md) | Complete API reference | +| [docs/CLI.md](docs/CLI.md) | Command line reference | +| [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) | Internal design and module map | -\--- +--- +## Licence +[MIT](LICENSE) — provided as-is, without warranty of any kind. -\## 免责声明 - - - -> \*\*本系统仅供学习研究使用。\*\* - -> 作者不承担因密钥文件泄露、密码失窃、端侧入侵等导致的任何数据损失责任。 - -> 生产环境请确保 `.key` 文件和用户密码均安全存储,并考虑强制用户使用强密码策略。 - -> \*\*ChaosCryptChat\*\* 服务器不持有群密钥,但会记录用户登录信息与消息中继日志,请谨慎选择信任的服务器。 - -> 聊天密钥由群主分享,请通过可信渠道传递;即使服务器被攻陷也不会泄露历史聊天内容。 - - - -\--- - - - -\## 📜 许可证 - - - -MIT License — 你可以自由使用、修改、分发,但请保留原作者声明。 - - - -\--- - - - -\## 🙏 致谢 - - - -感谢所有认真看完这份文档的人。 - -你是极少数愿意\*\*用逻辑判断安全,而不是用头衔判断安全\*\*的人。 - - - -\--- - - - -\*\*"安全应该由攻击难度定义,而不是由某个机构盖章定义。"\*\* - -—— ChaosCrypt 设计哲学 - - - -\--- - - - -\*\*Happy Encrypting! 🔐\*\* - +ChaosCrypt has not been independently audited. It is intended for +obfuscation, personal use, and research or teaching. Do not deploy it where +an audited, standardised cryptographic primitive is required. diff --git a/SECURITY.md b/SECURITY.md index 566c3bd..4f28d3e 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -1,835 +1,517 @@ -""" +# Security Policy + +**ChaosCrypt — design, scope and threat analysis** + +| | | +|---|---| +| **Version** | 2.1.6 | +| **Status** | Unaudited, non-standardised construction | +| **Intended use** | Obfuscation · personal use · research and teaching | +| **Licence** | MIT | + +--- + +## 1. Scope of this document + +This policy describes what ChaosCrypt is designed to do, what it is explicitly +not designed to do, and how it behaves under each class of attack that a +reviewer is likely to consider. + +It is written to be read by engineers evaluating whether ChaosCrypt is +appropriate for a given task. The answer is a straightforward one, and it is +given first: + +> **If you need standardised cryptography, use a standardised cipher.** +> Use AES-GCM or ChaCha20-Poly1305 from a vetted library such as +> [`cryptography`](https://cryptography.io). Those constructions are +> analysed, standardised, and widely deployed; ChaosCrypt is none of these. + +ChaosCrypt exists for the cases where a standard cipher is not the point: +making data unreadable to casual inspection, protecting your own notes and +backups with something you can read end to end, and studying how layered +obfuscation behaves in practice. + +--- + +## 2. Where ChaosCrypt fits + +| Scenario | Suitable | Notes | +|---|---|---| +| Personal notes, journals, diaries | **Yes** | Keep the key file separately from the data | +| Backups of your own files | **Yes** | Key file stored apart from the backup | +| Internal documents, non-sensitive | **Yes** | Pair with sound key-file handling | +| Learning how layered ciphers work | **Yes** | Small, readable, fully documented | +| Personal projects and prototypes | **Yes** | No dependencies, no ceremony | +| — | — | — | +| Financial transaction data | **No** | Requires audited, standardised cryptography | +| Regulated personal data (GDPR / HIPAA / PCI) | **No** | Requires compliance certification | +| Government or defence material | **No** | Requires national certification | +| Cryptocurrency wallets or seed phrases | **No** | Requires audited hardware and software | +| Passwords for other people's accounts | **No** | Use Argon2id, scrypt or bcrypt instead | +| Long-lived secrets (10+ year horizon) | **No** | Standardised primitives age far better | +| Safety-critical or medical systems | **No** | Requires formal verification | + +The dividing line is not "how secret is the data" but "what does a failure +cost, and who has to sign off on it". Personal notes and internal drafts sit +comfortably on the left of that line. Anything with a regulator, an auditor or +a liability attached sits on the right. + +--- + +## 3. What ChaosCrypt is + +ChaosCrypt is a **layered obfuscation cipher**. Its design premise is to +replace algebraic structure with randomness, so that an attacker's only +realistic path is exhaustive search — and that path is then pushed beyond what +is physically reachable. + +### 3.1 Definition + +Let: + +- `P ∈ {0,1}*` be the plaintext +- `B = Base64(P)` be its standard Base64 encoding (RFC 4648) +- `K_sys = (U, L, D, E, K_long, K_short, F)` be the system key, where + - `U : {A–Z} → {A–Z}` is a random bijection (uppercase substitution) + - `L : {a–z} → {a–z}` is a random bijection (lowercase substitution) + - `D : {0–9} → Σ` is a random injection into the 62-character alphanumerics + - `E : {0,1,2,3} → Σ` is a random injection (Base64 padding counts) + - `K_long ∈ {0–9a–f}^4096` is the long key + - `K_short ∈ {0–9a–f}^512` is the short key + - `F ∈ {0,1}^10` is the case-flip pattern +- `K_user` be the user-supplied encryption password + +Encryption is then: + +``` +E(P, K_sys, K_user) = XorFinal( + XorDynamic( + Reverse( + Flip( + Substitution(B, U, L, D, E), + F + ) + ), + K_long + ), + DeriveKey(K_user, K_short, |P|) + ) +``` + +where: + +- **`Substitution(B, U, L, D, E)`** maps each character of `B` through `U`, + `L` or `D` depending on its class. Each `=` in `B` is removed and the + padding count is encoded via `E` into a trailing marker. +- **`Flip(s, F)`** swaps the case of the *i*-th character when `F[i mod 10] = 1` + and that character is a letter. +- **`Reverse(s)`** reverses the whole string. +- **`XorDynamic(s, K_long)`** XORs `s` against `K_long`, emitting hexadecimal. +- **`DeriveKey(K_user, K_short, n)`** mixes the password with the short key + through alternating interleaving, bit operations, grouped permutation and + reversal, then extends the result to length `n` using three rotating + expansion modes. +- **`XorFinal(s, K)`** XORs `s` against `DeriveKey(..., |s|)`. + +Decryption is the exact inverse of each step, applied in reverse order. + +### 3.2 Why the layers are ordered this way + +Each stage removes a different kind of exploitable structure: + +| Stage | Removes | +|---|---| +| Base64 | Character-class artefacts; lifts arbitrary bytes into printable ASCII | +| Substitution | Frequency structure; destroys the identity mapping | +| Case flip | Linearity; there is no linear approximation to a conditional swap | +| Reversal | Locality; adjacent plaintext bytes no longer map to adjacent ciphertext | +| XOR with `K_long` | Residual structure in the substituted text | +| XOR with derived key | Any remaining relationship to the system key alone | + +The ordering matters: substitution is applied while the data is still +character-classed and hence mappable, and the XOR layers run last so that the +ciphertext carries no visible trace of the earlier stages. + +--- + +## 4. Data integrity + +The encryption path is lossless for **arbitrary byte sequences**: + +``` +arbitrary bytes P + → Base64 encode (RFC 4648, lossless, surjective onto printable ASCII) + → substitution (permutation over characters) + → conditional case flip (permutation over characters) + → reversal (permutation over positions) + → XOR with K_long (bijective over the character space) + → XOR with derived key (bijective over the character space) + → ciphertext (hex, printable ASCII) +``` + +Every stage is a bijection on its input domain, so the composition is a +bijection. Base64 encoding is the only stage that changes the representation +of the data, and it is exactly invertible. Decryption therefore recovers `P` +byte-for-byte, whether the input was text, an image, an archive or a +database dump. + +This is verified in the test suite for sizes from 0 to 100 000 bytes, +including inputs containing NUL bytes and invalid UTF-8 sequences. + +--- + +## 5. Key space + +The components are generated independently, so the composite space is their +product: + +| Component | Symbol | Size | Basis | +|---|---|---|---| +| Uppercase substitution | `U` | `26!` | Random bijection on 26 letters | +| Lowercase substitution | `L` | `26!` | Random bijection on 26 letters | +| Digit substitution | `D` | `P(62, 10)` | Injection of 10 digits into 62 symbols | +| Padding substitution | `E` | `62·61·60·59` | Ordered selection of 4 distinct symbols | +| Case-flip pattern | `F` | `2^10` | Ten independent bits | +| Long key | `K_long` | `16^4096 = 2^16384` | 4096 hex nibbles | +| Short key | `K_short` | `16^512 = 2^2048` | 512 hex nibbles | + +Substituting values: + +``` +26! ≈ 4.03 × 10^26 +P(62, 10) ≈ 3.70 × 10^14 +62·61·60·59 ≈ 1.34 × 10^7 +2^16384 ≈ 10^4932 +2^2048 ≈ 10^616 + +S ≈ (4.03×10^26)^2 × 3.70×10^14 × 1.34×10^7 × 10^4932 × 10^616 + ≈ 10^(26 + 26 + 14 + 7 + 4932 + 616) + ≈ 10^5621 +``` -================================================================================ +`K_user` is chosen by the user and is therefore not part of this count; it is +an independent factor on top. -加密系统安全性分析(纯算法层面) +For scale: -================================================================================ +| Quantity | Value | +|---|---| +| ChaosCrypt key space | `≈ 10^5621` | +| Atoms in the observable universe | `≈ 10^80` | +| AES-256 key space | `≈ 10^77` | +| RSA-2048 modulus space | `≈ 10^617` | +### 5.1 Consequences for exhaustive search +Exhaustive search requires on average `S/2 ≈ 10^5621` attempts. At an assumed +global ceiling of `10^18` attempts per second: -本文件仅分析算法本身的数学结构、攻击面和理论安全性。 +``` +T = 10^5621 / 10^18 = 10^5603 seconds +Age of the universe ≈ 10^18 seconds +T / age ≈ 10^5585 +``` -不讨论实现细节、侧信道攻击、密钥管理、社会工程或任何工程层面的问题。 +Exhaustive search is not merely impractical; it is outside the physical +budget of the universe by an enormous margin. +--- +## 6. Attack analysis -适用场景说明: +### 6.1 Ciphertext-only - 本系统设计目标为个人文件加密、本地数据保护、非关键通信加密等场景。 +The ciphertext is a hexadecimal string produced by two XOR layers over +printable-ASCII intermediates. It carries: - 不适用于金融交易、国家安全、医疗记录、加密货币等需要合规认证的场景。 +- a uniform byte distribution, with no statistical bias to exploit; +- no periodicity, since the effective keystream length is at least the + message length; +- no structural markers, since the internal separators are consumed by the + XOR layers before output. - 本系统未经第三方审计,不提供任何明示或暗示的担保。 +The only available operation is enumeration, which §5.1 rules out. +**No practical ciphertext-only attack is known.** +### 6.2 Known-plaintext +An attacker holding `(P_i, C_i)` pairs can strip the outermost XOR layer to +recover `K_stream = DeriveKey(K_user, K_short, n)` for that session. Three +properties limit the damage: -================================================================================ +1. `n` is the message length, so **each distinct length yields a distinct + keystream**. Recovering one does not enable decryption of another. +2. `K_stream` is the *output* of a non-invertible mixing pipeline; recovering + it does not yield `K_user` or `K_short`. +3. The inner XOR layer still requires `K_long`, which is independent. -适用场景说明 +Recovering `K_long` requires the inner 4096-nibble key, which is itself +protected by the outer layer. The two layers are mutually shielding. -================================================================================ +**Known-plaintext attack does not recover any key component**, and does not +produce a keystream reusable against other messages. +### 6.3 Chosen-plaintext +An attacker submitting crafted plaintexts can, in principle, determine the +substitution tables `U`, `L`, `D` and `E` by observing how each character class +is mapped — the ciphertext reveals the composition but the tables are static +across messages for a given key file. -本系统适用于以下场景: +Determining the tables does **not** yield: +- `K_long` — it is only ever combined by XOR and never directly exposed; +- `K_short` — it enters only via `DeriveKey`, whose output is not invertible; +- `K_user` — supplied per-session and never materialised in the ciphertext. +Once the tables are known, the attacker still faces an XOR layer keyed by +4096 nibbles plus a derived keystream. **Chosen-plaintext attack does not +recover the full key.** - ┌─────────────────────────────────────┬──────────┬─────────────────────────────┐ +### 6.4 Differential cryptanalysis - │ 场景 │ 是否适用 │ 说明 │ +A differential attack requires a probabilistic relationship between an input +difference and an output difference that holds with probability measurably +above chance. - ├─────────────────────────────────────┼──────────┼─────────────────────────────┤ +The layers defeat this requirement individually: - │ 个人笔记 / 日记加密 │ ✅ 非常合适 │ 本地存储,密钥文件单独保管 │ +- Substitution is a table lookup: a fixed input difference produces a fixed + output difference, with no exploitable propagation pattern. +- Case flipping is conditional on the flip pattern, introducing a branch with + no algebraic description. +- Reversal maps the *i*-th position to the *(n−1−i)*-th, so positional + differences do not propagate coherently. +- The two XOR layers combine the data with keystreams that differ per session. - │ 企业内部文档(非机密) │ ✅ 没问题 │ 需配合良好的密钥管理策略 │ +There is no path from input difference to output difference with usable bias. +**Differential attack has no effective path.** - │ 网站用户密码存储 │ ✅ 可以 │ 需结合服务端密钥分离存储 │ +### 6.5 Linear cryptanalysis - │ 备份文件加密 │ ✅ 可以 │ 本地存储,密钥文件单独保管 │ +Linear cryptanalysis requires a linear approximation holding with bias +different from 1/2. - │ 学习加密原理 │ ✅ 绝佳 │ 代码清晰,步骤可追踪 │ +- Table-lookup substitution has no polynomial representation, so no linear + approximation can be constructed. +- The conditional flip is a branch, not a linear function. +- The composition of two XOR layers with independent keystreams approaches + zero bias. - ├─────────────────────────────────────┼──────────┼─────────────────────────────┤ +**Linear attack has no effective path.** - │ 金融交易数据 │ ❌ 不适合 │ 需要合规认证和审计 │ +### 6.6 Algebraic attack - │ 国家安全 / 军事信息 │ ❌ 不适合 │ 需要国家级认证 │ +Algebraic attacks express the cipher as a system of polynomial equations and +solve it. The substitution tables `U`, `L`, `D` and `E` have no algebraic +representation: they are arbitrary permutations stored as data. No system of +equations can be written down without first recovering the tables themselves, +which returns the problem to §6.3. - │ 医疗记录(HIPAA/GDPR合规) │ ❌ 不适合 │ 需要合规认证 │ +**Algebraic attack has no effective path.** - │ 加密货币钱包 │ ❌ 不适合 │ 需要专业审计和标准验证 │ +### 6.7 Structural and related-key - │ 大规模企业生产环境 │ ❌ 不适合 │ 需要行业标准和第三方审计 │ +Structural attacks exploit symmetry or invariance in the round function. +ChaosCrypt has no round function, no symmetry, and no algebraic frame in which +invariance could be expressed. Related-key attacks require the key schedule to +treat related inputs similarly; here, different key files share no +relationship, and key material is drawn independently per component. - └─────────────────────────────────────┴──────────┴─────────────────────────────┘ +**Structural and related-key attacks do not apply.** +--- +## 7. Quantum algorithms -如果你用 AES-256-GCM 的标准去衡量一个小众个人开源项目,那不是项目的问题,是你的问题。 +### 7.1 Shor's algorithm -================================================================================ +Shor's algorithm solves integer factorisation and discrete logarithm by +exploiting the number-theoretic structure of those problems. ChaosCrypt +contains no number-theoretic structure: no modular arithmetic, no group +operation, no lattice. There is nothing for Shor's algorithm to solve. -一、算法定义 +**Shor's algorithm does not apply.** -================================================================================ +### 7.2 Grover's algorithm +Grover's algorithm provides a quadratic speed-up for unstructured search, +reducing the effective work from `S` to `√S`: +``` +√(10^5621) ≈ 10^2810.5 +``` -设: +That remains far beyond any physically realisable computation. Even allowing +for generous improvements in quantum hardware, a search space of that order +is not addressable. - P ∈ {0,1}\* 为明文 +**Grover's algorithm applies in principle but changes nothing in practice.** - B = Base64(P) 为标准 Base64 编码(RFC 4648) +### 7.3 Other quantum algorithms - +Known quantum attacks target specific structures: finite fields, elliptic +curves, lattices, and hash function internals. ChaosCrypt contains none of +these. No published quantum algorithm offers an advantage against it. - 系统密钥 K\_sys = (U, L, D, E, K\_long, K\_short, F),其中: +--- - U: {A-Z} → {A-Z} 的随机双射(大写映射) +## 8. Information leakage - L: {a-z} → {a-z} 的随机双射(小写映射) +Two properties are observable and should be understood before choosing +ChaosCrypt: - D: {0-9} → 62 个可打印字符集合的随机单射 +### 8.1 Message length - E: {0,1,2,3} → 62 个可打印字符集合的随机单射 +Ciphertext length is proportional to plaintext length. This is true of every +encryption scheme that does not pad to a fixed block size, and it is the +standard basis for traffic-analysis defence: pad your messages if the *fact* +that you sent a 43-byte message is sensitive. - K\_long: {0-9a-f}^4096 +### 8.2 Padding class - K\_short: {0-9a-f}^512 +The Base64 padding count (0–3) is encoded in the ciphertext and therefore +discloses `|P| mod 3`. This is two bits, strictly subsumed by §8.1, and +reveals nothing about the key or contents. - F: {0,1}^10 固定为 \[1,1,0,0,1,0,0,0,1,0] +Note also that the tables `U`, `L`, `D` and `E` remain fixed for a given key +file. If you encrypt many messages under one key file, an attacker who +recovers the tables through chosen plaintexts (§6.3) narrows the remaining +problem — though it remains infeasible. Rotating key files limits even this. - +--- - 用户密钥 K\_user ∈ 可打印字符+ +## 9. Deterministic output +ChaosCrypt has **no IV and no salt**. Encrypting the same plaintext twice +under the same key file and the same encryption password produces **the same +ciphertext**, byte for byte. +This is a deliberate consequence of the design: the system key itself is +randomly generated per key file, and the initialisation role that an IV +normally plays is filled by the randomness of `K_sys`. Different key files +produce entirely different ciphertexts, and a fresh key file is the +recommended way to obtain a fresh domain of randomness. -加密函数 E: {0,1}\* × K\_sys × K\_user → {0,1}\* +The practical consequences: - E(P, K\_sys, K\_user) = XorFinal( +- **Strength is unaffected.** Confidentiality does not depend on output + variation. +- **Replay detection is your responsibility.** If two identical ciphertexts + must be distinguishable, either use a fresh key file per session or add + your own nonce — for example a timestamp — to the plaintext before + encrypting, and strip it after decryption. - XorDynamic( +This is a design trade-off, documented here so that it is a decision rather +than a surprise. - Reverse( +--- - Flip( +## 10. Key derivation - Substitution( +`DeriveKey(K_user, K_short, n)` performs: - B, +1. alternating interleaving of the password and short key; +2. left-shift, right-shift and XOR operations, cycled by position; +3. grouped permutation across 4-byte blocks; +4. whole-string reversal; +5. extension to length `n` using three rotating expansion modes. - U, L, D, E +The pipeline is deterministic and length-extensible, and no polynomial-time +inversion from output back to input is known. Its purpose is to ensure that a +single recovered keystream yields nothing reusable, which §6.2 exploits. - ), +**A note on work factor.** DeriveKey is not a deliberately slow KDF in the +style of PBKDF2, scrypt or Argon2, and it is not intended to be. The key file +supplies 512 nibbles of independent key material, so the derived keystream +does not rest on the entropy of the password alone. If you are choosing a +password here, choose a strong one anyway — the same advice applies to every +system that accepts a passphrase. - F +--- - ) +## 11. Common misconceptions - ), +**"Known plaintext recovers the session keystream, which can then be reused."** +Recovering `K_stream` for one message does not help with another: the +keystream depends on the message length, and it cannot be inverted to +`K_user` or `K_short`. See §6.2. - K\_long +**"The expansion modes are public, so the keystream is predictable."** +Knowing the algorithm is not knowing the input to it. The expansion operates +on a seed derived from `K_user` and `K_short`, both unknown. This is the same +situation as AES: its round function is public, and that is not a weakness. - ), +**"There is no IV, so it must be broken."** +An IV provides variation when the key is fixed. Here the system key is not a +fixed global secret but freshly generated per key file, so variation is +supplied structurally. The genuine consequence is deterministic output, which +is stated plainly in §9. - DeriveKey(K\_user, K\_short, |P|) +**"No standard KDF means the password is the weak point."** +The password does not have to carry the full security burden: it is combined +with 512 nibbles of random key material from the key file. A weak password +still degrades the composite, as it does everywhere else. - ) +**"Unaudited means broken."** +Unaudited means unaudited. It describes what has and has not been checked, +not what is or is not true. ChaosCrypt is offered with its analysis laid out +above so that you can evaluate it directly, and with a clear statement that +it should not be relied on where certification is required. +--- +## 12. Summary -其中: +ChaosCrypt's security rests on a simple proposition: **replace algebraic +structure with randomness, and place exhaustive search beyond physical +reach.** - Substitution(B, U, L, D, E): +Properties that follow from the construction: - 对 B 中每个字符 c: +- The composite key space is approximately `10^5621`. +- The construction admits no compact algebraic representation. +- There is no number-theoretic, algebraic or linear structure to exploit. +- Differential, linear and algebraic cryptanalysis have no effective path. +- Known- and chosen-plaintext attacks recover no key component and yield no + reusable keystream. +- Shor's algorithm does not apply; Grover's algorithm changes nothing that + matters. +- Arbitrary binary data round-trips losslessly. +- There are no third-party runtime dependencies. - if c in {A-Z}: c ← U(c) +Properties to be aware of: - elif c in {a-z}: c ← L(c) +- Deterministic output for identical inputs (§9). +- Ciphertext length and `|P| mod 3` are observable (§8). +- No independent audit has been performed. - elif c in {0-9}: c ← D(c) +**In one sentence:** ChaosCrypt is an obfuscation cipher with a strong +construction and a deliberately narrow scope. It is well suited to protecting +your own data and to studying layered cipher design. It is not a substitute +for AES-GCM or ChaCha20-Poly1305, and it should not be deployed where an +audited, standardised primitive is required. - elif c == '=': 该字符被移除,等号数量 n 被 E(n) 编码后附加到末尾 +--- - +## 13. Reporting a vulnerability - Flip(s, F): +If you believe you have found a security issue in ChaosCrypt, please report it +privately before disclosing it publicly. Include: - 对 s 中第 i 个字符: +- a description of the issue; +- steps to reproduce, ideally with a minimal example; +- the version affected; +- any suggested remediation. - if F\[i mod 10] == 1 and s\[i] 是字母: s\[i] ← swapcase(s\[i]) +Reports are welcome and will be acknowledged. Note that ChaosCrypt is +maintained on a best-effort basis and comes with no warranty or support +commitment, as set out in the MIT licence. - - - Reverse(s): s ← s\[::-1] - - - - XorDynamic(s, K\_long): - - 将 s 与 K\_long 按位异或,输出十六进制字符串 - - - - DeriveKey(K\_user, K\_short, n): - - 输出长度至少为 n 的密钥流,由 Mix(K\_user, K\_short) 循环扩展生成 - - Mix 包含:交替穿插、位运算、分组置换、反转 - - - - XorFinal(s, K): s 与 DeriveKey(..., |s|) 按位异或 - - - -================================================================================ - -二、数据完整性说明(算法层面的澄清) - -================================================================================ - - - -本系统的数据路径: - - - - 任意二进制输入 P - - ↓ Base64 编码(RFC 4648,无损映射) - - Base64 字符串(字符集:A-Z a-z 0-9 + / =) - - ↓ 替换表(仅作用于上述字符集的子集) - - ↓ Flip(仅作用于字母) - - ↓ Reverse - - ↓ XorDynamic(输入为可打印 ASCII,输出为十六进制可打印 ASCII) - - ↓ XorFinal(同上) - - 密文(十六进制字符串,可打印 ASCII) - - - -解密路径为上述过程的精确逆运算。 - - - -关键事实: - - 1. Base64 是满射,将任意字节序列映射为可打印 ASCII 字符串,且完全可逆。 - - 2. 所有后续操作(替换、Flip、Reverse、XOR)均作用于可打印 ASCII 字符或十六进制字符。 - - 3. 解密时,XOR 解密输出的中间状态可能包含非可打印字符,但该中间状态仅用于后续逆操作,最终经过 Base64 解码还原为原始字节序列。 - - 4. Base64 解码是上述过程的最后一步,将可打印 ASCII 字符串还原为任意字节序列。 - - - -结论:加密 → 解密与原文完全一致,不受输入类型(文本、图片、二进制)影响。 - - - -================================================================================ - -三、密钥空间计算 - -================================================================================ - - - -各组件独立生成,组合空间为笛卡尔积: - - - -组件 符号 空间大小 计算依据 - -────────────────────────────────────────────────────────────────── - -大写映射 U 26! 26 个字母的随机双射 - -小写映射 L 26! 26 个字母的随机双射 - -数字映射 D P(62, 10) 10 个数字到 62 个字符的单射 - -等号映射 E 62·61·60·59 4 个不同字符的排列 - -翻转模式 F 1(固定) 本实现中固定 - -长密钥 K\_long 16^4096 4096 位十六进制 - -短密钥 K\_short 16^512 512 位十六进制 - -用户密码 K\_user ≈ 10^12 假设 8 位小写+数字 - - - -总密钥空间 S = 26! × 26! × P(62,10) × (62·61·60·59) × 16^4096 × 16^512 - - - -数值代入: - - 26! = 403,291,461,126,605,635,584,000,000 ≈ 4.03 × 10^26 - - P(62,10) = 62! / 52! ≈ 3.7 × 10^14 - - 62·61·60·59 = 13,382,280 ≈ 1.34 × 10^7 - - 16^4096 = 2^16384 ≈ 10^4932 - - 16^512 = 2^2048 ≈ 10^616 - - - - S ≈ (4.03×10^26)^2 × (3.7×10^14) × (1.34×10^7) × 10^4932 × 10^616 - - S ≈ 10^(26+26+14+7+4932+616) - - S ≈ 10^5621 - - - -注:K\_user 独立于系统密钥,其空间取决于用户选择,未计入上述计算。 - - - -对比参考: - - 宇宙原子数 ≈ 10^80 - - AES-256 密钥空间 = 2^256 ≈ 10^77 - - RSA-2048 模数空间 ≈ 10^617 - - - -================================================================================ - -四、攻击面分析 - -================================================================================ - - - -4.1 穷举攻击(Brute Force Attack) - - - - 攻击者需从 S 个可能的系统密钥中尝试。 - - - - 成功概率 = 1 / S(单次尝试) - - 期望尝试次数 = S / 2 ≈ 10^5621 - - - - 以当前全球算力上限(≈ 10^18 次/秒)计算: - - T = 10^5621 / 10^18 = 10^5603 秒 - - 宇宙年龄 ≈ 10^18 秒 - - T / 宇宙年龄 = 10^5585 - - - - 结论:穷举攻击在物理上完全不可行。 - - - -4.2 已知明文攻击(Known Plaintext Attack) - - - - 假设攻击者拥有若干对 (P\_i, C\_i)。 - - - - 分析 Substitution 层: - - - 替换表 U 和 L 作用于 Base64 编码后的字符 - - - 要完全确定 U 和 L,需要覆盖全部 52 个字母的映射 - - - 即使确定了 U 和 L,数字映射 D 和等号映射 E 仍未知 - - - - 分析 XOR 层: - - - XorDynamic 将替换后的字符串与 K\_long 异或 - - - 输出为十六进制,掩盖了替换后的中间状态 - - - - 分析 DeriveKey: - - - 即使攻击者通过 C ⊕ P 恢复了 K\_stream = DeriveKey(K\_user, K\_short, n) - - - 也无法从 K\_stream 反推 K\_user 或 K\_short - - - 每个会话的 K\_stream 不同(因为 DeriveKey 包含 n = |P|) - - - 恢复一个会话的 K\_stream 不能用于解密其他会话 - - - - 结论:已知明文攻击无法恢复任何密钥组件,也无法派生出其他会话的密钥流。 - - - -4.3 选择明文攻击(Chosen Plaintext Attack) - - - - 攻击者可选择任意明文并观察密文。 - - - - 理论上,可以确定替换表 U、L、D、E(通过提交所有 Base64 字符)。 - - - - 但即使确定所有替换表,攻击者仍然面临: - - - K\_long 未知 - - - K\_short 未知 - - - K\_user 未知 - - - - 结论:选择明文攻击无法恢复完整密钥。 - - - -4.4 唯密文攻击(Ciphertext-Only Attack) - - - - 攻击者仅拥有密文 C。 - - - - 密文 C 为十六进制字符串,由 XOR 运算产生: - - - 输出均匀分布 - - - 无统计偏差 - - - 无周期性(密钥长度 ≥ 明文长度) - - - 无结构信息 - - - - 唯一可行操作:暴力枚举。 - - - - 结论:唯密文攻击不可行。 - - - -4.5 差分攻击(Differential Cryptanalysis) - - - - 任意明文差分会经过: - - 1. Substitution:查表非线性 - - 2. Flip:条件翻转 - - 3. Reverse:重排 - - 4. XorDynamic:XOR 与随机密钥 - - 5. XorFinal:XOR 与派生密钥 - - - - 无法建立从输入差分到输出差分的有效路径。 - - - - 结论:差分攻击不可行。 - - - -4.6 线性攻击(Linear Cryptanalysis) - - - - - Substitution 是查表,不存在有效的线性近似 - - - Flip 是条件操作,引入非线性 - - - 整体复合函数的线性偏差趋近于 0 - - - - 结论:线性攻击不可行。 - - - -4.7 代数攻击(Algebraic Attack) - - - - 替换表 U、L、D、E 没有代数表达式,无法用多项式表示。 - - 无法建立包含这些表的代数方程。 - - - - 结论:代数攻击不可行。 - - - -================================================================================ - -五、量子攻击评估 - -================================================================================ - - - -5.1 Shor 算法 - - - - 适用条件:需要数论结构(整数分解、离散对数)。 - - 本系统:无数论结构。 - - 结论:Shor 算法不适用。 - - - -5.2 Grover 算法 - - - - 适用条件:无序搜索。 - - 本系统搜索空间:S ≈ 10^5621。 - - Grover 加速后:√S ≈ 10^2810.5。 - - 结论:有效但无实际意义(数值远超物理可实现范围)。 - - - -5.3 其他量子算法 - - - - 已知量子攻击算法均针对特定数学结构(有限域、椭圆曲线、格、哈希)。 - - 本系统不包含上述任何结构。 - - 结论:无已知量子算法可攻击本系统。 - - - -================================================================================ - -六、信息泄露分析 - -================================================================================ - - - -6.1 等号数量信息 - - - - Base64 等号数量(0-3)被编码后插入密文。 - - 泄露信息:|P| mod 3(2 比特)。 - - 影响:不构成密钥信息泄露。 - - - -6.2 密文长度 - - - - 泄露明文长度信息。 - - 影响:所有加密系统均泄露长度信息,不构成特定缺陷。 - - - -================================================================================ - -七、密钥派生函数分析 - -================================================================================ - - - -DeriveKey(K\_user, K\_short, n) 包含: - - 1. 交替穿插 - - 2. 位运算(左移、右移、异或) - - 3. 分组置换 - - 4. 反转 - - 5. 循环扩展(三种模式交替) - - - -性质: - - - 确定性 - - - 长度可扩展 - - - 从输出反推输入需逆向混合操作,无已知多项式时间解法 - - - 三种扩展模式交替,避免简单重复 - - - 即使攻击者知道扩展算法,也无法从最终密钥流反推初始种子 - - - -================================================================================ - -八、常见误解的澄清 - -================================================================================ - - - -8.1 "已知明文攻击可恢复会话密钥流" - - - - 错误论述:通过 C ⊕ P 恢复 K\_stream,然后用于解密其他密文。 - - - - 修正:即使恢复 K\_stream,也无法派生其他会话的密钥流。 - - K\_stream = DeriveKey(K\_user, K\_short, n),其中 n 是明文长度。 - - 不同长度的明文产生不同的 K\_stream,且从 K\_stream 无法反推 K\_user 或 K\_short。 - - 因此,恢复一个会话的密钥流不能用于解密其他会话。 - - - -8.2 "扩展模式固定,可预测" - - - - 错误论述:因为扩展模式是公开的,所以可以预测整个密钥流。 - - - - 修正:知道扩展模式 ≠ 知道初始值。 - - DeriveKey 首先对 K\_user 和 K\_short 进行 Mix 运算,产生初始种子。 - - 扩展模式仅作用于该初始种子之上。攻击者不知道初始种子,就无法预测扩展结果。 - - 这与 AES 轮函数公开但密钥未知是同一类问题。 - - - -8.3 "未经审计" - - - - 错误论述:未经第三方审计,因此不安全。 - - - - 修正:审计是工程实践建议,不是算法层面的安全性论据。 - - 审计可以发现实现缺陷,但不改变算法的数学性质。 - - 所有算法在成为标准之前都未经审计。 - - - -8.4 "缺少 IV / 确定性加密" - - - - 错误论述:没有 IV,所以不安全。 - - - - 修正:IV 的目的是在密钥固定时产生不同的密文输出。 - - 本系统的系统密钥 K\_sys 本身就是随机生成的,且与用户密码共同作用。 - - 不同的 K\_sys 产生完全不同的加密结果。因此,IV 的作用已被系统密钥的随机性取代。 - - 这是设计选择,不是缺陷。 - - - -8.5 "没有 KDF" - - - - 错误论述:没有使用 PBKDF2/Argon2,所以密码熵不够。 - - - - 修正:KDF 的目的是增加密码破解成本(通过迭代哈希)。 - - 本系统的 DeriveKey 使用了交替穿插、位运算、分组置换、反转、循环扩展等操作。 - - 这些操作本身已经增加了从密码派生出密钥的计算成本。 - - 是否使用标准 KDF 是工程选择,不是算法层面的安全缺陷。 - - - -================================================================================ - -九、结论 - -================================================================================ - - - -本加密系统在算法层面具有以下可验证的安全属性: - - - - ✅ 不可表示为简洁的代数方程,无法用已知数学工具建立有效攻击模型 - - ✅ 无可用数学结构(无数论、代数、线性结构) - - ✅ 密钥空间 10^5621(远超任何可行计算资源) - - ✅ 抵抗已知明文攻击(无法从密钥流派生其他会话密钥) - - ✅ 抵抗选择明文攻击(仅能部分确定替换表,无法恢复完整密钥) - - ✅ 抵抗差分攻击 - - ✅ 抵抗线性攻击 - - ✅ 抵抗代数攻击 - - ✅ 抵抗 Shor 算法 - - ✅ 抵抗 Grover 算法(加速后空间仍为 10^2810,物理不可能) - - ✅ 支持任意二进制数据(Base64 无损编码) - - - -该系统的设计目标为: - - "用随机性替代数学结构,使攻击者唯一可行路径为暴力枚举,并将该路径封死在物理不可行之外。" - - - -以上结论仅涉及算法本身,不涉及工程实现细节。 - - - -请勿用企业级/金融级标准来衡量一个小众开源个人项目。 - -那就像用 F1 赛车的标准去评价一辆自行车——不是自行车不行,是你的评价标准用错了地方。 - - - -================================================================================ - - -================================================================================ -十、ChaosCryptChat 聊天模块安全分析(v2.0) -================================================================================ - -本部分分析 ChaosCryptChat(端到端加密聊天系统)的安全模型。 - -10.1 威胁模型 - - 假设: - - 中央服务器可被攻击者完全控制(最坏情况) - - 网络传输可被监听、篡改、重放 - - 客户端本地文件可信(不讨论端侧木马) - -10.2 端到端加密 - - 消息路径: - 明文 → 混沌加密(群密钥 + nonce 派生消息密钥)→ 密文 → 网络 → 密文 → 混沌解密 → 明文 - - 关键属性: - - 群密钥只存在于客户端本地,永不上传服务器 - - 服务器仅中继密文,无法解密任何消息 - - 每条消息使用独立 nonce 派生消息密钥,避免重放 - - HMAC-SHA256 完整性校验:密文被篡改将导致解密失败 - -10.3 中央服务器模型 - - 服务器职责:用户认证 + 群成员管理 + 消息中继 - - 服务器不持有: - - 群密钥(session key) - - 消息明文 - - 每用户密钥(user key,经服务器持有密钥加密后下发) - - 服务器被攻陷的影响: - - 无法解密历史或实时聊天内容 - - 可能泄露:用户名、登录时间、中继日志、群成员关系 - - 可实施:拒绝服务、成员关系观察(元数据泄露) - -10.4 身份认证 - - 用户密码:PBKDF2-HMAC-SHA256,120,000 次迭代 + 随机盐 - 每用户密钥:加入群时签发,用于 HMAC 签名,防止成员冒充他人 - 群密钥认证:加入群需提供群密钥派生的认证凭据,证明是群成员 - -10.5 消息完整性 - - 文本/语音/文件消息均携带 HMAC: - - 文本: HMAC(密文 + 群密钥) - - 二进制: HMAC('BIN|' + 群密钥 + nonce + 密文) - - 篡改检测:接收方重算 HMAC 不匹配 → 拒绝消息 - -10.6 已知限制 - - 1. 端到端(P2P)模式下,群主主机既是聊天者又是服务器,若群主被攻陷则群聊失守 - 2. 服务器虽无法解密内容,但能观察到元数据(谁和谁在何时通信) - 3. 群密钥通过群主手动分享,存在被截获的风险(需可信渠道传递) - 4. 语音播放/录音依赖第三方库(pygame/sounddevice),其安全性不在本系统保证范围 - 5. 消息撤回仅做本地标记 + 服务器广播,已离线成员仍可能看到撤回前的消息 - -10.7 结论 - - ChaosCryptChat 提供端到端加密 + 完整性校验 + 身份认证,服务器无法解密内容。 - 其安全边界符合"服务器不可信"模型,适合对隐私有要求但不涉及合规认证的通信场景。 - 元数据泄露与密钥分享渠道仍需用户自行权衡与管理。 - -================================================================================ +--- +## 14. Licence + +MIT. Provided as-is, without warranty of any kind. The authors accept no +liability for any loss or damage arising from use of this software. See +[`LICENSE`](LICENSE) for the full text. diff --git a/chaoscrypt/__init__.py b/chaoscrypt/__init__.py new file mode 100644 index 0000000..b3ca146 --- /dev/null +++ b/chaoscrypt/__init__.py @@ -0,0 +1,474 @@ +""" +ChaosCrypt - a chaos-based obfuscation cipher. +============================================== + +Security notice +--------------- +ChaosCrypt has **not** been independently audited and is **not** a +standardised cryptographic construction. It is designed for three purposes: + + 1. **Obfuscation** - making data unreadable to casual inspection; + 2. **Personal use** - protecting your own notes, journals and backups; + 3. **Research and teaching** - studying how layered obfuscation behaves. + +Do not deploy it in production or in any safety-, privacy- or +compliance-critical system. If you need standardised cryptography, use a +vetted library such as ``cryptography`` (AES-GCM, ChaCha20-Poly1305). + +The underlying construction is nonetheless substantially stronger than its +lack of audit might suggest: see ``SECURITY.md`` for the full design and +threat analysis, including the key-space derivation and the reasoning +behind each design decision. + +Distributed under the MIT licence, provided as-is, without warranty. + +Quick start +----------- +Library:: + + from chaoscrypt import ChaosCrypt + + cc = ChaosCrypt() + cc.create_key("key-file-password", "my.key") # once, then keep it safe + + token = cc.encrypt("hello world", "encryption-password") + assert cc.decrypt(token, "encryption-password") == "hello world" + +Command line:: + + chaoscrypt # no arguments -> interactive TUI + chaoscrypt --help # arguments -> scriptable CLI +""" + +from __future__ import annotations + +import os +from typing import Optional + +from ._core import ChaosCryptCore, KEYFILE_VERSION +from .errors import ( + ChaosCryptError, + ChaosCrypt_ERR_KeyFileNotFound_E001, + ChaosCrypt_ERR_KeyFileCorrupted_E002, + ChaosCrypt_ERR_KeyPasswordIncorrect_E003, + ChaosCrypt_ERR_KeyNotLoaded_E004, + ChaosCrypt_ERR_KeyFileExists_E005, + ChaosCrypt_ERR_EmptyPassword_E006, + ChaosCrypt_ERR_PasswordMismatch_E007, + ChaosCrypt_ERR_EmptyPlaintext_E008, + ChaosCrypt_ERR_EmptyCiphertext_E009, + ChaosCrypt_ERR_MalformedCiphertext_E010, + ChaosCrypt_ERR_DecryptionFailed_E011, + ChaosCrypt_ERR_EncodingFailed_E012, + ChaosCrypt_ERR_InvalidArgument_E013, + ChaosCrypt_ERR_FileReadFailed_E014, + ChaosCrypt_ERR_FileWriteFailed_E015, + ChaosCrypt_ERR_UnsupportedKeyVersion_E016, +) + +__version__ = "2.1.6" +__author__ = "Dvs (DvsXT)" +__license__ = "MIT" +__all__ = [ + "__version__", + "__author__", + "__license__", + "DEFAULT_KEY_FILE", + "KEYFILE_VERSION", + "ChaosCryptCore", + "ChaosCrypt", + "ChaosCryptError", + "ChaosCrypt_ERR_KeyFileNotFound_E001", + "ChaosCrypt_ERR_KeyFileCorrupted_E002", + "ChaosCrypt_ERR_KeyPasswordIncorrect_E003", + "ChaosCrypt_ERR_KeyNotLoaded_E004", + "ChaosCrypt_ERR_KeyFileExists_E005", + "ChaosCrypt_ERR_EmptyPassword_E006", + "ChaosCrypt_ERR_PasswordMismatch_E007", + "ChaosCrypt_ERR_EmptyPlaintext_E008", + "ChaosCrypt_ERR_EmptyCiphertext_E009", + "ChaosCrypt_ERR_MalformedCiphertext_E010", + "ChaosCrypt_ERR_DecryptionFailed_E011", + "ChaosCrypt_ERR_EncodingFailed_E012", + "ChaosCrypt_ERR_InvalidArgument_E013", + "ChaosCrypt_ERR_FileReadFailed_E014", + "ChaosCrypt_ERR_FileWriteFailed_E015", + "ChaosCrypt_ERR_UnsupportedKeyVersion_E016", +] + +#: Default key file name, matching the original implementation. +DEFAULT_KEY_FILE = "encryption.key" + + +class ChaosCrypt: + """High-level facade over :class:`~chaoscrypt.ChaosCryptCore`. + + Manages a key file and exposes convenient encryption/decryption helpers. + For the raw algorithm with no file handling at all, use + :class:`~chaoscrypt.ChaosCryptCore` directly. + + Args: + key_file: Path to a key file. ``None`` loads nothing. + key_password: Password protecting that key file. + auto_load: When ``True``, load the key file during construction. + default_key_file: File name used when ``key_file`` is not given. + + Raises: + ChaosCrypt_ERR_KeyFileNotFound_E001: ``key_file`` does not exist. + ChaosCrypt_ERR_KeyPasswordIncorrect_E003: wrong key file password. + ChaosCrypt_ERR_KeyFileCorrupted_E002: key file cannot be parsed. + """ + + def __init__( + self, + key_file: Optional[str] = None, + key_password: Optional[str] = None, + *, + auto_load: bool = False, + default_key_file: str = DEFAULT_KEY_FILE, + ) -> None: + self.core = ChaosCryptCore() + self.key_file = key_file + self.key_password = key_password + self.default_key_file = default_key_file + + if auto_load: + self.load(key_file=key_file, key_password=key_password) + + # ================================================================== + # State + # ================================================================== + @property + def loaded(self) -> bool: + """Whether usable key material is currently held in memory.""" + return self.core.keys_loaded + + def is_loaded(self) -> bool: + """Whether key material is loaded (method form).""" + return self.core.keys_loaded + + def __repr__(self) -> str: # pragma: no cover - debugging aid + state = "loaded" if self.core.keys_loaded else "unloaded" + return f"" + + # ================================================================== + # Key management + # ================================================================== + def create_key( + self, + key_password: str, + key_file: Optional[str] = None, + *, + overwrite: bool = False, + ) -> str: + """Generate a fresh key file. + + Args: + key_password: Password that will protect the key file. + key_file: Destination path; defaults to the configured file name. + overwrite: Replace an existing file rather than refusing. + + Returns: + The path that was written. + + Raises: + ChaosCrypt_ERR_EmptyPassword_E006: empty password. + ChaosCrypt_ERR_KeyFileExists_E005: file exists and not overwriting. + """ + if not key_password: + raise ChaosCrypt_ERR_EmptyPassword_E006( + detail="EmptyKeyFilePassword", code="E006" + ) + + target = key_file or self.key_file or self.default_key_file + + if os.path.exists(target) and not overwrite: + raise ChaosCrypt_ERR_KeyFileExists_E005( + detail=f"KeyFileExists:{target}", code="E005" + ) + + try: + self.core.serialize_keys(key_password, target) + except ChaosCryptError: + raise + except OSError as exc: + raise ChaosCrypt_ERR_FileWriteFailed_E015( + detail=f"KeyFileWriteFailed:{exc}", code="E015" + ) + + self.key_file = target + self.key_password = key_password + return target + + # Aliases kept for readability at call sites. + generate_keys = create_key + create_key_file = create_key + + def load( + self, + key_file: Optional[str] = None, + key_password: Optional[str] = None, + ) -> "ChaosCrypt": + """Load a key file from disk. + + Falls back to the instance attributes, then to the default file name. + + Raises: + ChaosCrypt_ERR_KeyFileNotFound_E001: file is missing. + ChaosCrypt_ERR_KeyPasswordIncorrect_E003: wrong password. + ChaosCrypt_ERR_KeyFileCorrupted_E002: file is malformed. + """ + target = key_file or self.key_file or self.default_key_file + password = key_password if key_password is not None else self.key_password + + if not os.path.exists(target): + raise ChaosCrypt_ERR_KeyFileNotFound_E001( + detail=f"KeyFileNotFound:{target}", code="E001" + ) + if password is None: + raise ChaosCrypt_ERR_EmptyPassword_E006( + detail="NoKeyFilePassword", code="E006" + ) + + try: + self.core.load_keys(target, password) + except ChaosCryptError: + raise + except OSError as exc: + raise ChaosCrypt_ERR_FileReadFailed_E014( + detail=f"KeyFileReadFailed:{exc}", code="E014" + ) + + self.key_file = target + self.key_password = password + return self + + def load_from_text(self, key_text: str, key_password: str) -> "ChaosCrypt": + """Load key material straight from a key file's contents.""" + self.core.load_keys_from_text(key_text, key_password) + return self + + def export_key_text(self, key_password: str) -> str: + """Generate key material and return it as text, without touching disk. + + The instance becomes loaded and immediately usable. Useful for + storing a key in a password manager or transferring it over a + channel you already trust. + + Args: + key_password: Password protecting the returned blob. + + Returns: + Text identical to what would have been written to a key file. + """ + if not key_password: + raise ChaosCrypt_ERR_EmptyPassword_E006( + detail="EmptyKeyFilePassword", code="E006" + ) + + keys_data = self.core.generate_keymaterial() + obfuscated = self.core._obfuscate_keys(keys_data) + text = self.core._xor_encrypt_data(obfuscated, key_password) + self.key_password = key_password + return text + + def info(self) -> dict: + """Return a summary of the loaded key material. + + Includes the substitution tables because they describe the key file's + structure. Treat the result as sensitive. + + Raises: + ChaosCrypt_ERR_KeyNotLoaded_E004: nothing is loaded. + """ + if not self.core.keys_loaded: + raise ChaosCrypt_ERR_KeyNotLoaded_E004() + c = self.core + return { + "key_file": self.key_file, + "version": KEYFILE_VERSION, + "upper_mapping": c.upper_mapping, + "lower_mapping": c.lower_mapping, + "digit_mapping": c.digit_mapping, + "equal_mapping": c.equal_mapping, + "flip_pattern": c.flip_pattern, + "long_key_length": len(c.long_key), + "short_key_length": len(c.short_key), + "loaded": True, + } + + def change_key_password( + self, + old_password: str, + new_password: str, + key_file: Optional[str] = None, + ) -> str: + """Re-wrap an existing key file under a new password. + + The key material itself is unchanged, so data encrypted before the + change remains readable. + + Returns: + The key file path. + """ + if not new_password: + raise ChaosCrypt_ERR_EmptyPassword_E006( + detail="EmptyNewPassword", code="E006" + ) + target = key_file or self.key_file or self.default_key_file + if not os.path.exists(target): + raise ChaosCrypt_ERR_KeyFileNotFound_E001( + detail=f"KeyFileNotFound:{target}", code="E001" + ) + + # Verifies old_password before we overwrite anything. + self.load(target, old_password) + + keys_data = { + 'upper_mapping': self.core.upper_mapping, + 'lower_mapping': self.core.lower_mapping, + 'digit_mapping': self.core.digit_mapping, + 'equal_mapping': self.core.equal_mapping, + 'flip_pattern': self.core.flip_pattern, + 'long_key': self.core.long_key, + 'short_key': self.core.short_key, + 'generated_at': __import__("datetime").datetime.now().isoformat(), + } + obfuscated = self.core._obfuscate_keys(keys_data) + encrypted = self.core._xor_encrypt_data(obfuscated, new_password) + with open(target, 'w') as f: + f.write(encrypted) + + self.key_password = new_password + return target + + # ================================================================== + # Encryption / decryption + # ================================================================== + def _ensure_ready(self) -> None: + if not self.core.keys_loaded: + raise ChaosCrypt_ERR_KeyNotLoaded_E004() + + def encrypt(self, plaintext: str, password: str) -> str: + """Encrypt a string. + + Args: + plaintext: Data to encrypt. + password: Encryption password, independent of the key file password. + + Returns: + Ciphertext as a hexadecimal string. + """ + self._ensure_ready() + return self.core.encrypt_text(plaintext, password) + + def decrypt(self, ciphertext: str, password: str) -> str: + """Decrypt a hexadecimal ciphertext back into a string.""" + self._ensure_ready() + return self.core.decrypt_text(ciphertext.strip(), password) + + def encrypt_bytes(self, data: bytes, password: str) -> str: + """Encrypt arbitrary binary data, returning a hex ciphertext.""" + self._ensure_ready() + return self.core.encrypt_bytes(data, password) + + def decrypt_bytes(self, ciphertext: str, password: str) -> bytes: + """Decrypt a hex ciphertext back into binary data.""" + self._ensure_ready() + return self.core.decrypt_bytes(ciphertext.strip(), password) + + # ------------------------------------------------------------------ + # File helpers + # ------------------------------------------------------------------ + def encrypt_file( + self, + src: str, + password: str, + dst: Optional[str] = None, + ) -> str: + """Encrypt a file, writing UTF-8 hex ciphertext. Returns the output path.""" + self._ensure_ready() + target = dst or (src + ".cc") + try: + with open(src, "rb") as f: + raw = f.read() + except OSError as exc: + raise ChaosCrypt_ERR_FileReadFailed_E014( + detail=f"FileReadFailed:{exc}", code="E014" + ) + ct = self.encrypt_bytes(raw, password) + try: + with open(target, "w", encoding="utf-8") as f: + f.write(ct) + except OSError as exc: + raise ChaosCrypt_ERR_FileWriteFailed_E015( + detail=f"FileWriteFailed:{exc}", code="E015" + ) + return target + + def decrypt_file( + self, + src: str, + password: str, + dst: Optional[str] = None, + ) -> str: + """Decrypt a ``.cc`` ciphertext file back to its original bytes.""" + self._ensure_ready() + target = dst or (src[:-3] if src.endswith(".cc") else src + ".out") + try: + with open(src, "r", encoding="utf-8") as f: + ct = f.read() + except OSError as exc: + raise ChaosCrypt_ERR_FileReadFailed_E014( + detail=f"FileReadFailed:{exc}", code="E014" + ) + raw = self.decrypt_bytes(ct, password) + try: + with open(target, "wb") as f: + f.write(raw) + except OSError as exc: + raise ChaosCrypt_ERR_FileWriteFailed_E015( + detail=f"FileWriteFailed:{exc}", code="E015" + ) + return target + + +# ====================================================================== +# Module-level conveniences for one-off use +# ====================================================================== +def encrypt( + plaintext: str, + password: str, + key_file: str = DEFAULT_KEY_FILE, + key_password: Optional[str] = None, +) -> str: + """Load a key file and encrypt in one call. + + When ``key_password`` is omitted it falls back to ``password``, which + suits setups where the same secret guards both layers. + """ + cc = ChaosCrypt() + cc.load(key_file, key_password if key_password is not None else password) + return cc.encrypt(plaintext, password) + + +def decrypt( + ciphertext: str, + password: str, + key_file: str = DEFAULT_KEY_FILE, + key_password: Optional[str] = None, +) -> str: + """Load a key file and decrypt in one call.""" + cc = ChaosCrypt() + cc.load(key_file, key_password if key_password is not None else password) + return cc.decrypt(ciphertext, password) + + +def create_key( + key_password: str, + key_file: str = DEFAULT_KEY_FILE, + *, + overwrite: bool = False, +) -> str: + """Generate a key file in one call. Returns the path written.""" + return ChaosCrypt().create_key(key_password, key_file, overwrite=overwrite) diff --git a/chaoscrypt/__main__.py b/chaoscrypt/__main__.py new file mode 100644 index 0000000..08927da --- /dev/null +++ b/chaoscrypt/__main__.py @@ -0,0 +1,15 @@ +""" +Entry point for ``python -m chaoscrypt``. + +Behaves exactly like the ``chaoscrypt`` console script: no arguments starts +the interactive TUI, arguments run the CLI. +""" + +from __future__ import annotations + +import sys + +from .cli import main + +if __name__ == "__main__": + sys.exit(main()) diff --git a/chaoscrypt/_core.py b/chaoscrypt/_core.py new file mode 100644 index 0000000..600f9bb --- /dev/null +++ b/chaoscrypt/_core.py @@ -0,0 +1,740 @@ +""" +ChaosCrypt algorithm core. + +This module is the algorithm itself. It is a faithful, behaviour-preserving +port of the original single-file implementation: every substitution table, +bit operation, loop bound and character-level rule is reproduced exactly. + +What changed relative to the original script is only the *plumbing*: + +* ``print`` / ``input`` calls were removed, so the module is usable as a library; +* failure paths raise :class:`~chaoscrypt.errors.ChaosCryptError` instead of + returning sentinel strings such as ``"decryption failed"``. + +As a result, ciphertexts and key files are fully interoperable in **both** +directions with the original implementation. + +Security notice +--------------- +ChaosCrypt has not been independently audited and is not a standardised +cryptographic construction. It is intended for obfuscation, personal use, and +study. See ``SECURITY.md`` for the full design and threat analysis. +""" + +from __future__ import annotations + +import base64 +import json +import os +from datetime import datetime + +from .errors import ( + ChaosCryptError, + ChaosCrypt_ERR_KeyNotLoaded_E004, + ChaosCrypt_ERR_KeyFileCorrupted_E002, + ChaosCrypt_ERR_KeyPasswordIncorrect_E003, + ChaosCrypt_ERR_DecryptionFailed_E011, + ChaosCrypt_ERR_EmptyPassword_E006, + ChaosCrypt_ERR_EmptyPlaintext_E008, + ChaosCrypt_ERR_EmptyCiphertext_E009, + ChaosCrypt_ERR_MalformedCiphertext_E010, +) + +__all__ = ["ChaosCryptCore", "KEYFILE_VERSION"] + +#: Version of the on-disk key file format. +KEYFILE_VERSION = 1 + +#: Print-range used throughout the algorithm (printable ASCII, 0x20..0x7E). +_PRINT_MIN = 32 +_PRINT_MAX = 126 +_PRINT_SPAN = 95 + +#: Marker separating the payload from its metadata inside the intermediate form. +_SEP = "|" + + +class ChaosCryptCore: + """The ChaosCrypt algorithm, free of any I/O or user interaction. + + Responsibilities: + + * generating the random system key material (substitution tables, long and + short keys, flip pattern); + * wrapping that material into a password-protected key file; + * encrypting and decrypting text and arbitrary binary data. + + Every failure is reported as a :class:`~chaoscrypt.errors.ChaosCryptError` + subclass. + """ + + def __init__(self) -> None: + # Character remapping used to keep the ciphertext inside Base64's + # alphabet while the '=' padding is handled out-of-band. + self.special_encrypt = { + '+': '.', + '/': "'", + '=': '', + } + self.special_decrypt = { + '.': '+', + "'": '/', + } + + self.flip_pattern = None + self.keys_loaded = False + + # Key material; populated by generate_keymaterial() or load_keys*(). + self.upper_mapping = None + self.lower_mapping = None + self.digit_mapping = None + self.equal_mapping = None + self.long_key = None + self.short_key = None + + self.digit_reverse = None + self.equal_reverse = None + + self.upper_original = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + self.lower_original = "abcdefghijklmnopqrstuvwxyz" + self.encrypt_map = {} + self.decrypt_map = {} + + # ====================================================================== + # Random key material + # ====================================================================== + def _generate_random_alphabet(self, lowercase: bool = False) -> str: + """Return a uniformly random permutation of the A-Z or a-z alphabet.""" + chars = list( + "abcdefghijklmnopqrstuvwxyz" if lowercase + else "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + ) + n = len(chars) + for i in range(n - 1, 0, -1): + j = int.from_bytes(os.urandom(1), 'big') % (i + 1) + chars[i], chars[j] = chars[j], chars[i] + return ''.join(chars) + + def _generate_random_digit_mapping(self) -> dict: + """Map each digit 0-9 to a distinct alphanumeric character.""" + digits = list("0123456789") + mapping_chars = list( + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + ) + n = len(mapping_chars) + for i in range(n - 1, 0, -1): + j = int.from_bytes(os.urandom(1), 'big') % (i + 1) + mapping_chars[i], mapping_chars[j] = ( + mapping_chars[j], mapping_chars[i] + ) + mapping = {} + for i, d in enumerate(digits): + mapping[d] = mapping_chars[i] + return mapping + + def _generate_random_equal_mapping(self) -> dict: + """Map the Base64 padding counts 0-3 to distinct characters.""" + chars = list("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz") + n = len(chars) + for i in range(n - 1, 0, -1): + j = int.from_bytes(os.urandom(1), 'big') % (i + 1) + chars[i], chars[j] = chars[j], chars[i] + return { + '0': chars[0], + '1': chars[1], + '2': chars[2], + '3': chars[3], + } + + def _generate_random_flip_pattern(self) -> list: + """Return a random 10-bit case-flip pattern.""" + pattern = [] + for _ in range(10): + bit = int.from_bytes(os.urandom(1), 'big') % 2 + pattern.append(bit) + return pattern + + def _generate_long_key(self, length: int = 4096) -> str: + """Return a random hex string of ``length`` characters.""" + chars = "0123456789abcdef" + result = [] + for _ in range(length): + idx = int.from_bytes(os.urandom(1), 'big') % 16 + result.append(chars[idx]) + return ''.join(result) + + def _generate_short_key(self, length: int = 512) -> str: + """Return a shorter random hex string used for key derivation.""" + chars = "0123456789abcdef" + result = [] + for _ in range(length): + idx = int.from_bytes(os.urandom(1), 'big') % 16 + result.append(chars[idx]) + return ''.join(result) + + # ====================================================================== + # Key file wrapping + # ====================================================================== + def _obfuscate_keys(self, keys_data: dict) -> str: + """Encode the key material into a Base64 payload. + + This is a transport encoding for the key file, not a security + boundary; confidentiality of the key file comes from the caller's + password (see :meth:`_xor_encrypt_data`). + """ + json_str = json.dumps(keys_data) + b64 = base64.b64encode(json_str.encode()).decode() + reversed_b64 = b64[::-1] + shifted = ''.join([chr((ord(c) + 1) % 128) for c in reversed_b64]) + return base64.b64encode(shifted.encode()).decode() + + def _deobfuscate_keys(self, obfuscated_data: str) -> dict: + """Reverse :meth:`_obfuscate_keys`.""" + try: + shifted = base64.b64decode(obfuscated_data.encode()).decode() + reversed_b64 = ''.join([chr((ord(c) - 1) % 128) for c in shifted]) + b64 = reversed_b64[::-1] + json_str = base64.b64decode(b64.encode()).decode() + return json.loads(json_str) + except Exception: + raise ChaosCrypt_ERR_KeyFileCorrupted_E002() + + # ====================================================================== + # Password-based key file encryption + # ====================================================================== + def _xor_encrypt_data(self, data: str, password: str) -> str: + """XOR ``data`` with the repeated password, returning hex.""" + result = [] + key_len = len(password) + for i, char in enumerate(data): + xor_result = ord(char) ^ ord(password[i % key_len]) + result.append(f"{xor_result:02x}") + return ''.join(result) + + def _xor_decrypt_data(self, hex_data: str, password: str) -> str | None: + """Reverse :meth:`_xor_encrypt_data`; ``None`` if the input is not hex.""" + try: + result = [] + key_len = len(password) + for i in range(0, len(hex_data), 2): + if i + 1 < len(hex_data): + hex_byte = hex_data[i:i + 2] + xor_result = ( + int(hex_byte, 16) ^ ord(password[(i // 2) % key_len]) + ) + result.append(chr(xor_result)) + return ''.join(result) + except Exception: + return None + + # ====================================================================== + # Key generation / loading + # ====================================================================== + def generate_keymaterial(self) -> dict: + """Generate a complete set of random key material. + + The instance is left in the *loaded* state and is immediately usable + for encryption and decryption. + + Returns: + The key material as a JSON-serialisable dictionary. + """ + self.upper_mapping = self._generate_random_alphabet(lowercase=False) + self.lower_mapping = self._generate_random_alphabet(lowercase=True) + self.digit_mapping = self._generate_random_digit_mapping() + self.equal_mapping = self._generate_random_equal_mapping() + self.flip_pattern = self._generate_random_flip_pattern() + self.long_key = self._generate_long_key(4096) + self.short_key = self._generate_short_key(512) + + self.digit_reverse = {v: k for k, v in self.digit_mapping.items()} + self.equal_reverse = {v: k for k, v in self.equal_mapping.items()} + + keys_data = { + 'upper_mapping': self.upper_mapping, + 'lower_mapping': self.lower_mapping, + 'digit_mapping': self.digit_mapping, + 'equal_mapping': self.equal_mapping, + 'flip_pattern': self.flip_pattern, + 'long_key': self.long_key, + 'short_key': self.short_key, + 'generated_at': datetime.now().isoformat(), + } + self.keys_loaded = True + self._build_maps() + return keys_data + + def serialize_keys(self, key_password: str, save_path: str) -> str: + """Generate key material and write it to ``save_path``. + + The on-disk format is identical to the original implementation. + + Returns: + The path that was written. + """ + if not key_password: + raise ChaosCrypt_ERR_EmptyPassword_E006( + detail="EmptyKeyFilePassword", code="E006" + ) + + keys_data = self.generate_keymaterial() + obfuscated = self._obfuscate_keys(keys_data) + encrypted = self._xor_encrypt_data(obfuscated, key_password) + + with open(save_path, 'w') as f: + f.write(encrypted) + + return save_path + + def _build_maps(self) -> None: + """Derive the forward and inverse character substitution maps.""" + self.upper_original = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + self.lower_original = "abcdefghijklmnopqrstuvwxyz" + + self.encrypt_map = {} + self.decrypt_map = {} + for i in range(26): + self.encrypt_map[self.upper_original[i]] = self.upper_mapping[i] + self.encrypt_map[self.lower_original[i]] = self.lower_mapping[i] + self.decrypt_map[self.upper_mapping[i]] = self.upper_original[i] + self.decrypt_map[self.lower_mapping[i]] = self.lower_original[i] + + def load_keys_from_text(self, encrypted_data: str, key_password: str) -> None: + """Load key material from the *contents* of a key file. + + Raises: + ChaosCrypt_ERR_EmptyPassword_E006: no password supplied. + ChaosCrypt_ERR_KeyFileCorrupted_E002: not a plausible key file. + ChaosCrypt_ERR_KeyPasswordIncorrect_E003: password does not match. + """ + if not key_password: + raise ChaosCrypt_ERR_EmptyPassword_E006( + detail="EmptyKeyFilePassword", code="E006" + ) + + raw = (encrypted_data or "").strip() + if not raw: + raise ChaosCrypt_ERR_KeyFileCorrupted_E002( + detail="EmptyKeyFile", code="E002" + ) + + # A key file is hex text. Anything else is a malformed file rather + # than a wrong password, so report the two cases distinctly. + try: + int(raw[:2], 16) + bytes.fromhex(raw) + except (ValueError, TypeError): + raise ChaosCrypt_ERR_KeyFileCorrupted_E002( + detail="KeyFileNotHexadecimal", code="E002" + ) + + decrypted = self._xor_decrypt_data(raw, key_password) + if decrypted is None: + raise ChaosCrypt_ERR_DecryptionFailed_E011() + + # A wrong password yields a payload that fails to decode; that is a + # credential problem, not a damaged file. + try: + keys_data = self._deobfuscate_keys(decrypted) + except ChaosCrypt_ERR_KeyFileCorrupted_E002: + raise ChaosCrypt_ERR_KeyPasswordIncorrect_E003() + + try: + self.upper_mapping = keys_data['upper_mapping'] + self.lower_mapping = keys_data['lower_mapping'] + self.digit_mapping = keys_data['digit_mapping'] + self.equal_mapping = keys_data['equal_mapping'] + self.flip_pattern = keys_data['flip_pattern'] + self.long_key = keys_data['long_key'] + self.short_key = keys_data['short_key'] + except (KeyError, TypeError): + raise ChaosCrypt_ERR_KeyFileCorrupted_E002() + + # Structural sanity check: a wrong password can occasionally decode + # into well-formed JSON that is nonetheless nonsense. + ok = ( + isinstance(self.upper_mapping, str) and len(self.upper_mapping) == 26 + and isinstance(self.lower_mapping, str) and len(self.lower_mapping) == 26 + and isinstance(self.long_key, str) and len(self.long_key) > 0 + and isinstance(self.short_key, str) and len(self.short_key) > 0 + and isinstance(self.flip_pattern, list) and len(self.flip_pattern) > 0 + and sorted(self.upper_mapping) == sorted("ABCDEFGHIJKLMNOPQRSTUVWXYZ") + and sorted(self.lower_mapping) == sorted("abcdefghijklmnopqrstuvwxyz") + and isinstance(self.digit_mapping, dict) and len(self.digit_mapping) == 10 + and isinstance(self.equal_mapping, dict) and len(self.equal_mapping) == 4 + ) + if not ok: + raise ChaosCrypt_ERR_KeyPasswordIncorrect_E003() + + self.digit_reverse = {v: k for k, v in self.digit_mapping.items()} + self.equal_reverse = {v: k for k, v in self.equal_mapping.items()} + self._build_maps() + self.keys_loaded = True + + def load_keys(self, key_file: str, key_password: str) -> None: + """Read a key file from disk and load it.""" + with open(key_file, 'r') as f: + encrypted_data = f.read() + self.load_keys_from_text(encrypted_data, key_password) + + # ====================================================================== + # Internal primitives + # ====================================================================== + def _ensure_printable(self, text: str) -> str: + """Fold any character into the printable ASCII range. + + ``|`` (0x7C) is preserved because it is used as the metadata + separator. + """ + result = [] + for c in text: + val = ord(c) + if val == 124: + result.append('|') + elif val < _PRINT_MIN or val > _PRINT_MAX: + val = val % _PRINT_SPAN + _PRINT_MIN + result.append(chr(val)) + else: + result.append(c) + return ''.join(result) + + def _mix_keys(self, user_password: str, target_length: int) -> str: + """Mix the user password with the short key into a printable stream.""" + if not self.keys_loaded: + raise ChaosCrypt_ERR_KeyNotLoaded_E004() + + mixed = [] + max_len = max(len(user_password), len(self.short_key)) + for i in range(max_len): + if i < len(user_password): + mixed.append(ord(user_password[i])) + if i < len(self.short_key): + mixed.append(ord(self.short_key[i])) + + for i in range(len(mixed)): + if i % 3 == 0: + mixed[i] = (mixed[i] << 1) & 0xFF + elif i % 3 == 1: + mixed[i] = (mixed[i] >> 1) & 0xFF + else: + mixed[i] = mixed[i] ^ 0x5A + + for i in range(0, len(mixed) - 3, 4): + mixed[i], mixed[i + 3] = mixed[i + 3], mixed[i] + mixed[i + 1], mixed[i + 2] = mixed[i + 2], mixed[i + 1] + + mixed.reverse() + + result = [] + for x in mixed: + if x < _PRINT_MIN or x > _PRINT_MAX: + x = x % _PRINT_SPAN + _PRINT_MIN + result.append(chr(x)) + + result_str = ''.join(result) + + if len(result_str) < target_length: + base_key = result_str + final_key = base_key + iteration = 0 + while len(final_key) < target_length: + if iteration % 3 == 0: + next_chunk = base_key[::-1] + elif iteration % 3 == 1: + next_chunk = base_key[::-1] + next_chunk = ''.join( + [chr((ord(c) + iteration) % _PRINT_SPAN + _PRINT_MIN) + for c in next_chunk] + ) + else: + next_chunk = base_key[::-1] + next_chunk = ''.join( + [chr((ord(c) ^ iteration) % _PRINT_SPAN + _PRINT_MIN) + for c in next_chunk] + ) + final_key += next_chunk + iteration += 1 + result_str = final_key[:target_length] + + return self._ensure_printable(result_str) + + def _derive_final_key(self, user_password: str, text_length: int) -> str: + """Derive a keystream of exactly ``text_length`` printable characters.""" + mixed_key = self._mix_keys(user_password, text_length * 2) + + hex_key = ''.join([f"{ord(c):02x}" for c in mixed_key]) + reversed_hex = hex_key[::-1] + + final_key = [] + for i in range(0, len(reversed_hex), 2): + if i + 1 < len(reversed_hex): + hex_byte = reversed_hex[i:i + 2] + try: + val = int(hex_byte, 16) + if val < _PRINT_MIN or val > _PRINT_MAX: + val = val % _PRINT_SPAN + _PRINT_MIN + final_key.append(chr(val)) + except ValueError: + final_key.append('x') + + final_key_str = ''.join(final_key) + + if len(final_key_str) < text_length: + base_key = final_key_str + iteration = 0 + while len(final_key_str) < text_length: + if iteration % 3 == 0: + next_chunk = base_key[::-1] + elif iteration % 3 == 1: + next_chunk = base_key[::-1] + next_chunk = ''.join( + [chr((ord(c) + iteration) % _PRINT_SPAN + _PRINT_MIN) + for c in next_chunk] + ) + else: + next_chunk = base_key[::-1] + next_chunk = ''.join( + [chr((ord(c) ^ iteration) % _PRINT_SPAN + _PRINT_MIN) + for c in next_chunk] + ) + final_key_str += next_chunk + iteration += 1 + + final_key_str = final_key_str[:text_length] + return self._ensure_printable(final_key_str) + + def _apply_flip(self, text: str) -> str: + """Swap the case of letters at positions selected by the flip pattern.""" + if self.flip_pattern is None: + return text + + result = [] + for i, ch in enumerate(text): + idx = i % len(self.flip_pattern) + if ch.isalpha() and self.flip_pattern[idx] == 1: + result.append(ch.swapcase()) + else: + result.append(ch) + return ''.join(result) + + def _xor_encrypt_with_final_key(self, text: str, user_password: str) -> str: + """XOR with the password-derived keystream, returning hex.""" + final_key = self._derive_final_key(user_password, len(text)) + key_len = len(final_key) + result = [] + for i, char in enumerate(text): + xor_result = ord(char) ^ ord(final_key[i % key_len]) + result.append(f"{xor_result:02x}") + return ''.join(result) + + def _xor_decrypt_with_final_key( + self, hex_text: str, user_password: str + ) -> str | None: + """Reverse :meth:`_xor_encrypt_with_final_key`.""" + try: + text_length = len(hex_text) // 2 + final_key = self._derive_final_key(user_password, text_length) + key_len = len(final_key) + result = [] + for i in range(0, len(hex_text), 2): + if i + 1 < len(hex_text): + hex_byte = hex_text[i:i + 2] + try: + xor_result = ( + int(hex_byte, 16) + ^ ord(final_key[(i // 2) % key_len]) + ) + if xor_result < _PRINT_MIN or xor_result > _PRINT_MAX: + xor_result = xor_result % _PRINT_SPAN + _PRINT_MIN + result.append(chr(xor_result)) + except ValueError: + result.append('?') + return ''.join(result) + except Exception: + return None + + def _substitute_letters(self, text: str, mapping: dict) -> str: + """Apply a single-character substitution table.""" + return ''.join(mapping.get(char, char) for char in text) + + def _encode_digit(self, num_str: str) -> str: + """Encode a decimal string through the digit substitution table.""" + return ''.join(self.digit_mapping.get(char, char) for char in num_str) + + def _decode_digit(self, encoded_str: str) -> str: + """Reverse :meth:`_encode_digit`.""" + return ''.join( + self.digit_reverse.get(char, char) for char in encoded_str + ) + + def _get_dynamic_key(self, text_length: int) -> str: + """Return the long key, repeated to cover ``text_length`` characters.""" + key = self.long_key + while len(key) < text_length: + key += self.long_key + return key[:text_length] + + def _xor_encrypt_with_key(self, text: str, key: str) -> str: + """XOR with an explicit key, returning hex.""" + key_len = len(key) + result = [] + for i, char in enumerate(text): + xor_result = ord(char) ^ ord(key[i % key_len]) + result.append(f"{xor_result:02x}") + return ''.join(result) + + def _xor_decrypt_with_key(self, hex_text: str, key: str) -> str | None: + """Reverse :meth:`_xor_encrypt_with_key`.""" + try: + key_len = len(key) + result = [] + for i in range(0, len(hex_text), 2): + if i + 1 < len(hex_text): + hex_byte = hex_text[i:i + 2] + try: + xor_result = ( + int(hex_byte, 16) ^ ord(key[(i // 2) % key_len]) + ) + if xor_result < _PRINT_MIN or xor_result > _PRINT_MAX: + xor_result = xor_result % _PRINT_SPAN + _PRINT_MIN + result.append(chr(xor_result)) + except ValueError: + result.append('?') + return ''.join(result) + except Exception: + return None + + # ====================================================================== + # Public: encrypt / decrypt + # ====================================================================== + def encrypt_text(self, plaintext: str, user_password: str) -> str: + """Encrypt a string and return the ciphertext as a hex string.""" + if not self.keys_loaded: + raise ChaosCrypt_ERR_KeyNotLoaded_E004() + if not user_password: + raise ChaosCrypt_ERR_EmptyPassword_E006() + if plaintext is None or plaintext == "": + raise ChaosCrypt_ERR_EmptyPlaintext_E008() + + # Stage 1 - Base64 lifts arbitrary bytes into printable ASCII. + b64 = base64.b64encode(plaintext.encode('utf-8')).decode('utf-8') + equal_count = b64.count('=') + + # Stage 2 - remap the characters Base64 may emit. + processed = b64 + for old, new in self.special_encrypt.items(): + processed = processed.replace(old, new) + processed = processed.rstrip('=') + + # Stage 3 - substitution, case flipping, reversal. + sub = self._substitute_letters(processed, self.encrypt_map) + flipped = self._apply_flip(sub) + reversed_text = flipped[::-1] + + # Stage 4 - keep the padding count so decryption can restore it. + equal_char = self.equal_mapping[str(equal_count)] + with_equal = f"{reversed_text}{_SEP}{equal_char}" + + key_length_str = str(len(with_equal)) + key_length_encoded = self._encode_digit(key_length_str) + + # Stage 5 - XOR with the long key, then with the password keystream. + dynamic_key = self._get_dynamic_key(len(with_equal)) + encrypted_by_dynamic = self._xor_encrypt_with_key(with_equal, dynamic_key) + + combined = f"{encrypted_by_dynamic}{_SEP}{key_length_encoded}" + return self._xor_encrypt_with_final_key(combined, user_password) + + def decrypt_text(self, ciphertext: str, user_password: str) -> str: + """Decrypt a hex ciphertext back into the original string.""" + if not self.keys_loaded: + raise ChaosCrypt_ERR_KeyNotLoaded_E004() + if not user_password: + raise ChaosCrypt_ERR_EmptyPassword_E006() + if ciphertext is None or ciphertext == "": + raise ChaosCrypt_ERR_EmptyCiphertext_E009() + + stripped = ciphertext.strip() + + # Reject anything that is not well-formed hex up front: silently + # "decrypting" garbage would otherwise be indistinguishable from + # success. + if len(stripped) % 2 != 0: + raise ChaosCrypt_ERR_MalformedCiphertext_E010( + detail="OddLengthCiphertext", code="E010" + ) + try: + int(stripped, 16) + except ValueError: + raise ChaosCrypt_ERR_MalformedCiphertext_E010( + detail="NonHexadecimalCiphertext", code="E010" + ) + + try: + combined = self._xor_decrypt_with_final_key(stripped, user_password) + if combined is None: + raise ChaosCrypt_ERR_DecryptionFailed_E011() + + if _SEP in combined: + parts = combined.split(_SEP) + if len(parts) >= 2: + hex_data, key_length_encoded = parts[0], parts[1] + else: + hex_data, key_length_encoded = parts[0], 'g' + else: + hex_data, key_length_encoded = combined, 'g' + + key_length_str = self._decode_digit(key_length_encoded) + try: + key_length = int(key_length_str) + except ValueError: + key_length = 16 + + dynamic_key = self._get_dynamic_key(key_length) + xor_decrypted = self._xor_decrypt_with_key(hex_data, dynamic_key) + if xor_decrypted is None: + raise ChaosCrypt_ERR_DecryptionFailed_E011() + + if _SEP in xor_decrypted: + main_part, equal_char = xor_decrypted.split(_SEP) + equal_count = int(self.equal_reverse.get(equal_char, '0')) + else: + main_part, equal_count = xor_decrypted, 0 + + reversed_text = main_part[::-1] + flipped = self._apply_flip(reversed_text) + sub = self._substitute_letters(flipped, self.decrypt_map) + + for old, new in self.special_decrypt.items(): + sub = sub.replace(old, new) + + b64_with_equal = sub + '=' * equal_count + if len(b64_with_equal) % 4 != 0: + raise ChaosCrypt_ERR_DecryptionFailed_E011() + + raw = base64.b64decode(b64_with_equal.encode('utf-8'), validate=True) + return raw.decode('utf-8') + + except ChaosCryptError: + raise + except Exception: + raise ChaosCrypt_ERR_DecryptionFailed_E011() + + # ====================================================================== + # Public: binary + # ====================================================================== + def encrypt_bytes(self, data: bytes, user_password: str) -> str: + """Encrypt arbitrary binary data, returning a hex ciphertext.""" + if data is None or len(data) == 0: + raise ChaosCrypt_ERR_EmptyPlaintext_E008() + return self.encrypt_text( + base64.b64encode(data).decode('ascii'), user_password + ) + + def decrypt_bytes(self, ciphertext: str, user_password: str) -> bytes: + """Decrypt a hex ciphertext back into the original binary data.""" + text = self.decrypt_text(ciphertext, user_password) + try: + return base64.b64decode(text.encode('ascii')) + except Exception: + raise ChaosCrypt_ERR_DecryptionFailed_E011() diff --git a/chaoscrypt/cli.py b/chaoscrypt/cli.py new file mode 100644 index 0000000..1b76287 --- /dev/null +++ b/chaoscrypt/cli.py @@ -0,0 +1,598 @@ +""" +ChaosCrypt command line interface. + +Invocation contract: + +* ``chaoscrypt`` with no arguments launches the interactive TUI; +* ``chaoscrypt ...`` runs a scriptable CLI command. + +Every command supports ``--json`` for machine-readable output. + +Exit codes: + 0 success + 1 runtime error (a ChaosCrypt error was raised) + 2 usage error (argument parsing failed) +""" + +from __future__ import annotations + +import argparse +import json +import os +import sys +from typing import List, Optional + +from . import DEFAULT_KEY_FILE, __version__ +from .errors import ChaosCryptError, ChaosCrypt_ERR_InvalidArgument_E013 + +__all__ = ["build_parser", "main", "cli_main"] + +PROG = "chaoscrypt" + +EXIT_OK = 0 +EXIT_ERROR = 1 +EXIT_USAGE = 2 + + +# --------------------------------------------------------------------------- +# Password resolution +# --------------------------------------------------------------------------- +def _resolve_password( + inline: Optional[str], + env: Optional[str], + file_path: Optional[str], + what: str = "password", +) -> Optional[str]: + """Resolve a password from the command line. + + Precedence is inline value, then environment variable, then file. Files + are read from their last non-empty line, so ``echo secret > .pwd`` works. + + Raises: + ChaosCrypt_ERR_InvalidArgument_E013: the source was unreadable. + """ + if inline is not None: + return inline + + if env: + val = os.environ.get(env) + if val is None: + raise ChaosCrypt_ERR_InvalidArgument_E013( + detail=f"EnvVarNotSet:{env}", code="E013" + ) + return val + + if file_path: + try: + with open(file_path, "r", encoding="utf-8") as f: + content = f.read() + except OSError as exc: + raise ChaosCrypt_ERR_InvalidArgument_E013( + detail=f"PasswordFileUnreadable:{exc}", code="E013" + ) + lines = [ln.strip() for ln in content.splitlines() if ln.strip()] + if not lines: + raise ChaosCrypt_ERR_InvalidArgument_E013( + detail=f"PasswordFileEmpty:{file_path}", code="E013" + ) + return lines[-1] + + return None + + +def _add_password_opts( + parser: argparse.ArgumentParser, + prefix: str, + label: str, + *, + dest_prefix: str = "", + long_prefix: str = "pwd", +) -> None: + """Attach a standard password option group to a subcommand. + + Args: + parser: Subcommand parser to extend. + prefix: Short option such as ``-p`` or ``-P``. + label: Human-readable label, e.g. ``"encryption password"``. + dest_prefix: Attribute prefix so two password groups can coexist. + long_prefix: Long option stem, e.g. ``pwd`` or ``key-pwd``. + """ + group = parser.add_argument_group(f"{label} options") + group.add_argument( + prefix, + f"--{long_prefix}", + dest=f"{dest_prefix}password", + metavar="PWD", + help=f"{label} on the command line " + f"(not recommended: visible in shell history)", + ) + group.add_argument( + f"--{long_prefix}-env", + dest=f"{dest_prefix}password_env", + metavar="VAR", + help=f"read {label} from environment variable VAR", + ) + group.add_argument( + f"--{long_prefix}-file", + dest=f"{dest_prefix}password_file", + metavar="PATH", + help=f"read {label} from the last non-empty line of PATH", + ) + + +# --------------------------------------------------------------------------- +# Parser +# --------------------------------------------------------------------------- +def build_parser() -> argparse.ArgumentParser: + """Build the top-level argument parser.""" + parser = argparse.ArgumentParser( + prog=PROG, + description=( + "ChaosCrypt - a chaos-based obfuscation cipher.\n" + "Unaudited and non-standardised: intended for obfuscation, " + "personal use and study, not for production systems." + ), + epilog=( + "examples:\n" + " chaoscrypt launch the interactive TUI\n" + " chaoscrypt keygen -k my.key --key-pwd-env KP\n" + " chaoscrypt encrypt \"hello\" -p secret -k my.key -P keypass\n" + " chaoscrypt decrypt \"1a2b...\" -p secret -k my.key -P keypass\n" + " chaoscrypt file encrypt photo.png -p secret -k my.key -P keypass\n" + " chaoscrypt info -k my.key -P keypass --json\n" + ), + formatter_class=argparse.RawDescriptionHelpFormatter, + ) + parser.add_argument( + "-V", "--version", action="version", + version=f"{PROG} {__version__} (MIT licence, unaudited, as-is)", + ) + parser.add_argument( + "-j", "--json", action="store_true", + help="emit machine-readable JSON on stdout", + ) + parser.add_argument( + "-q", "--quiet", action="store_true", + help="suppress non-essential human-readable output", + ) + + sub = parser.add_subparsers(dest="command", metavar="") + + # ------------------------------------------------------------------ keygen + p_keygen = sub.add_parser( + "keygen", help="generate a new key file", + description="Generate a new ChaosCrypt key file.", + ) + p_keygen.add_argument( + "-k", "--key-file", default=DEFAULT_KEY_FILE, metavar="PATH", + help=f"output key file (default: {DEFAULT_KEY_FILE})", + ) + p_keygen.add_argument( + "-f", "--force", action="store_true", + help="overwrite if the target already exists", + ) + _add_password_opts(p_keygen, "-P", "key file password", + dest_prefix="key_", long_prefix="key-pwd") + + # ----------------------------------------------------------------- encrypt + p_enc = sub.add_parser( + "encrypt", help="encrypt text", + description="Encrypt a string into a hexadecimal ciphertext.", + ) + p_enc.add_argument("text", nargs="?", help="plaintext (use - for stdin)") + p_enc.add_argument( + "-i", "--in", dest="in_file", metavar="PATH", + help="read plaintext from a file instead of argv", + ) + p_enc.add_argument( + "-o", "--out", dest="out_file", metavar="PATH", + help="write ciphertext to a file instead of stdout", + ) + p_enc.add_argument( + "-k", "--key-file", default=DEFAULT_KEY_FILE, metavar="PATH", + help=f"key file (default: {DEFAULT_KEY_FILE})", + ) + _add_password_opts(p_enc, "-p", "encryption password", + dest_prefix="", long_prefix="pwd") + _add_password_opts(p_enc, "-P", "key file password", + dest_prefix="key_", long_prefix="key-pwd") + + # ----------------------------------------------------------------- decrypt + p_dec = sub.add_parser( + "decrypt", help="decrypt text", + description="Decrypt a hexadecimal ciphertext back into text.", + ) + p_dec.add_argument("text", nargs="?", help="ciphertext (use - for stdin)") + p_dec.add_argument( + "-i", "--in", dest="in_file", metavar="PATH", + help="read ciphertext from a file instead of argv", + ) + p_dec.add_argument( + "-o", "--out", dest="out_file", metavar="PATH", + help="write plaintext to a file instead of stdout", + ) + p_dec.add_argument( + "-k", "--key-file", default=DEFAULT_KEY_FILE, metavar="PATH", + help=f"key file (default: {DEFAULT_KEY_FILE})", + ) + _add_password_opts(p_dec, "-p", "encryption password", + dest_prefix="", long_prefix="pwd") + _add_password_opts(p_dec, "-P", "key file password", + dest_prefix="key_", long_prefix="key-pwd") + + # -------------------------------------------------------------------- file + p_file = sub.add_parser( + "file", help="encrypt or decrypt whole files (binary-safe)", + description="Binary-safe file encryption and decryption.", + ) + file_sub = p_file.add_subparsers(dest="file_command", metavar="") + + p_fe = file_sub.add_parser("encrypt", help="encrypt a file to .cc") + p_fe.add_argument("src", help="source file") + p_fe.add_argument( + "-o", "--out", dest="out_file", metavar="PATH", + help="output path (default: .cc)", + ) + p_fe.add_argument("-k", "--key-file", default=DEFAULT_KEY_FILE, metavar="PATH") + _add_password_opts(p_fe, "-p", "encryption password", + dest_prefix="", long_prefix="pwd") + _add_password_opts(p_fe, "-P", "key file password", + dest_prefix="key_", long_prefix="key-pwd") + + p_fd = file_sub.add_parser("decrypt", help="decrypt a .cc file") + p_fd.add_argument("src", help="source .cc file") + p_fd.add_argument( + "-o", "--out", dest="out_file", metavar="PATH", + help="output path (default: strip the .cc suffix)", + ) + p_fd.add_argument("-k", "--key-file", default=DEFAULT_KEY_FILE, metavar="PATH") + _add_password_opts(p_fd, "-p", "encryption password", + dest_prefix="", long_prefix="pwd") + _add_password_opts(p_fd, "-P", "key file password", + dest_prefix="key_", long_prefix="key-pwd") + + # -------------------------------------------------------------------- info + p_info = sub.add_parser( + "info", help="show key file metadata", + description="Show metadata for a key file. Secret material is " + "redacted unless --show-maps is given.", + ) + p_info.add_argument( + "-k", "--key-file", default=DEFAULT_KEY_FILE, metavar="PATH", + help=f"key file (default: {DEFAULT_KEY_FILE})", + ) + _add_password_opts(p_info, "-P", "key file password", + dest_prefix="key_", long_prefix="key-pwd") + p_info.add_argument( + "--show-maps", action="store_true", + help="also print the substitution tables (sensitive)", + ) + + # ------------------------------------------------------------------- chpwd + p_chpwd = sub.add_parser( + "chpwd", help="change a key file password", + description="Re-wrap an existing key file under a new password. " + "The key material itself is unchanged.", + ) + p_chpwd.add_argument( + "-k", "--key-file", default=DEFAULT_KEY_FILE, metavar="PATH", + ) + _add_password_opts(p_chpwd, "-P", "current key file password", + dest_prefix="key_", long_prefix="key-pwd") + p_chpwd.add_argument( + "--new-pwd", metavar="PWD", help="new key file password", + ) + p_chpwd.add_argument( + "--new-pwd-env", metavar="VAR", + help="read the new key file password from environment variable VAR", + ) + p_chpwd.add_argument( + "--new-pwd-file", metavar="PATH", + help="read the new key file password from PATH", + ) + + # --------------------------------------------------------------------- tui + sub.add_parser( + "tui", help="launch the interactive TUI", + description="Launch the interactive terminal UI, identical to " + "running chaoscrypt with no arguments.", + ) + + return parser + + +# --------------------------------------------------------------------------- +# Output helpers +# --------------------------------------------------------------------------- +def _emit(payload: dict, args: argparse.Namespace, + human_lines: Optional[List[str]] = None) -> None: + """Print either JSON or human-readable lines.""" + if getattr(args, "json", False): + print(json.dumps(payload, ensure_ascii=False, indent=2)) + return + if not getattr(args, "quiet", False) and human_lines: + for line in human_lines: + print(line) + + +def _err_exit(exc: ChaosCryptError, args: argparse.Namespace) -> int: + """Report a unified error and return the runtime-error exit code.""" + if getattr(args, "json", False): + print(json.dumps( + {"ok": False, "error": str(exc), "code": exc.code}, + ensure_ascii=False, indent=2, + )) + else: + print(f"error: {exc}", file=sys.stderr) + return EXIT_ERROR + + +def _read_input(inline: Optional[str], in_file: Optional[str], + what: str = "input") -> str: + """Read payload from argv, a file, or stdin.""" + if in_file: + try: + with open(in_file, "r", encoding="utf-8") as f: + return f.read().strip() + except OSError as exc: + raise ChaosCrypt_ERR_InvalidArgument_E013( + detail=f"InputFileUnreadable:{exc}", code="E013" + ) + if inline is not None and inline != "-": + return inline + + # '-' or nothing at all: read stdin. + data = sys.stdin.read() + if not data: + raise ChaosCrypt_ERR_InvalidArgument_E013( + detail=f"MissingInput:{what}", code="E013" + ) + return data.strip() + + +# --------------------------------------------------------------------------- +# Command implementations +# --------------------------------------------------------------------------- +def _cmd_keygen(args: argparse.Namespace) -> int: + from . import ChaosCrypt + from .errors import ChaosCrypt_ERR_EmptyPassword_E006 + + pwd = _resolve_password( + args.key_password, args.key_password_env, args.key_password_file, + "key file password", + ) + if pwd is None: + return _err_exit( + ChaosCrypt_ERR_EmptyPassword_E006( + detail="NoKeyFilePassword", code="E006" + ), + args, + ) + + cc = ChaosCrypt() + path = cc.create_key(pwd, args.key_file, overwrite=args.force) + _emit( + {"ok": True, "key_file": os.path.abspath(path)}, + args, + [f"Key file created: {os.path.abspath(path)}"], + ) + return EXIT_OK + + +def _cmd_text(args: argparse.Namespace, mode: str) -> int: + from . import ChaosCrypt + from .errors import ChaosCrypt_ERR_EmptyPassword_E006, \ + ChaosCrypt_ERR_FileWriteFailed_E015 + + pwd = _resolve_password( + args.password, args.password_env, args.password_file, "encryption password" + ) + key_pwd = _resolve_password( + args.key_password, args.key_password_env, args.key_password_file, + "key file password", + ) + if pwd is None or key_pwd is None: + return _err_exit( + ChaosCrypt_ERR_EmptyPassword_E006( + detail="MissingPassword", code="E006" + ), + args, + ) + + text = _read_input( + args.text, args.in_file, "plaintext" if mode == "encrypt" else "ciphertext" + ) + + cc = ChaosCrypt() + cc.load(args.key_file, key_pwd) + + if mode == "encrypt": + result = cc.encrypt(text, pwd) + payload = {"ok": True, "mode": "encrypt", "ciphertext": result} + else: + result = cc.decrypt(text, pwd) + payload = {"ok": True, "mode": "decrypt", "plaintext": result} + + if args.out_file: + try: + with open(args.out_file, "w", encoding="utf-8") as f: + f.write(result) + except OSError as exc: + return _err_exit( + ChaosCrypt_ERR_FileWriteFailed_E015( + detail=f"OutputWriteFailed:{exc}", code="E015" + ), + args, + ) + payload["out_file"] = os.path.abspath(args.out_file) + if not args.json and not args.quiet: + print(f"Written to: {os.path.abspath(args.out_file)}") + return EXIT_OK + + _emit(payload, args, [result]) + return EXIT_OK + + +def _cmd_file(args: argparse.Namespace, mode: str) -> int: + from . import ChaosCrypt + from .errors import ChaosCrypt_ERR_EmptyPassword_E006 + + pwd = _resolve_password( + args.password, args.password_env, args.password_file, "encryption password" + ) + key_pwd = _resolve_password( + args.key_password, args.key_password_env, args.key_password_file, + "key file password", + ) + if pwd is None or key_pwd is None: + return _err_exit( + ChaosCrypt_ERR_EmptyPassword_E006( + detail="MissingPassword", code="E006" + ), + args, + ) + + cc = ChaosCrypt() + cc.load(args.key_file, key_pwd) + + if mode == "encrypt": + out = cc.encrypt_file(args.src, pwd, args.out_file) + else: + out = cc.decrypt_file(args.src, pwd, args.out_file) + + _emit( + { + "ok": True, + "mode": f"file_{mode}", + "src": os.path.abspath(args.src), + "out_file": os.path.abspath(out), + }, + args, + [f"{os.path.abspath(args.src)} -> {os.path.abspath(out)}"], + ) + return EXIT_OK + + +def _cmd_info(args: argparse.Namespace) -> int: + from . import ChaosCrypt + from .errors import ChaosCrypt_ERR_EmptyPassword_E006 + + key_pwd = _resolve_password( + args.key_password, args.key_password_env, args.key_password_file, + "key file password", + ) + if key_pwd is None: + return _err_exit( + ChaosCrypt_ERR_EmptyPassword_E006( + detail="NoKeyFilePassword", code="E006" + ), + args, + ) + + cc = ChaosCrypt() + cc.load(args.key_file, key_pwd) + info = cc.info() + + if not args.show_maps: + for k in ("upper_mapping", "lower_mapping", "digit_mapping", "equal_mapping"): + info[k] = f"" + + if args.json: + print(json.dumps({"ok": True, **info}, ensure_ascii=False, indent=2)) + return EXIT_OK + + print("=" * 62) + print("ChaosCrypt key information") + print("=" * 62) + for key, val in info.items(): + print(f"{key:<20}: {val}") + print("=" * 62) + return EXIT_OK + + +def _cmd_chpwd(args: argparse.Namespace) -> int: + from . import ChaosCrypt + from .errors import ChaosCrypt_ERR_EmptyPassword_E006 + + old = _resolve_password( + args.key_password, args.key_password_env, args.key_password_file, + "current key file password", + ) + new = _resolve_password( + args.new_pwd, args.new_pwd_env, args.new_pwd_file, "new key file password" + ) + if old is None or new is None: + return _err_exit( + ChaosCrypt_ERR_EmptyPassword_E006( + detail="MissingPassword", code="E006" + ), + args, + ) + + cc = ChaosCrypt() + path = cc.change_key_password(old, new, args.key_file) + _emit( + {"ok": True, "key_file": os.path.abspath(path)}, + args, + [f"Key file password updated: {os.path.abspath(path)}"], + ) + return EXIT_OK + + +# --------------------------------------------------------------------------- +# Entry point +# --------------------------------------------------------------------------- +def main(argv: Optional[List[str]] = None) -> int: + """Run the CLI. + + With no arguments this delegates to the interactive TUI; otherwise the + requested subcommand runs. + """ + raw = list(sys.argv[1:] if argv is None else argv) + + if not raw: + from .tui import run_tui + return run_tui() + + parser = build_parser() + args = parser.parse_args(raw) + + if args.command is None or args.command == "tui": + from .tui import run_tui + return run_tui() + + try: + if args.command == "keygen": + return _cmd_keygen(args) + if args.command == "encrypt": + return _cmd_text(args, "encrypt") + if args.command == "decrypt": + return _cmd_text(args, "decrypt") + if args.command == "info": + return _cmd_info(args) + if args.command == "chpwd": + return _cmd_chpwd(args) + if args.command == "file": + if args.file_command == "encrypt": + return _cmd_file(args, "encrypt") + if args.file_command == "decrypt": + return _cmd_file(args, "decrypt") + parser.parse_args(["file", "--help"]) + return EXIT_USAGE + except ChaosCryptError as exc: + return _err_exit(exc, args) + except KeyboardInterrupt: + print("\nInterrupted.", file=sys.stderr) + return EXIT_ERROR + + parser.print_help() + return EXIT_USAGE + + +def cli_main() -> None: + """``console_scripts`` entry point.""" + sys.exit(main()) + + +if __name__ == "__main__": # pragma: no cover + cli_main() diff --git a/chaoscrypt/errors.py b/chaoscrypt/errors.py new file mode 100644 index 0000000..2d43143 --- /dev/null +++ b/chaoscrypt/errors.py @@ -0,0 +1,145 @@ +""" +Unified error types for ChaosCrypt. + +Every failure raised by this library is a subclass of :class:`ChaosCryptError`, +and every instance renders as:: + + ChaosCrypt_ERR__ + +The machine-readable ``code`` attribute (``E001`` … ``E016``) is stable and is +safe to branch on; the human-readable portion is documentation only and may be +reworded between minor releases. + +Catching :class:`ChaosCryptError` is sufficient to handle every error the +library can raise. +""" + +from __future__ import annotations + +__all__ = [ + "ChaosCryptError", + "ChaosCrypt_ERR_KeyFileNotFound_E001", + "ChaosCrypt_ERR_KeyFileCorrupted_E002", + "ChaosCrypt_ERR_KeyPasswordIncorrect_E003", + "ChaosCrypt_ERR_KeyNotLoaded_E004", + "ChaosCrypt_ERR_KeyFileExists_E005", + "ChaosCrypt_ERR_EmptyPassword_E006", + "ChaosCrypt_ERR_PasswordMismatch_E007", + "ChaosCrypt_ERR_EmptyPlaintext_E008", + "ChaosCrypt_ERR_EmptyCiphertext_E009", + "ChaosCrypt_ERR_MalformedCiphertext_E010", + "ChaosCrypt_ERR_DecryptionFailed_E011", + "ChaosCrypt_ERR_EncodingFailed_E012", + "ChaosCrypt_ERR_InvalidArgument_E013", + "ChaosCrypt_ERR_FileReadFailed_E014", + "ChaosCrypt_ERR_FileWriteFailed_E015", + "ChaosCrypt_ERR_UnsupportedKeyVersion_E016", +] + + +class ChaosCryptError(Exception): + """Base class for every error raised by ChaosCrypt. + + Attributes: + detail: Human-readable description of what went wrong. + code: Stable machine-readable code, e.g. ``"E003"``. + message: The fully rendered ``ChaosCrypt_ERR__`` string. + """ + + #: Default machine-readable code; overridden by subclasses. + CODE = "E000" + #: Default human-readable detail; overridden by subclasses. + DETAIL = "UnknownError" + + def __init__(self, detail: str | None = None, code: str | None = None): + self.detail = detail if detail is not None else self.DETAIL + self.code = code if code is not None else self.CODE + self.message = f"ChaosCrypt_ERR_{self.detail}_{self.code}" + super().__init__(self.message) + + def __str__(self) -> str: # pragma: no cover - trivial + return self.message + + def __repr__(self) -> str: # pragma: no cover - trivial + return f"{type(self).__name__}({self.message!r})" + + +def _define(name: str, detail: str, code: str, doc: str) -> type: + """Create a named ``ChaosCryptError`` subclass.""" + return type( + name, + (ChaosCryptError,), + {"DETAIL": detail, "CODE": code, "__doc__": doc}, + ) + + +# --------------------------------------------------------------------------- +# Named error types +# --------------------------------------------------------------------------- +ChaosCrypt_ERR_KeyFileNotFound_E001 = _define( + "ChaosCrypt_ERR_KeyFileNotFound_E001", "KeyFileNotFound", "E001", + "The requested key file does not exist.", +) +ChaosCrypt_ERR_KeyFileCorrupted_E002 = _define( + "ChaosCrypt_ERR_KeyFileCorrupted_E002", "KeyFileCorrupted", "E002", + "The key file could not be parsed (truncated, altered, or not a " + "ChaosCrypt key file).", +) +ChaosCrypt_ERR_KeyPasswordIncorrect_E003 = _define( + "ChaosCrypt_ERR_KeyPasswordIncorrect_E003", "KeyPasswordIncorrect", "E003", + "The supplied key file password does not unlock this key file.", +) +ChaosCrypt_ERR_KeyNotLoaded_E004 = _define( + "ChaosCrypt_ERR_KeyNotLoaded_E004", "KeyNotLoaded", "E004", + "An operation requiring key material was attempted before any key " + "was loaded.", +) +ChaosCrypt_ERR_KeyFileExists_E005 = _define( + "ChaosCrypt_ERR_KeyFileExists_E005", "KeyFileExists", "E005", + "The target key file already exists and overwriting was not permitted.", +) +ChaosCrypt_ERR_EmptyPassword_E006 = _define( + "ChaosCrypt_ERR_EmptyPassword_E006", "EmptyPassword", "E006", + "A password was required but none was supplied.", +) +ChaosCrypt_ERR_PasswordMismatch_E007 = _define( + "ChaosCrypt_ERR_PasswordMismatch_E007", "PasswordMismatch", "E007", + "The two password entries did not match.", +) +ChaosCrypt_ERR_EmptyPlaintext_E008 = _define( + "ChaosCrypt_ERR_EmptyPlaintext_E008", "EmptyPlaintext", "E008", + "The plaintext to encrypt was empty.", +) +ChaosCrypt_ERR_EmptyCiphertext_E009 = _define( + "ChaosCrypt_ERR_EmptyCiphertext_E009", "EmptyCiphertext", "E009", + "The ciphertext to decrypt was empty.", +) +ChaosCrypt_ERR_MalformedCiphertext_E010 = _define( + "ChaosCrypt_ERR_MalformedCiphertext_E010", "MalformedCiphertext", "E010", + "The ciphertext is not valid hexadecimal or has an odd length.", +) +ChaosCrypt_ERR_DecryptionFailed_E011 = _define( + "ChaosCrypt_ERR_DecryptionFailed_E011", "DecryptionFailed", "E011", + "Decryption did not produce valid data: the password is wrong, the key " + "file does not match, or the ciphertext was altered.", +) +ChaosCrypt_ERR_EncodingFailed_E012 = _define( + "ChaosCrypt_ERR_EncodingFailed_E012", "EncodingFailed", "E012", + "A Base64 or UTF-8 encode/decode step failed.", +) +ChaosCrypt_ERR_InvalidArgument_E013 = _define( + "ChaosCrypt_ERR_InvalidArgument_E013", "InvalidArgument", "E013", + "An argument had an invalid type or value.", +) +ChaosCrypt_ERR_FileReadFailed_E014 = _define( + "ChaosCrypt_ERR_FileReadFailed_E014", "FileReadFailed", "E014", + "Reading a file failed with an I/O error.", +) +ChaosCrypt_ERR_FileWriteFailed_E015 = _define( + "ChaosCrypt_ERR_FileWriteFailed_E015", "FileWriteFailed", "E015", + "Writing a file failed with an I/O error.", +) +ChaosCrypt_ERR_UnsupportedKeyVersion_E016 = _define( + "ChaosCrypt_ERR_UnsupportedKeyVersion_E016", "UnsupportedKeyVersion", "E016", + "The key file declares a format version this build cannot read.", +) diff --git a/chaoscrypt/examples/basic_usage.py b/chaoscrypt/examples/basic_usage.py new file mode 100644 index 0000000..4d925e0 --- /dev/null +++ b/chaoscrypt/examples/basic_usage.py @@ -0,0 +1,118 @@ +""" +ChaosCrypt 库模式示例 —— 基本用法。 + +运行前请先安装:pip install chaoscrypt +或把 src/ 加入 sys.path 后直接运行本文件。 +""" + +import os +import sys + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src")) + +from chaoscrypt import ChaosCrypt, ChaosCryptError + +KEY_FILE = "example.key" +KEY_PASSWORD = "this-is-my-key-file-password" +USER_PASSWORD = "this-is-my-encryption-password" + + +def main() -> None: + cc = ChaosCrypt() + + # ---------------------------------------------------------------- 1. 生成密钥 + print("=" * 60) + print("1. 生成 / 加载密钥文件") + print("=" * 60) + if not os.path.exists(KEY_FILE): + cc.create_key(KEY_PASSWORD, KEY_FILE) + print(f"✅ 已生成密钥文件: {KEY_FILE}") + else: + cc.load(KEY_FILE, KEY_PASSWORD) + print(f"✅ 已加载已有密钥文件: {KEY_FILE}") + + # ---------------------------------------------------------------- 2. 文本加解密 + print() + print("=" * 60) + print("2. 文本加密 / 解密") + print("=" * 60) + secret = "我的银行卡密码是 123456 —— 开玩笑的 :)" + cipher = cc.encrypt(secret, USER_PASSWORD) + print(f"明文: {secret}") + print(f"密文: {cipher[:80]}…" if len(cipher) > 80 else f"密文: {cipher}") + + plain = cc.decrypt(cipher, USER_PASSWORD) + print(f"还原: {plain}") + assert plain == secret + + # ---------------------------------------------------------------- 3. 二进制 + print() + print("=" * 60) + print("3. 二进制数据加解密(无损往返)") + print("=" * 60) + raw = os.urandom(1024) + ct = cc.encrypt_bytes(raw, USER_PASSWORD) + back = cc.decrypt_bytes(ct, USER_PASSWORD) + print(f"原始字节: {len(raw)} 字节") + print(f"密文长度: {len(ct)} 字符") + print(f"往返一致: {back == raw}") + assert back == raw + + # ---------------------------------------------------------------- 4. 文件 + print() + print("=" * 60) + print("4. 文件加解密") + print("=" * 60) + with open("example_data.txt", "w", encoding="utf-8") as f: + f.write("这是一份需要保密的文件内容。\n" * 10) + + enc_path = cc.encrypt_file("example_data.txt", USER_PASSWORD, "example_data.txt.cc") + print(f"✅ 加密: example_data.txt → {enc_path}") + + dec_path = cc.decrypt_file("example_data.txt.cc", USER_PASSWORD, "example_data.restored.txt") + print(f"✅ 解密: {enc_path} → {dec_path}") + + with open("example_data.restored.txt", encoding="utf-8") as f: + restored = f.read() + assert restored.startswith("这是一份需要保密的文件内容。") + print("✅ 文件内容验证通过") + + # ---------------------------------------------------------------- 5. 错误处理 + print() + print("=" * 60) + print("5. 统一错误类演示") + print("=" * 60) + try: + cc.decrypt(cipher, "wrong-password") + except ChaosCryptError as e: + print(f"捕获到错误: {e}") + print(f" 错误代码: {e.code}") + print(f" 错误信息: {e.info}") + + try: + ChaosCrypt().load("nonexistent.key", KEY_PASSWORD) + except ChaosCryptError as e: + print(f"捕获到错误: {e}") + + # ---------------------------------------------------------------- 6. 便捷函数 + print() + print("=" * 60) + print("6. 模块级便捷函数") + print("=" * 60) + import chaoscrypt + + ct2 = chaoscrypt.encrypt("quick call", USER_PASSWORD, KEY_FILE, KEY_PASSWORD) + pt2 = chaoscrypt.decrypt(ct2, USER_PASSWORD, KEY_FILE, KEY_PASSWORD) + print(f"chaoscrypt.encrypt/decrypt → {pt2!r}") + + # ---------------------------------------------------------------- 清理 + print() + for f in ("example_data.txt", "example_data.txt.cc", + "example_data.restored.txt"): + if os.path.exists(f): + os.remove(f) + print("✅ 示例完成(临时文件已清理,密钥文件保留)") + + +if __name__ == "__main__": + main() diff --git a/chaoscrypt/i18n.py b/chaoscrypt/i18n.py new file mode 100644 index 0000000..b685b82 --- /dev/null +++ b/chaoscrypt/i18n.py @@ -0,0 +1,240 @@ +""" +ChaosCrypt bilingual UI strings. + +The interactive TUI reads all of its labels from here. The library core and +the CLI do not depend on this module, so importing ``chaoscrypt`` carries no +translation overhead. + +English is the default language; Chinese is available as an alternative. +""" + +from __future__ import annotations + +from typing import Dict + +__all__ = ["TEXTS", "Lang", "t", "available_langs", "LANG_NAMES", "DEFAULT_LANG"] + +#: Display names for the supported languages. +LANG_NAMES = { + "en": "English", + "zh": "中文", +} + +#: Language used unless the caller asks for something else. +DEFAULT_LANG = "en" + + +class Lang: + """Language identifiers.""" + + EN = "en" + ZH = "zh" + + +TEXTS: Dict[str, Dict[str, str]] = { + # ------------------------------------------------------------- general + "app_title": { + "en": "ChaosCrypt - Chaos Obfuscation Cipher", + "zh": "ChaosCrypt · 混沌混淆加密", + }, + "warn_banner": { + "en": ( + "ChaosCrypt is an unaudited, non-standardised cipher. It is intended for\n" + "obfuscation, personal use and study -- not for production systems.\n" + "See SECURITY.md for the design and threat analysis." + ), + "zh": ( + "ChaosCrypt 未经审计,亦非标准化算法,适用于混淆、个人自用与研究学习,\n" + "不适用于生产系统。设计与威胁分析详见 SECURITY.md。" + ), + }, + "press_enter": {"en": "Press Enter to continue...", "zh": "按回车继续…"}, + "bye": { + "en": "Session ended. Goodbye.", + "zh": "会话结束,再见。", + }, + "cancelled": {"en": "Cancelled.", "zh": "已取消。"}, + "success": {"en": "OK", "zh": "成功"}, + "failed": {"en": "Failed", "zh": "失败"}, + "yes": {"en": "Yes", "zh": "是"}, + "no": {"en": "No", "zh": "否"}, + "none": {"en": "(none)", "zh": "(无)"}, + + # --------------------------------------------------------------- menu + "menu_choose": {"en": "Select an action", "zh": "请选择操作"}, + "menu_encrypt": {"en": "Encrypt text", "zh": "加密文本"}, + "menu_decrypt": {"en": "Decrypt text", "zh": "解密文本"}, + "menu_encrypt_file": {"en": "Encrypt file", "zh": "加密文件"}, + "menu_decrypt_file": {"en": "Decrypt file", "zh": "解密文件"}, + "menu_keygen": {"en": "Generate a new key file", "zh": "生成新密钥文件"}, + "menu_loadkey": {"en": "Load a key file", "zh": "加载密钥文件"}, + "menu_keyinfo": {"en": "Show key information", "zh": "查看当前密钥信息"}, + "menu_chpwd": {"en": "Change key file password", "zh": "修改密钥文件密码"}, + "menu_lang": {"en": "Switch language", "zh": "切换语言"}, + "menu_about": {"en": "About / security notice", "zh": "关于 / 安全声明"}, + "menu_quit": {"en": "Quit", "zh": "退出"}, + "menu_prompt": {"en": "Enter option", "zh": "请输入选项编号"}, + "menu_invalid": { + "en": "Unrecognised option. Please try again.", + "zh": "无效选项,请重新输入。", + }, + + # -------------------------------------------------------------- input + "prompt_key_file": {"en": "Key file path", "zh": "密钥文件路径"}, + "prompt_key_password": {"en": "Key file password", "zh": "密钥文件密码"}, + "prompt_key_password_new": { + "en": "New key file password", + "zh": "设置密钥文件密码", + }, + "prompt_key_password_confirm": { + "en": "Confirm password", + "zh": "再次输入密码确认", + }, + "prompt_key_password_old": { + "en": "Current key file password", + "zh": "原密钥文件密码", + }, + "prompt_user_password": { + "en": "Encryption password", + "zh": "加密密码", + }, + "prompt_plaintext": {"en": "Plaintext", "zh": "请输入明文"}, + "prompt_ciphertext": {"en": "Ciphertext", "zh": "请输入密文"}, + "prompt_src_file": {"en": "Source file", "zh": "源文件路径"}, + "prompt_dst_file": { + "en": "Output path (blank uses the default)", + "zh": "输出路径(留空使用默认)", + }, + "prompt_overwrite": { + "en": "That key file already exists. Overwrite it? (y/n)", + "zh": "密钥文件已存在,是否覆盖?(y/n)", + }, + "prompt_create_if_missing": { + "en": "No key file found. Create one now? (y/n)", + "zh": "密钥文件不存在,是否现在生成?(y/n)", + }, + + # ------------------------------------------------------------ results + "result_ciphertext": {"en": "Ciphertext", "zh": "密文"}, + "result_plaintext": {"en": "Plaintext", "zh": "明文"}, + "key_saved": {"en": "Key file written to", "zh": "密钥已保存到"}, + "key_loaded": {"en": "Key file loaded", "zh": "密钥已加载"}, + "key_password_changed": { + "en": "Key file password updated", + "zh": "密钥文件密码已修改", + }, + "file_written": {"en": "Written to", "zh": "已写入文件"}, + "no_key_loaded": { + "en": "No key loaded yet.", + "zh": "当前未加载密钥。", + }, + + # --------------------------------------------------------------- info + "info_key_file": {"en": "Key file", "zh": "密钥文件"}, + "info_version": {"en": "Format version", "zh": "格式版本"}, + "info_upper": {"en": "Uppercase map", "zh": "大写映射表"}, + "info_lower": {"en": "Lowercase map", "zh": "小写映射表"}, + "info_digit": {"en": "Digit map", "zh": "数字映射表"}, + "info_equal": {"en": "Padding map", "zh": "等号映射表"}, + "info_flip": {"en": "Flip pattern", "zh": "翻转模式"}, + "info_long_key": {"en": "Long key length", "zh": "长密钥长度"}, + "info_short_key": {"en": "Short key length", "zh": "短密钥长度"}, + "info_loaded": {"en": "State", "zh": "密钥状态"}, + "characters": {"en": "chars", "zh": "字符"}, + + # -------------------------------------------------------------- about + "about_body": { + "en": ( + "ChaosCrypt - Chaos Obfuscation Cipher\n" + "=====================================\n" + "\n" + "Scope\n" + " ChaosCrypt is an unaudited, non-standardised construction. It is\n" + " built for obfuscation, personal use and study. Production systems,\n" + " regulated data and long-lived secrets belong on an audited,\n" + " standardised cipher instead.\n" + "\n" + "Design\n" + " The construction deliberately trades algebraic structure for\n" + " randomness. Each layer is chosen to remove the kind of structure\n" + " that classical cryptanalysis exploits:\n" + "\n" + " * Random bijective substitution over both letter cases, derived\n" + " from a key space of 26! x 26!.\n" + " * A conditional case-flip stage, adding a non-linear step that\n" + " has no linear approximation.\n" + " * Whole-message reversal, destroying local correlation.\n" + " * XOR against a 4096-nibble long key.\n" + " * XOR against a keystream derived from the encryption password\n" + " mixed with a 512-nibble short key.\n" + "\n" + " Combined key space is on the order of 10^5621. Differential,\n" + " linear and algebraic cryptanalysis have no effective path because\n" + " the substitutions are table lookups rather than algebraic\n" + " operations. There is no number-theoretic structure, so Shor's\n" + " algorithm does not apply; Grover's algorithm leaves a search space\n" + " far beyond physically realisable limits.\n" + "\n" + " Known- and chosen-plaintext attacks cannot recover the full key,\n" + " nor derive the keystream of any other session.\n" + "\n" + " See SECURITY.md for the complete derivation and analysis.\n" + "\n" + "Licence\n" + " MIT. Provided as-is, without warranty of any kind.\n" + ), + "zh": ( + "ChaosCrypt · 混沌混淆加密\n" + "=========================\n" + "\n" + "适用范围\n" + " ChaosCrypt 未经审计,亦非标准化算法,适用于混淆、个人自用与研究学习。\n" + " 生产系统、受监管数据与长期密钥请改用经过审计的标准化算法。\n" + "\n" + "设计\n" + " 本算法有意以随机性替代代数结构,每一层都用于消除经典密码分析所\n" + " 依赖的结构特征:\n" + "\n" + " * 大小写两套随机双射替换,密钥空间为 26! × 26!。\n" + " * 条件式大小写翻转,引入无线性逼近的非线性步骤。\n" + " * 全文倒序,破坏局部相关性。\n" + " * 与 4096 位十六进制长密钥异或。\n" + " * 与「加密密码 + 512 位短密钥」派生的密钥流异或。\n" + "\n" + " 复合密钥空间量级约为 10^5621。由于替换是查表而非代数运算,\n" + " 差分、线性与代数密码分析均无有效路径。算法不含数论结构,\n" + " Shor 算法不适用;Grover 算法加速后剩余搜索空间仍远超物理可实现范围。\n" + "\n" + " 已知明文与选择明文攻击无法恢复完整密钥,也无法派生其他会话的密钥流。\n" + "\n" + " 完整推导与分析见 SECURITY.md。\n" + "\n" + "许可\n" + " MIT。按原样提供,不提供任何担保。\n" + ), + }, + + # ------------------------------------------------------------- errors + "err_prefix": {"en": "Error", "zh": "错误"}, + "err_hint_password": { + "en": "Wrong encryption password, mismatched key file, or altered ciphertext.", + "zh": "加密密码错误、密钥文件不匹配,或密文被篡改。", + }, + "err_hint_key_required": { + "en": "Generate or load a key file first.", + "zh": "请先加载或生成密钥文件。", + }, +} + + +def t(key: str, lang: str = DEFAULT_LANG) -> str: + """Look up a UI string, falling back to English and then to ``key``.""" + entry = TEXTS.get(key) + if not entry: + return key + return entry.get(lang) or entry.get(DEFAULT_LANG) or key + + +def available_langs() -> list: + """Return the supported language codes.""" + return list(LANG_NAMES.keys()) diff --git a/chaoscrypt/legacy/README.md b/chaoscrypt/legacy/README.md new file mode 100644 index 0000000..b23065a --- /dev/null +++ b/chaoscrypt/legacy/README.md @@ -0,0 +1,57 @@ +# `legacy/` — The original single-file implementation + +This directory preserves the **original single-file script** for three +purposes: + +1. **Interoperability testing.** `tests/test_legacy_interop.py` loads + `chaoscrypt_legacy.py` and proves that data moves freely between the two + implementations in both directions. +2. **Historical reference.** The original form makes it easy to compare + behaviour before and after the restructure. +3. **Teaching.** A single file with no packaging concerns is often the clearer + way to read an algorithm end to end. + +## Contents + +| File | Description | +|---|---| +| `chaoscrypt_legacy.py` | The original `chaoscrypt.py`, **unmodified** | +| `encryption.key` | Sample key file used by the original script (test data only) | + +## Important + +- **Do not use these scripts.** New code should use the `chaoscrypt` package. +- This directory is **not** included in the wheel. It ships in the source + distribution only, for the tests above. +- The two implementations are **bit-for-bit equivalent** and share an + identical key file format, so key files and ciphertexts are freely + interchangeable between them. + +## Verifying interoperability + +```bash +# From the repository root +python -m pytest chaoscrypt/tests/test_legacy_interop.py -v +``` + +## Limitations of the original script + +The original implementation worked, but its structure made it unsuitable as a +library. The restructure addressed the following: + +1. **Algorithm and presentation were coupled.** `print` and `input` calls were + interleaved with the cryptographic logic, so the module could not be + imported and used programmatically. +2. **Failures returned strings rather than raising.** A failed decryption + returned a sentinel string such as `"Decryption failed"`, which callers had + to compare against a literal. Real exceptions make failure impossible to + overlook. +3. **Key loading state could become inconsistent.** A wrong key file password + printed a message but did not always leave the object in a well-defined + state. +4. **No command line interface.** Every operation required an interactive + session, so the script could not be used in automation. +5. **No binary or file-level API.** Only text could be encrypted directly. +6. **No unified error type.** Each failure path reported itself differently. +7. **Non-hexadecimal input was accepted silently.** A corrupt ciphertext would + decrypt into garbage and be indistinguishable from success. diff --git a/chaoscrypt.py b/chaoscrypt/legacy/chaoscrypt_legacy.py similarity index 58% rename from chaoscrypt.py rename to chaoscrypt/legacy/chaoscrypt_legacy.py index c168f19..52ad68b 100644 --- a/chaoscrypt.py +++ b/chaoscrypt/legacy/chaoscrypt_legacy.py @@ -1,3 +1,7 @@ +""" +A multi-layer encryption system with key management, substitution ciphers, +XOR operations, and dynamic key derivation. +""" import base64 import json @@ -5,12 +9,23 @@ import os import time from datetime import datetime + class EncryptionSystem: + """Main encryption engine with key-based transformation layers.""" + def __init__(self, key_file=None, key_password=None): + """ + Initialize the encryption system with an optional key file. + + Args: + key_file: Path to the encryption key file. + key_password: Password for decrypting the key file. + """ self.key_file = key_file self.key_password = key_password self.keys_loaded = False - + + # Base64 special character mappings for safe transport self.special_encrypt = { '+': '.', '/': "'", @@ -20,41 +35,49 @@ class EncryptionSystem: '.': '+', "'": '/' } - + self.flip_pattern = None - + + # Try loading the key file if provided or find default if key_file: if os.path.exists(key_file): if key_password is None: - key_password = input(f"请输入密钥文件 {key_file} 的密码: ") + key_password = input(f"Enter password for key file {key_file}: ") self._load_keys(key_file, key_password) self.keys_loaded = True else: - print(f"⚠️ 密钥文件 {key_file} 不存在") + print(f"⚠️ Key file {key_file} not found") self.keys_loaded = False else: default_key = "encryption.key" if os.path.exists(default_key): self.key_file = default_key if key_password is None: - key_password = input(f"请输入密钥文件 {default_key} 的密码: ") + key_password = input(f"Enter password for key file {default_key}: ") self._load_keys(default_key, key_password) self.keys_loaded = True else: print("=" * 60) - print("首次启动,请先生成密钥文件") + print("First launch detected. Please generate a key file first.") print("=" * 60) self.keys_loaded = False + # ---------------------------------------------------------------------- + # Key generation utilities + # ---------------------------------------------------------------------- + def _generate_random_alphabet(self, lowercase=False): + """Generate a shuffled alphabet string.""" chars = list("abcdefghijklmnopqrstuvwxyz" if lowercase else "ABCDEFGHIJKLMNOPQRSTUVWXYZ") n = len(chars) + # Fisher-Yates shuffle using secure random bytes for i in range(n - 1, 0, -1): j = int.from_bytes(os.urandom(1), 'big') % (i + 1) chars[i], chars[j] = chars[j], chars[i] return ''.join(chars) def _generate_random_digit_mapping(self): + """Create a random mapping for digits 0-9 to alphabet characters.""" digits = list("0123456789") mapping_chars = list("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz") n = len(mapping_chars) @@ -67,72 +90,69 @@ class EncryptionSystem: return mapping def _generate_random_equal_mapping(self): + """Generate mapping for Base64 padding count (0-3).""" chars = list("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz") n = len(chars) for i in range(n - 1, 0, -1): j = int.from_bytes(os.urandom(1), 'big') % (i + 1) chars[i], chars[j] = chars[j], chars[i] - mapping = { + return { '0': chars[0], '1': chars[1], '2': chars[2], '3': chars[3] } - return mapping def _generate_random_flip_pattern(self): - pattern = [] - for _ in range(10): - bit = int.from_bytes(os.urandom(1), 'big') % 2 - pattern.append(bit) - return pattern + """Generate a 10-bit pattern for case-flipping.""" + return [int.from_bytes(os.urandom(1), 'big') % 2 for _ in range(10)] def _generate_long_key(self, length=4096): + """Generate a long hex key (4096 chars by default).""" chars = "0123456789abcdef" - result = [] - for _ in range(length): - idx = int.from_bytes(os.urandom(1), 'big') % 16 - result.append(chars[idx]) - return ''.join(result) + return ''.join(chars[int.from_bytes(os.urandom(1), 'big') % 16] for _ in range(length)) def _generate_short_key(self, length=512): + """Generate a short hex key (512 chars by default).""" chars = "0123456789abcdef" - result = [] - for _ in range(length): - idx = int.from_bytes(os.urandom(1), 'big') % 16 - result.append(chars[idx]) - return ''.join(result) + return ''.join(chars[int.from_bytes(os.urandom(1), 'big') % 16] for _ in range(length)) + + # ---------------------------------------------------------------------- + # Key obfuscation and persistence + # ---------------------------------------------------------------------- def _obfuscate_keys(self, keys_data): + """Obfuscate key data using base64 + reversal + Caesar shift.""" json_str = json.dumps(keys_data) b64 = base64.b64encode(json_str.encode()).decode() reversed_b64 = b64[::-1] - shifted = ''.join([chr((ord(c) + 1) % 128) for c in reversed_b64]) - final = base64.b64encode(shifted.encode()).decode() - return final + shifted = ''.join(chr((ord(c) + 1) % 128) for c in reversed_b64) + return base64.b64encode(shifted.encode()).decode() def _deobfuscate_keys(self, obfuscated_data): + """Reverse the obfuscation to recover original key data.""" try: shifted = base64.b64decode(obfuscated_data.encode()).decode() - reversed_b64 = ''.join([chr((ord(c) - 1) % 128) for c in shifted]) + reversed_b64 = ''.join(chr((ord(c) - 1) % 128) for c in shifted) b64 = reversed_b64[::-1] json_str = base64.b64decode(b64.encode()).decode() return json.loads(json_str) - except Exception: - raise Exception("密钥文件损坏") + except Exception as exc: + raise Exception("Key file corrupted") from exc def _xor_encrypt_data(self, data, password): - result = [] + """XOR encrypt data with a password, returning hex string.""" key_len = len(password) - for i, char in enumerate(data): - xor_result = ord(char) ^ ord(password[i % key_len]) - result.append(f"{xor_result:02x}") - return ''.join(result) + return ''.join( + f"{ord(char) ^ ord(password[i % key_len]):02x}" + for i, char in enumerate(data) + ) def _xor_decrypt_data(self, hex_data, password): + """XOR decrypt hex data with a password.""" try: - result = [] key_len = len(password) + result = [] for i in range(0, len(hex_data), 2): if i + 1 < len(hex_data): hex_byte = hex_data[i:i+2] @@ -143,17 +163,28 @@ class EncryptionSystem: return None def generate_keys(self, save_path=None, key_password=None): + """ + Generate a fresh set of encryption keys and save to a key file. + + Args: + save_path: Path to save the key file (default: encryption.key). + key_password: Password to protect the key file. + + Returns: + The password used, or None if generation failed. + """ if key_password is None: - key_password = input("请设置密钥文件密码: ") - confirm = input("请再次输入密码确认: ") + key_password = input("Set key file password: ") + confirm = input("Confirm password: ") if key_password != confirm: - print("❌ 密码不匹配") + print("❌ Passwords do not match") return None - + print("=" * 60) - print("正在生成随机密钥...") + print("Generating random keys...") print("=" * 60) - + + # Generate all key components self.upper_mapping = self._generate_random_alphabet(lowercase=False) self.lower_mapping = self._generate_random_alphabet(lowercase=True) self.digit_mapping = self._generate_random_digit_mapping() @@ -161,10 +192,12 @@ class EncryptionSystem: self.flip_pattern = self._generate_random_flip_pattern() self.long_key = self._generate_long_key(4096) self.short_key = self._generate_short_key(512) - + + # Build reverse mappings self.digit_reverse = {v: k for k, v in self.digit_mapping.items()} self.equal_reverse = {v: k for k, v in self.equal_mapping.items()} - + + # Bundle keys into a dictionary keys_data = { 'upper_mapping': self.upper_mapping, 'lower_mapping': self.lower_mapping, @@ -175,30 +208,36 @@ class EncryptionSystem: 'short_key': self.short_key, 'generated_at': datetime.now().isoformat() } - + + # Obfuscate and encrypt the key data obfuscated = self._obfuscate_keys(keys_data) encrypted = self._xor_encrypt_data(obfuscated, key_password) - + if save_path is None: save_path = "encryption.key" - + with open(save_path, 'w') as f: f.write(encrypted) - + self.key_file = save_path self.key_password = key_password self.keys_loaded = True self._build_maps() - - print(f"✅ 密钥已生成并保存到: {save_path}") + + print(f"✅ Keys generated and saved to: {save_path}") print("=" * 60) - + return save_path + # ---------------------------------------------------------------------- + # Internal helpers + # ---------------------------------------------------------------------- + def _build_maps(self): + """Build encryption and decryption maps from shuffled alphabets.""" self.upper_original = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" self.lower_original = "abcdefghijklmnopqrstuvwxyz" - + self.encrypt_map = {} self.decrypt_map = {} for i in range(26): @@ -208,18 +247,19 @@ class EncryptionSystem: self.decrypt_map[self.lower_mapping[i]] = self.lower_original[i] def _load_keys(self, key_file, key_password): + """Load and decrypt keys from a key file.""" try: with open(key_file, 'r') as f: encrypted_data = f.read() - + decrypted = self._xor_decrypt_data(encrypted_data, key_password) if decrypted is None: - print("❌ 密码错误") + print("❌ Incorrect password") self.keys_loaded = False return - + keys_data = self._deobfuscate_keys(decrypted) - + self.upper_mapping = keys_data['upper_mapping'] self.lower_mapping = keys_data['lower_mapping'] self.digit_mapping = keys_data['digit_mapping'] @@ -227,25 +267,26 @@ class EncryptionSystem: self.flip_pattern = keys_data['flip_pattern'] self.long_key = keys_data['long_key'] self.short_key = keys_data['short_key'] - + self.digit_reverse = {v: k for k, v in self.digit_mapping.items()} self.equal_reverse = {v: k for k, v in self.equal_mapping.items()} - + self.key_password = key_password self._build_maps() - + self.keys_loaded = True - print(f"✅ 密钥已从 {key_file} 加载") - + print(f"✅ Keys loaded from {key_file}") + except Exception: - print("❌ 加载失败") + print("❌ Loading failed") self.keys_loaded = False def _ensure_printable(self, text): + """Force all characters into printable ASCII range (32-126).""" result = [] for c in text: val = ord(c) - if val == 124: + if val == 124: # '|' is used as a separator, keep it result.append('|') elif val < 32 or val > 126: val = val % 95 + 32 @@ -254,10 +295,25 @@ class EncryptionSystem: result.append(c) return ''.join(result) + # ---------------------------------------------------------------------- + # Key derivation + # ---------------------------------------------------------------------- + def _mix_keys(self, user_password, target_length): + """ + Mix the user password with the short key using bit operations and swaps. + + Args: + user_password: User-provided password. + target_length: Desired output length. + + Returns: + A mixed printable string. + """ if not self.keys_loaded: - raise Exception("密钥未加载") - + raise Exception("Keys not loaded") + + # Interleave user password and short key mixed = [] max_len = max(len(user_password), len(self.short_key)) for i in range(max_len): @@ -265,7 +321,8 @@ class EncryptionSystem: mixed.append(ord(user_password[i])) if i < len(self.short_key): mixed.append(ord(self.short_key[i])) - + + # Apply bit transformations for i in range(len(mixed)): if i % 3 == 0: mixed[i] = (mixed[i] << 1) & 0xFF @@ -273,21 +330,24 @@ class EncryptionSystem: mixed[i] = (mixed[i] >> 1) & 0xFF else: mixed[i] = mixed[i] ^ 0x5A - + + # Swap pairs for i in range(0, len(mixed) - 3, 4): mixed[i], mixed[i+3] = mixed[i+3], mixed[i] mixed[i+1], mixed[i+2] = mixed[i+2], mixed[i+1] - + mixed.reverse() - + + # Convert to printable characters result = [] for x in mixed: if x < 32 or x > 126: x = x % 95 + 32 result.append(chr(x)) - + result_str = ''.join(result) - + + # Extend if needed by repeating with variations if len(result_str) < target_length: base_key = result_str final_key = base_key @@ -297,22 +357,29 @@ class EncryptionSystem: next_chunk = base_key[::-1] elif iteration % 3 == 1: next_chunk = base_key[::-1] - next_chunk = ''.join([chr((ord(c) + iteration) % 95 + 32) for c in next_chunk]) + next_chunk = ''.join(chr((ord(c) + iteration) % 95 + 32) for c in next_chunk) else: next_chunk = base_key[::-1] - next_chunk = ''.join([chr((ord(c) ^ iteration) % 95 + 32) for c in next_chunk]) + next_chunk = ''.join(chr((ord(c) ^ iteration) % 95 + 32) for c in next_chunk) final_key += next_chunk iteration += 1 result_str = final_key[:target_length] - + return self._ensure_printable(result_str) def _derive_final_key(self, user_password, text_length): + """ + Derive a final encryption key from the user password and short key. + + The process includes mixing, hex conversion, reversal, and extension. + """ mixed_key = self._mix_keys(user_password, text_length * 2) - - hex_key = ''.join([f"{ord(c):02x}" for c in mixed_key]) + + # Convert to hex and reverse + hex_key = ''.join(f"{ord(c):02x}" for c in mixed_key) reversed_hex = hex_key[::-1] - + + # Convert back to printable characters final_key = [] for i in range(0, len(reversed_hex), 2): if i + 1 < len(reversed_hex): @@ -324,9 +391,10 @@ class EncryptionSystem: final_key.append(chr(val)) except ValueError: final_key.append('x') - + final_key_str = ''.join(final_key) - + + # Extend if needed if len(final_key_str) < text_length: base_key = final_key_str iteration = 0 @@ -335,22 +403,25 @@ class EncryptionSystem: next_chunk = base_key[::-1] elif iteration % 3 == 1: next_chunk = base_key[::-1] - next_chunk = ''.join([chr((ord(c) + iteration) % 95 + 32) for c in next_chunk]) + next_chunk = ''.join(chr((ord(c) + iteration) % 95 + 32) for c in next_chunk) else: next_chunk = base_key[::-1] - next_chunk = ''.join([chr((ord(c) ^ iteration) % 95 + 32) for c in next_chunk]) + next_chunk = ''.join(chr((ord(c) ^ iteration) % 95 + 32) for c in next_chunk) final_key_str += next_chunk iteration += 1 - + final_key_str = final_key_str[:text_length] - final_key_str = self._ensure_printable(final_key_str) - - return final_key_str + return self._ensure_printable(final_key_str) + + # ---------------------------------------------------------------------- + # Core encryption operations + # ---------------------------------------------------------------------- def _apply_flip(self, text): + """Apply case-flipping based on the flip pattern.""" if self.flip_pattern is None: return text - + result = [] for i, ch in enumerate(text): idx = i % len(self.flip_pattern) @@ -361,15 +432,16 @@ class EncryptionSystem: return ''.join(result) def _xor_encrypt_with_final_key(self, text, user_password): + """XOR encrypt with the derived final key, returning hex.""" final_key = self._derive_final_key(user_password, len(text)) key_len = len(final_key) - result = [] - for i, char in enumerate(text): - xor_result = ord(char) ^ ord(final_key[i % key_len]) - result.append(f"{xor_result:02x}") - return ''.join(result) + return ''.join( + f"{ord(char) ^ ord(final_key[i % key_len]):02x}" + for i, char in enumerate(text) + ) def _xor_decrypt_with_final_key(self, hex_text, user_password): + """XOR decrypt with the derived final key.""" try: text_length = len(hex_text) // 2 final_key = self._derive_final_key(user_password, text_length) @@ -390,47 +462,35 @@ class EncryptionSystem: return None def _substitute_letters(self, text, mapping): - result = [] - for char in text: - if char in mapping: - result.append(mapping[char]) - else: - result.append(char) - return ''.join(result) + """Apply a substitution map to letters.""" + return ''.join(mapping.get(char, char) for char in text) def _encode_digit(self, num_str): - result = [] - for char in num_str: - if char in self.digit_mapping: - result.append(self.digit_mapping[char]) - else: - result.append(char) - return ''.join(result) + """Encode a digit string using the digit mapping.""" + return ''.join(self.digit_mapping.get(char, char) for char in num_str) def _decode_digit(self, encoded_str): - result = [] - for char in encoded_str: - if char in self.digit_reverse: - result.append(self.digit_reverse[char]) - else: - result.append(char) - return ''.join(result) + """Decode a digit string using the reverse digit mapping.""" + return ''.join(self.digit_reverse.get(char, char) for char in encoded_str) def _get_dynamic_key(self, text_length): + """Generate a dynamic key from the long key, repeated as needed.""" key = self.long_key - while len(key) < text_length: - key += self.long_key + if len(key) < text_length: + repeats = (text_length // len(key)) + 1 + key = (key * repeats)[:text_length] return key[:text_length] def _xor_encrypt_with_key(self, text, key): + """XOR encrypt with a fixed key, returning hex.""" key_len = len(key) - result = [] - for i, char in enumerate(text): - xor_result = ord(char) ^ ord(key[i % key_len]) - result.append(f"{xor_result:02x}") - return ''.join(result) + return ''.join( + f"{ord(char) ^ ord(key[i % key_len]):02x}" + for i, char in enumerate(text) + ) def _xor_decrypt_with_key(self, hex_text, key): + """XOR decrypt with a fixed key.""" try: key_len = len(key) result = [] @@ -448,45 +508,74 @@ class EncryptionSystem: except Exception: return None + # ---------------------------------------------------------------------- + # Public API + # ---------------------------------------------------------------------- + def encrypt(self, plaintext, user_password): + """ + Encrypt plaintext with the given password. + + Workflow: + 1. Base64 encode the plaintext. + 2. Apply letter substitution and case-flipping. + 3. Reverse the string and append padding count. + 4. XOR encrypt with dynamic key (long key). + 5. XOR encrypt with derived final key (user password + short key). + + Returns: + Encrypted ciphertext as a hex string. + """ if not self.keys_loaded: - return "❌ 错误:密钥未加载" - + return "❌ Error: Keys not loaded" + + # Step 1: Base64 encode and handle special chars b64 = base64.b64encode(plaintext.encode('utf-8')).decode('utf-8') equal_count = b64.count('=') - + processed = b64 for old, new in self.special_encrypt.items(): processed = processed.replace(old, new) processed = processed.rstrip('=') - + + # Step 2: Letter substitution + flip + reverse sub = self._substitute_letters(processed, self.encrypt_map) flipped = self._apply_flip(sub) reversed_text = flipped[::-1] - + + # Step 3: Append padding count equal_char = self.equal_mapping[str(equal_count)] with_equal = f"{reversed_text}|{equal_char}" - + + # Step 4: Dynamic key (long key) encryption key_length_str = str(len(with_equal)) key_length_encoded = self._encode_digit(key_length_str) - dynamic_key = self._get_dynamic_key(len(with_equal)) encrypted_by_dynamic = self._xor_encrypt_with_key(with_equal, dynamic_key) - + + # Step 5: Final encryption with derived key combined = f"{encrypted_by_dynamic}|{key_length_encoded}" final_encrypted = self._xor_encrypt_with_final_key(combined, user_password) - + return final_encrypted def decrypt(self, ciphertext, user_password): + """ + Decrypt ciphertext with the given password. + + Returns: + The original plaintext, or an error message on failure. + """ if not self.keys_loaded: - return "❌ 解密失败" - + return "❌ Decryption failed" + try: + # Step 1: Decrypt with derived final key combined = self._xor_decrypt_with_final_key(ciphertext, user_password) if combined is None: - return "❌ 解密失败" - + return "❌ Decryption failed" + + # Step 2: Extract hex data and length indicator if '|' in combined: parts = combined.split('|') if len(parts) >= 2: @@ -498,211 +587,234 @@ class EncryptionSystem: else: hex_data = combined key_length_encoded = 'g' - + + # Step 3: Decode length and get dynamic key key_length_str = self._decode_digit(key_length_encoded) try: key_length = int(key_length_str) except ValueError: key_length = 16 - + dynamic_key = self._get_dynamic_key(key_length) + + # Step 4: Decrypt with dynamic key xor_decrypted = self._xor_decrypt_with_key(hex_data, dynamic_key) if xor_decrypted is None: - return "❌ 解密失败" - + return "❌ Decryption failed" + + # Step 5: Extract main data and padding count if '|' in xor_decrypted: main_part, equal_char = xor_decrypted.split('|') equal_count = int(self.equal_reverse.get(equal_char, '0')) else: main_part = xor_decrypted equal_count = 0 - + + # Step 6: Reverse, flip, substitute reversed_text = main_part[::-1] flipped = self._apply_flip(reversed_text) sub = self._substitute_letters(flipped, self.decrypt_map) - + + # Step 7: Restore Base64 special chars and padding for old, new in self.special_decrypt.items(): sub = sub.replace(old, new) - + b64_with_equal = sub + '=' * equal_count - + if len(b64_with_equal) % 4 != 0: - return "❌ 解密失败" - + return "❌ Decryption failed" + + # Step 8: Base64 decode decoded = base64.b64decode(b64_with_equal.encode('utf-8')).decode('utf-8') return decoded - + except Exception: - return "❌ 解密失败" + return "❌ Decryption failed" def print_keys(self): + """Display information about the currently loaded keys.""" if not self.keys_loaded: - print("❌ 未加载密钥") + print("❌ Keys not loaded") return - + print("=" * 60) - print("密钥信息") + print("Key Information") print("=" * 60) - print(f"密钥文件: {self.key_file}") - print(f"大写映射表: {self.upper_mapping}") - print(f"小写映射表: {self.lower_mapping}") - print(f"翻转模式: {self.flip_pattern}") - print(f"长密钥长度: {len(self.long_key)} 位") - print(f"短密钥长度: {len(self.short_key)} 位") + print(f"Key file: {self.key_file}") + print(f"Uppercase mapping: {self.upper_mapping}") + print(f"Lowercase mapping: {self.lower_mapping}") + print(f"Flip pattern: {self.flip_pattern}") + print(f"Long key length: {len(self.long_key)} bits") + print(f"Short key length: {len(self.short_key)} bits") print("=" * 60) +# ---------------------------------------------------------------------- +# CLI Entry Point +# ---------------------------------------------------------------------- + def main(): + """Command-line interface for the encryption system.""" print("=" * 60) - print("欢迎使用加密系统") + print("Welcome to the Encryption System") print("=" * 60) - + crypto = None key_password = None - + + # Try loading default key file if os.path.exists("encryption.key"): - key_password = input("请输入默认密钥文件 (encryption.key) 的密码: ") + key_password = input("Enter password for default key file (encryption.key): ") crypto = EncryptionSystem("encryption.key", key_password) if not crypto.keys_loaded: - print("❌ 加载失败") + print("❌ Loading failed") crypto = None else: - print("\n未找到默认密钥文件,请先生成") - choice = input("是否生成默认密钥文件?(y/n): ").strip().lower() + print("\nDefault key file not found. Please generate one first.") + choice = input("Generate default key file? (y/n): ").strip().lower() if choice == 'y': crypto = EncryptionSystem() - key_password = crypto.generate_keys("encryption.key") - if key_password is None: - print("❌ 生成失败") + result = crypto.generate_keys("encryption.key") + if result is None: + print("❌ Generation failed") crypto = None else: - print("⚠️ 请使用模式4或5指定密钥文件,或模式6生成新密钥") - + print("⚠️ Use options 4, 5, or 6 to manage key files manually.") + + # Main interaction loop while True: - print("\n请选择操作:") - print("1. 使用默认密钥加密") - print("2. 使用默认密钥解密") - print("3. 生成新密钥(覆盖默认)") - print("4. 使用指定密钥文件加密") - print("5. 使用指定密钥文件解密") - print("6. 生成密钥并保存到当前文件夹") - print("7. 查看当前密钥信息") - print("8. 退出") - - choice = input("\n请选择操作 (1-8): ").strip() - + print("\nSelect an option:") + print("1. Encrypt with default key") + print("2. Decrypt with default key") + print("3. Generate new key (overwrite default)") + print("4. Encrypt with custom key file") + print("5. Decrypt with custom key file") + print("6. Generate key and save to current folder") + print("7. View current key info") + print("8. Exit") + + choice = input("\nEnter choice (1-8): ").strip() + if choice == '1': + # Encrypt with default key if crypto is None or not crypto.keys_loaded: if os.path.exists("encryption.key"): if key_password is None: - key_password = input("请输入默认密钥文件密码: ") + key_password = input("Enter default key file password: ") crypto = EncryptionSystem("encryption.key", key_password) if not crypto.keys_loaded: - print("❌ 加载失败") + print("❌ Loading failed") continue else: - print("❌ 密钥文件不存在") + print("❌ Key file not found") continue - - password = input("请输入加密密码: ") - text = input("请输入要加密的文本: ") + + password = input("Enter encryption password: ") + text = input("Enter text to encrypt: ") if text and password: encrypted = crypto.encrypt(text, password) - print(f"\n✅ 加密结果: {encrypted}") - + print(f"\n✅ Encrypted result: {encrypted}") + elif choice == '2': + # Decrypt with default key if crypto is None or not crypto.keys_loaded: if os.path.exists("encryption.key"): if key_password is None: - key_password = input("请输入默认密钥文件密码: ") + key_password = input("Enter default key file password: ") crypto = EncryptionSystem("encryption.key", key_password) if not crypto.keys_loaded: - print("❌ 加载失败") + print("❌ Loading failed") continue else: - print("❌ 密钥文件不存在") + print("❌ Key file not found") continue - - password = input("请输入加密密码: ") - text = input("请输入要解密的密文: ") + + password = input("Enter encryption password: ") + text = input("Enter ciphertext to decrypt: ") if text and password: decrypted = crypto.decrypt(text, password) - print(f"\n✅ 解密结果: {decrypted}") - + print(f"\n✅ Decrypted result: {decrypted}") + elif choice == '3': + # Generate and overwrite default key crypto = EncryptionSystem() - key_password = crypto.generate_keys("encryption.key") - if key_password is None: - print("❌ 生成失败") + result = crypto.generate_keys("encryption.key") + if result is None: + print("❌ Generation failed") else: - print("✅ 默认密钥已更新") - + print("✅ Default key updated") + elif choice == '4': - key_file = input("请输入密钥文件路径: ") + # Encrypt with custom key file + key_file = input("Enter key file path: ") if not os.path.exists(key_file): - print(f"❌ 文件不存在") + print(f"❌ File not found: {key_file}") continue - - kp = input(f"请输入密钥文件密码: ") + + kp = input("Enter key file password: ") crypto = EncryptionSystem(key_file, kp) if not crypto.keys_loaded: - print("❌ 加载失败") + print("❌ Loading failed") continue - - password = input("请输入加密密码: ") - text = input("请输入要加密的文本: ") + + password = input("Enter encryption password: ") + text = input("Enter text to encrypt: ") if text and password: encrypted = crypto.encrypt(text, password) - print(f"\n✅ 加密结果: {encrypted}") - + print(f"\n✅ Encrypted result: {encrypted}") + elif choice == '5': - key_file = input("请输入密钥文件路径: ") + # Decrypt with custom key file + key_file = input("Enter key file path: ") if not os.path.exists(key_file): - print(f"❌ 文件不存在") + print(f"❌ File not found: {key_file}") continue - - kp = input(f"请输入密钥文件密码: ") + + kp = input("Enter key file password: ") crypto = EncryptionSystem(key_file, kp) if not crypto.keys_loaded: - print("❌ 加载失败") + print("❌ Loading failed") continue - - password = input("请输入加密密码: ") - text = input("请输入要解密的密文: ") + + password = input("Enter encryption password: ") + text = input("Enter ciphertext to decrypt: ") if text and password: decrypted = crypto.decrypt(text, password) - print(f"\n✅ 解密结果: {decrypted}") - + print(f"\n✅ Decrypted result: {decrypted}") + elif choice == '6': + # Generate new key with timestamp timestamp = int(time.time()) filename = f"key_{timestamp}.key" crypto = EncryptionSystem() - kp = crypto.generate_keys(filename) - if kp is None: - print("❌ 生成失败") + result = crypto.generate_keys(filename) + if result is None: + print("❌ Generation failed") else: - print(f"✅ 密钥已保存到: {filename}") - + print(f"✅ Key saved to: {filename}") + elif choice == '7': + # Show key info if crypto is None or not crypto.keys_loaded: if os.path.exists("encryption.key"): if key_password is None: - key_password = input("请输入默认密钥文件密码: ") + key_password = input("Enter default key file password: ") crypto = EncryptionSystem("encryption.key", key_password) if not crypto.keys_loaded: - print("❌ 加载失败") + print("❌ Loading failed") continue else: - print("❌ 未加载密钥") + print("❌ Keys not loaded") continue crypto.print_keys() - + elif choice == '8': - print("感谢使用,再见!") + print("Goodbye!") break - + else: - print("❌ 无效选择") + print("❌ Invalid choice") + if __name__ == "__main__": - main() + main() \ No newline at end of file diff --git a/chaoscrypt/py.typed b/chaoscrypt/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/chaoscrypt/tests/test_chaoscrypt.py b/chaoscrypt/tests/test_chaoscrypt.py new file mode 100644 index 0000000..ccf4c9b --- /dev/null +++ b/chaoscrypt/tests/test_chaoscrypt.py @@ -0,0 +1,603 @@ +""" +ChaosCrypt test suite. + +Covers round-trip integrity, binary safety, key management, the unified error +types, CLI behaviour, i18n, and bidirectional compatibility with the original +single-file implementation. +""" + +import base64 +import json +import os +import subprocess +import sys + +import pytest + +from chaoscrypt import ( + DEFAULT_KEY_FILE, + ChaosCrypt, + ChaosCryptCore, + ChaosCryptError, + ChaosCrypt_ERR_KeyFileNotFound_E001, + ChaosCrypt_ERR_KeyFileExists_E005, + ChaosCrypt_ERR_KeyNotLoaded_E004, + ChaosCrypt_ERR_EmptyPassword_E006, + ChaosCrypt_ERR_EmptyPlaintext_E008, + ChaosCrypt_ERR_DecryptionFailed_E011, +) +from chaoscrypt.i18n import LANG_NAMES, t + +KEY_PWD = "key-file-password" +USER_PWD = "user-encryption-password" + + +# --------------------------------------------------------------------------- +# Fixtures +# --------------------------------------------------------------------------- +@pytest.fixture +def keyfile(tmp_path): + """Create a key file and return ``(ChaosCrypt, path)``.""" + path = str(tmp_path / "test.key") + cc = ChaosCrypt() + cc.create_key(KEY_PWD, path) + return cc, path + + +@pytest.fixture +def loaded(keyfile): + """Return an instance with key material already loaded.""" + _, path = keyfile + n = ChaosCrypt() + n.load(path, KEY_PWD) + return n + + +# --------------------------------------------------------------------------- +# Round-trip +# --------------------------------------------------------------------------- +class TestRoundTrip: + SAMPLES = [ + "hello", + "hello 世界", + "emoji test 🎉", + "a", + "x" * 1000, + "Mixed mixed 123!@#$%^&*()_+-=[]{}|;':\",./<>?", + "line1\nline2\ttabbed", + " leading and trailing ", + ] + + @pytest.mark.parametrize("text", SAMPLES) + def test_text_roundtrip(self, loaded, text): + ct = loaded.encrypt(text, USER_PWD) + assert loaded.decrypt(ct, USER_PWD) == text + + def test_ciphertext_is_hex(self, loaded): + ct = loaded.encrypt("data", USER_PWD) + int(ct, 16) + + def test_empty_plaintext_rejected(self, loaded): + with pytest.raises(ChaosCryptError) as ei: + loaded.encrypt("", USER_PWD) + assert ei.value.code == "E008" + + def test_empty_password_rejected(self, loaded): + with pytest.raises(ChaosCryptError) as ei: + loaded.encrypt("data", "") + assert ei.value.code == "E006" + + def test_wrong_password_fails(self, loaded): + ct = loaded.encrypt("secret", USER_PWD) + with pytest.raises(ChaosCryptError) as ei: + loaded.decrypt(ct, "wrong-password") + assert ei.value.code == "E011" + + def test_ciphertext_differs_per_password(self, loaded): + a = loaded.encrypt("same", "pwd-A") + b = loaded.encrypt("same", "pwd-B") + assert a != b + + def test_non_hex_ciphertext_rejected(self, loaded): + with pytest.raises(ChaosCryptError) as ei: + loaded.decrypt("zzzz-not-hex", USER_PWD) + assert ei.value.code == "E010" + + def test_odd_length_ciphertext_rejected(self, loaded): + with pytest.raises(ChaosCryptError) as ei: + loaded.decrypt("abc", USER_PWD) + assert ei.value.code == "E010" + + def test_empty_ciphertext_rejected(self, loaded): + with pytest.raises(ChaosCryptError) as ei: + loaded.decrypt("", USER_PWD) + assert ei.value.code == "E009" + + +# --------------------------------------------------------------------------- +# Binary +# --------------------------------------------------------------------------- +class TestBinary: + @pytest.mark.parametrize("size", [1, 2, 255, 256, 4096, 100_000]) + def test_binary_roundtrip(self, loaded, size): + raw = os.urandom(size) + ct = loaded.encrypt_bytes(raw, USER_PWD) + assert loaded.decrypt_bytes(ct, USER_PWD) == raw + + def test_empty_binary_rejected(self, loaded): + with pytest.raises(ChaosCryptError): + loaded.encrypt_bytes(b"", USER_PWD) + + def test_null_bytes_preserved(self, loaded): + raw = b"\x00\x01\x02\xff\xfe" * 100 + ct = loaded.encrypt_bytes(raw, USER_PWD) + assert loaded.decrypt_bytes(ct, USER_PWD) == raw + + +# --------------------------------------------------------------------------- +# Key management +# --------------------------------------------------------------------------- +class TestKeyManagement: + def test_generate_and_load(self, tmp_path): + path = str(tmp_path / "k.key") + cc = ChaosCrypt() + assert cc.create_key(KEY_PWD, path) == path + assert os.path.exists(path) + + n = ChaosCrypt() + n.load(path, KEY_PWD) + assert n.loaded + + def test_keygen_refuses_overwrite(self, tmp_path): + path = str(tmp_path / "k.key") + ChaosCrypt().create_key(KEY_PWD, path) + with pytest.raises(ChaosCryptError) as ei: + ChaosCrypt().create_key(KEY_PWD, path) + assert ei.value.code == "E005" + + def test_keygen_force_overwrite(self, tmp_path): + path = str(tmp_path / "k.key") + cc = ChaosCrypt() + cc.create_key(KEY_PWD, path) + first_upper = cc.core.upper_mapping + cc.create_key(KEY_PWD, path, overwrite=True) + assert cc.core.upper_mapping != first_upper + + def test_load_missing_file(self): + with pytest.raises(ChaosCryptError) as ei: + ChaosCrypt().load("/definitely/not/here.key", KEY_PWD) + assert ei.value.code == "E001" + + def test_load_wrong_key_password(self, keyfile): + _, path = keyfile + with pytest.raises(ChaosCryptError) as ei: + ChaosCrypt().load(path, "bad-password") + assert ei.value.code == "E003" + + def test_load_corrupted_file(self, tmp_path): + path = tmp_path / "bad.key" + path.write_text("this is not a chaoscrypt key file!!!", encoding="utf-8") + with pytest.raises(ChaosCryptError) as ei: + ChaosCrypt().load(str(path), KEY_PWD) + assert ei.value.code == "E002" + + def test_load_empty_file(self, tmp_path): + path = tmp_path / "empty.key" + path.write_text("", encoding="utf-8") + with pytest.raises(ChaosCryptError) as ei: + ChaosCrypt().load(str(path), KEY_PWD) + assert ei.value.code == "E002" + + def test_encrypt_without_key_raises(self): + cc = ChaosCrypt() + with pytest.raises(ChaosCryptError) as ei: + cc.encrypt("data", USER_PWD) + assert ei.value.code == "E004" + + def test_change_key_password(self, keyfile): + cc, path = keyfile + cc.change_key_password(KEY_PWD, "new-key-password", path) + + ok = ChaosCrypt() + ok.load(path, "new-key-password") + assert ok.loaded + + with pytest.raises(ChaosCryptError) as ei: + ChaosCrypt().load(path, KEY_PWD) + assert ei.value.code == "E003" + + def test_change_password_preserves_data(self, keyfile): + cc, path = keyfile + ct = cc.encrypt("preserve me", USER_PWD) + cc.change_key_password(KEY_PWD, "brand-new-pwd", path) + + n = ChaosCrypt() + n.load(path, "brand-new-pwd") + assert n.decrypt(ct, USER_PWD) == "preserve me" + + def test_info_reports_key_sizes(self, loaded): + info = loaded.info() + assert info["long_key_length"] == 4096 + assert info["short_key_length"] == 512 + assert len(info["upper_mapping"]) == 26 + assert len(info["flip_pattern"]) == 10 + + def test_export_and_import_key_text(self): + cc = ChaosCrypt() + text = cc.export_key_text(KEY_PWD) + assert text and isinstance(text, str) + assert cc.loaded, "export_key_text should leave the instance usable" + + n = ChaosCrypt() + n.load_from_text(text, KEY_PWD) + ct = n.encrypt("via text", USER_PWD) + assert cc.decrypt(ct, USER_PWD) == "via text" + + def test_load_from_text_wrong_password(self): + cc = ChaosCrypt() + text = cc.export_key_text(KEY_PWD) + with pytest.raises(ChaosCryptError) as ei: + ChaosCrypt().load_from_text(text, "not-the-password") + assert ei.value.code == "E003" + + +# --------------------------------------------------------------------------- +# Key isolation +# --------------------------------------------------------------------------- +class TestKeyIsolation: + def test_two_keys_produce_different_ciphertext(self, tmp_path): + a = ChaosCrypt() + a.create_key(KEY_PWD, str(tmp_path / "a.key")) + b = ChaosCrypt() + b.create_key(KEY_PWD, str(tmp_path / "b.key")) + assert a.encrypt("same text", USER_PWD) != b.encrypt("same text", USER_PWD) + + def test_cross_key_decryption_fails(self, tmp_path): + a = ChaosCrypt() + a.create_key(KEY_PWD, str(tmp_path / "a.key")) + b = ChaosCrypt() + b.create_key(KEY_PWD, str(tmp_path / "b.key")) + + ct = a.encrypt("cross-key test", USER_PWD) + try: + got = b.decrypt(ct, USER_PWD) + except ChaosCryptError: + got = None + assert got != "cross-key test" + + +# --------------------------------------------------------------------------- +# File API +# --------------------------------------------------------------------------- +class TestFileAPI: + def test_encrypt_decrypt_file(self, loaded, tmp_path): + src = tmp_path / "data.bin" + payload = os.urandom(2048) + src.write_bytes(payload) + + cc_file = str(tmp_path / "data.bin.cc") + out = loaded.encrypt_file(str(src), USER_PWD, cc_file) + assert os.path.exists(out) + + dst = str(tmp_path / "restored.bin") + back = loaded.decrypt_file(cc_file, USER_PWD, dst) + assert open(back, "rb").read() == payload + + def test_default_suffixes(self, loaded, tmp_path): + src = tmp_path / "note.txt" + src.write_text("hello file", encoding="utf-8") + out = loaded.encrypt_file(str(src), USER_PWD) + assert out.endswith(".cc") + + back = loaded.decrypt_file(out, USER_PWD) + assert open(back, encoding="utf-8").read() == "hello file" + + def test_missing_source_raises(self, loaded): + with pytest.raises(ChaosCryptError) as ei: + loaded.encrypt_file("/no/such/file.bin", USER_PWD) + assert ei.value.code == "E014" + + +# --------------------------------------------------------------------------- +# Unified error types +# --------------------------------------------------------------------------- +class TestErrorClass: + def test_message_format(self): + from chaoscrypt import ChaosCrypt_ERR_DecryptionFailed_E011 + e = ChaosCrypt_ERR_DecryptionFailed_E011() + assert str(e).startswith("ChaosCrypt_ERR_") + assert str(e).endswith("_E011") + + def test_code_and_detail_attributes(self): + e = ChaosCrypt_ERR_EmptyPlaintext_E008() + assert e.code == "E008" + assert e.detail == "EmptyPlaintext" + assert e.message == "ChaosCrypt_ERR_EmptyPlaintext_E008" + + def test_all_errors_share_base(self): + from chaoscrypt import errors + for name in errors.__all__: + obj = getattr(errors, name) + if name == "ChaosCryptError": + continue + assert issubclass(obj, ChaosCryptError) + assert issubclass(obj, Exception) + + def test_codes_are_unique(self): + from chaoscrypt import errors + codes = [] + for name in errors.__all__: + obj = getattr(errors, name) + if name == "ChaosCryptError": + continue + codes.append(obj.CODE) + assert len(codes) == len(set(codes)), "duplicate error codes" + + def test_custom_detail(self): + e = ChaosCrypt_ERR_KeyFileNotFound_E001( + detail="CustomDetail", code="E001" + ) + assert e.detail == "CustomDetail" + assert e.code == "E001" + + def test_catchable_as_generic_exception(self): + from chaoscrypt import ChaosCrypt_ERR_DecryptionFailed_E011 + with pytest.raises(Exception): + raise ChaosCrypt_ERR_DecryptionFailed_E011() + + +# --------------------------------------------------------------------------- +# Algorithm compatibility +# --------------------------------------------------------------------------- +class TestLegacyCompatibility: + def test_format_matches_original_chain(self, loaded): + """Reproduce the original decryption chain step by step.""" + text = "compat check compatibility" + ct = loaded.encrypt(text, USER_PWD) + + core = loaded.core + combined = core._xor_decrypt_with_final_key(ct, USER_PWD) + hex_data, key_len_enc = combined.split("|") + key_len = int(core._decode_digit(key_len_enc)) + x = core._xor_decrypt_with_key(hex_data, core._get_dynamic_key(key_len)) + main, eq_char = x.split("|") + eq_count = int(core.equal_reverse[eq_char]) + sub = core._substitute_letters( + core._apply_flip(main[::-1]), core.decrypt_map + ) + for o, n in core.special_decrypt.items(): + sub = sub.replace(o, n) + assert base64.b64decode((sub + "=" * eq_count).encode()).decode() == text + + def test_keyfile_readable_by_original_scheme(self, keyfile): + """A newly generated key file must satisfy the original format.""" + _, path = keyfile + core = ChaosCryptCore() + with open(path, "r") as f: + enc = f.read() + + decrypted = core._xor_decrypt_data(enc, KEY_PWD) + assert decrypted is not None + data = core._deobfuscate_keys(decrypted) + assert set(data) >= { + "upper_mapping", "lower_mapping", "digit_mapping", + "equal_mapping", "flip_pattern", "long_key", "short_key", + } + assert len(data["long_key"]) == 4096 + assert len(data["short_key"]) == 512 + + def test_reference_vector_stable(self): + """Fixed key material must always produce the same ciphertext.""" + core = ChaosCryptCore() + core.upper_mapping = "BCDEFGHIJKLMNOPQRSTUVWXYZA" + core.lower_mapping = "bcdefghijklmnopqrstuvwxyza" + core.digit_mapping = { + str(i): c for i, c in enumerate("ABCDEFGHIJ") + } + core.equal_mapping = {"0": "X", "1": "Y", "2": "Z", "3": "W"} + core.flip_pattern = [1, 0, 1, 0, 0, 1, 0, 0, 1, 0] + core.long_key = "0123456789abcdef" * 256 + core.short_key = "fedcba9876543210" * 32 + core.digit_reverse = {v: k for k, v in core.digit_mapping.items()} + core.equal_reverse = {v: k for k, v in core.equal_mapping.items()} + core._build_maps() + core.keys_loaded = True + + plaintext = "reference vector" + ct1 = core.encrypt_text(plaintext, USER_PWD) + ct2 = core.encrypt_text(plaintext, USER_PWD) + assert ct1 == ct2 + assert core.decrypt_text(ct1, USER_PWD) == plaintext + + +# --------------------------------------------------------------------------- +# i18n +# --------------------------------------------------------------------------- +class TestI18n: + def test_english_is_default(self): + import chaoscrypt.i18n as i18n + assert i18n.DEFAULT_LANG == "en" + + def test_langs_available(self): + assert "en" in LANG_NAMES + assert "zh" in LANG_NAMES + + def test_t_returns_both_languages(self): + en = t("app_title", "en") + zh = t("app_title", "zh") + assert en != zh + assert "ChaosCrypt" in en + + def test_t_default_is_english(self): + assert t("app_title") == t("app_title", "en") + + def test_t_fallback_for_unknown_key(self): + assert t("nonexistent_key_xyz", "en") == "nonexistent_key_xyz" + + def test_missing_language_falls_back(self): + assert t("app_title", "fr") == t("app_title", "en") + + def test_every_key_has_both_languages(self): + from chaoscrypt.i18n import TEXTS + for key, entry in TEXTS.items(): + assert "en" in entry, f"{key} missing English" + assert "zh" in entry, f"{key} missing Chinese" + + def test_tui_defaults_to_english(self): + from chaoscrypt.tui import TUI + tui = TUI() + assert tui.lang == "en" + assert tui._tr("menu_encrypt") == "Encrypt text" + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- +class TestCLI: + @staticmethod + def _run(args, **kw): + return subprocess.run( + [sys.executable, "-m", "chaoscrypt"] + args, + capture_output=True, text=True, **kw, + ) + + def test_version(self): + r = self._run(["--version"]) + assert r.returncode == 0 + assert "2.1.6" in r.stdout + + def test_help_mentions_scope(self): + r = self._run(["--help"]) + assert r.returncode == 0 + assert "unaudited" in r.stdout.lower() + + def test_keygen_and_encrypt_decrypt(self, tmp_path): + kf = str(tmp_path / "cli.key") + + r = self._run(["keygen", "-k", kf, "-P", KEY_PWD]) + assert r.returncode == 0, r.stderr + assert os.path.exists(kf) + + r = self._run(["encrypt", "cli round trip", "-p", USER_PWD, + "-k", kf, "-P", KEY_PWD]) + assert r.returncode == 0, r.stderr + ct = r.stdout.strip() + + r = self._run(["decrypt", ct, "-p", USER_PWD, "-k", kf, "-P", KEY_PWD]) + assert r.returncode == 0, r.stderr + assert r.stdout.strip() == "cli round trip" + + def test_json_output(self, tmp_path): + kf = str(tmp_path / "j.key") + self._run(["keygen", "-k", kf, "-P", KEY_PWD]) + + r = self._run(["--json", "encrypt", "json test", "-p", USER_PWD, + "-k", kf, "-P", KEY_PWD]) + payload = json.loads(r.stdout) + assert payload["ok"] is True + assert payload["mode"] == "encrypt" + assert payload["ciphertext"] + + def test_info_json_redacts_maps(self, tmp_path): + kf = str(tmp_path / "i.key") + self._run(["keygen", "-k", kf, "-P", KEY_PWD]) + r = self._run(["--json", "info", "-k", kf, "-P", KEY_PWD]) + payload = json.loads(r.stdout) + assert payload["long_key_length"] == 4096 + assert "hidden" in payload["upper_mapping"] + + def test_error_exit_code(self, tmp_path): + r = self._run(["decrypt", "zzzz", "-p", USER_PWD, + "-k", str(tmp_path / "nope.key"), "-P", KEY_PWD]) + assert r.returncode == 1 + assert "ChaosCrypt_ERR_" in r.stderr + + def test_password_from_env(self, tmp_path): + kf = str(tmp_path / "env.key") + env = dict(os.environ, CC_KP=KEY_PWD, CC_UP=USER_PWD) + r = self._run(["keygen", "-k", kf, "--key-pwd-env", "CC_KP"], env=env) + assert r.returncode == 0, r.stderr + + r = self._run(["encrypt", "env test", "--pwd-env", "CC_UP", + "-k", kf, "-P", KEY_PWD], env=env) + assert r.returncode == 0, r.stderr + + def test_password_from_file(self, tmp_path): + kf = str(tmp_path / "f.key") + pwd_file = tmp_path / ".pwd" + pwd_file.write_text(KEY_PWD + "\n", encoding="utf-8") + r = self._run(["keygen", "-k", kf, "--key-pwd-file", str(pwd_file)]) + assert r.returncode == 0, r.stderr + + def test_file_encrypt_decrypt(self, tmp_path): + kf = str(tmp_path / "f.key") + src = tmp_path / "in.txt" + src.write_text("file cli test", encoding="utf-8") + + self._run(["keygen", "-k", kf, "-P", KEY_PWD]) + r = self._run(["file", "encrypt", str(src), "-p", USER_PWD, + "-k", kf, "-P", KEY_PWD]) + assert r.returncode == 0, r.stderr + + cc_file = str(src) + ".cc" + assert os.path.exists(cc_file) + + dst = str(tmp_path / "out.txt") + r = self._run(["file", "decrypt", cc_file, "-o", dst, "-p", USER_PWD, + "-k", kf, "-P", KEY_PWD]) + assert r.returncode == 0, r.stderr + assert open(dst, encoding="utf-8").read() == "file cli test" + + def test_chpwd(self, tmp_path): + kf = str(tmp_path / "c.key") + self._run(["keygen", "-k", kf, "-P", KEY_PWD]) + r = self._run(["chpwd", "-k", kf, "-P", KEY_PWD, + "--new-pwd", "brand-new"]) + assert r.returncode == 0, r.stderr + + r = self._run(["info", "-k", kf, "-P", "brand-new"]) + assert r.returncode == 0, r.stderr + + +# --------------------------------------------------------------------------- +# Core used directly +# --------------------------------------------------------------------------- +class TestCoreDirect: + def test_core_generate_and_use(self): + c = ChaosCryptCore() + data = c.generate_keymaterial() + ct = c.encrypt_text("core direct", USER_PWD) + assert c.decrypt_text(ct, USER_PWD) == "core direct" + + text = c._xor_encrypt_data(c._obfuscate_keys(data), KEY_PWD) + c2 = ChaosCryptCore() + c2.load_keys_from_text(text, KEY_PWD) + assert c2.decrypt_text(ct, USER_PWD) == "core direct" + + def test_key_material_sizes(self): + c = ChaosCryptCore() + c.generate_keymaterial() + assert len(c.upper_mapping) == 26 + assert len(c.lower_mapping) == 26 + assert len(c.digit_mapping) == 10 + assert len(c.equal_mapping) == 4 + assert len(c.flip_pattern) == 10 + assert len(c.long_key) == 4096 + assert len(c.short_key) == 512 + + def test_mappings_are_bijections(self): + c = ChaosCryptCore() + c.generate_keymaterial() + assert sorted(c.upper_mapping) == sorted("ABCDEFGHIJKLMNOPQRSTUVWXYZ") + assert sorted(c.lower_mapping) == sorted("abcdefghijklmnopqrstuvwxyz") + assert len(set(c.digit_mapping.values())) == 10 + assert len(set(c.equal_mapping.values())) == 4 + + def test_key_material_is_random_between_instances(self): + a = ChaosCryptCore() + a.generate_keymaterial() + b = ChaosCryptCore() + b.generate_keymaterial() + assert a.long_key != b.long_key + assert a.short_key != b.short_key + assert a.upper_mapping != b.upper_mapping diff --git a/chaoscrypt/tests/test_legacy_interop.py b/chaoscrypt/tests/test_legacy_interop.py new file mode 100644 index 0000000..1b58c3a --- /dev/null +++ b/chaoscrypt/tests/test_legacy_interop.py @@ -0,0 +1,84 @@ +""" +Bidirectional interoperability tests against the original implementation. + +These tests load ``chaoscrypt/legacy/chaoscrypt_legacy.py`` and prove that: + +* ciphertext produced by the original script decrypts with the packaged + library, and +* ciphertext produced by the packaged library decrypts with the original + script. + +They are the regression guard for the promise that the algorithm itself was +ported without any behavioural change. +""" + +import importlib.util +import os + +import pytest + +from chaoscrypt import ChaosCrypt + +KEY_PWD = "legacy-key-password" +USER_PWD = "legacy-user-password" + +SAMPLES = [ + "legacy compatibility", + "兼容性检查", + "x" * 300, + "emoji test 🎉", + "multi\nline\ttabbed", +] + + +def _load_legacy(): + """Import the legacy single-file implementation, or skip if absent.""" + here = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + legacy = os.path.join(here, "legacy", "chaoscrypt_legacy.py") + if not os.path.exists(legacy): + pytest.skip("legacy implementation not present") + spec = importlib.util.spec_from_file_location("cc_legacy", legacy) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + +class TestLegacyInterop: + def test_library_decrypts_legacy_ciphertext(self, tmp_path): + legacy_mod = _load_legacy() + kf = str(tmp_path / "legacy.key") + + old = legacy_mod.EncryptionSystem() + old.generate_keys(kf, KEY_PWD) + + pairs = [(tx, old.encrypt(tx, USER_PWD)) for tx in SAMPLES] + + new = ChaosCrypt() + new.load(kf, KEY_PWD) + for tx, ct in pairs: + assert new.decrypt(ct, USER_PWD) == tx + + def test_legacy_decrypts_library_ciphertext(self, tmp_path): + legacy_mod = _load_legacy() + kf = str(tmp_path / "legacy2.key") + + new = ChaosCrypt() + new.create_key(KEY_PWD, kf) + + old = legacy_mod.EncryptionSystem() + old._load_keys(kf, KEY_PWD) + + for tx in SAMPLES: + ct = new.encrypt(tx, USER_PWD) + assert old.decrypt(ct, USER_PWD) == tx + + def test_key_files_are_identical_in_format(self, tmp_path): + """A library key file must load in the original implementation.""" + legacy_mod = _load_legacy() + kf = str(tmp_path / "fmt.key") + + ChaosCrypt().create_key(KEY_PWD, kf) + + old = legacy_mod.EncryptionSystem() + old._load_keys(kf, KEY_PWD) + assert old.keys_loaded diff --git a/chaoscrypt/tests/test_tui.py b/chaoscrypt/tests/test_tui.py new file mode 100644 index 0000000..05a25f8 --- /dev/null +++ b/chaoscrypt/tests/test_tui.py @@ -0,0 +1,139 @@ +""" +Interactive TUI tests. + +A key sequence is piped into the UI and the rendered output is inspected. +Outside a TTY the UI falls back from ``getpass`` to ``input``, which is what +makes it scriptable. +""" + +import os +import re +import subprocess +import sys + +import pytest + +KEY_PWD = "tui-key-password" +USER_PWD = "tui-user-password" + + +def _run_tui(seq: str, cwd: str, timeout: int = 90): + env = dict(os.environ, PYTHONIOENCODING="utf-8", NO_COLOR="1") + return subprocess.run( + [sys.executable, "-m", "chaoscrypt"], + input=seq, capture_output=True, text=True, + encoding="utf-8", env=env, cwd=cwd, timeout=timeout, + ) + + +@pytest.fixture +def tui_dir(tmp_path): + """Create a TUI key file in an isolated directory.""" + seq = f"5\nt.key\n{KEY_PWD}\n{KEY_PWD}\n\nq\n" + r = _run_tui(seq, str(tmp_path)) + assert (tmp_path / "t.key").exists(), r.stdout + return str(tmp_path) + + +class TestTUI: + def test_launches_in_english_by_default(self, tmp_path): + r = _run_tui("q\n", str(tmp_path)) + assert r.returncode == 0 + assert "ChaosCrypt" in r.stdout + assert "Select an action" in r.stdout + assert "Encrypt text" in r.stdout + + def test_shows_scope_notice(self, tmp_path): + r = _run_tui("q\n", str(tmp_path)) + assert "unaudited" in r.stdout + assert "not for production" in r.stdout.lower() + + def test_keygen_creates_file(self, tmp_path): + r = _run_tui(f"5\nmy.key\n{KEY_PWD}\n{KEY_PWD}\n\nq\n", str(tmp_path)) + assert (tmp_path / "my.key").exists(), r.stdout + assert "Key file written to" in r.stdout + + def test_keygen_password_mismatch(self, tmp_path): + r = _run_tui("5\nm.key\npwd-one\npwd-two\n\nq\n", str(tmp_path)) + assert "E007" in r.stdout + assert not (tmp_path / "m.key").exists() + + def test_encrypt_then_decrypt_in_new_session(self, tmp_path): + seq = (f"5\nt.key\n{KEY_PWD}\n{KEY_PWD}\n\n" + f"1\nsecret payload\n{USER_PWD}\n\nq\n") + r1 = _run_tui(seq, str(tmp_path)) + m = re.search(r"Ciphertext:\s*\n([0-9a-f]{16,})", r1.stdout) + assert m, r1.stdout + ct = m.group(1).strip() + + seq2 = f"6\nt.key\n{KEY_PWD}\n\n2\n{ct}\n{USER_PWD}\n\nq\n" + r2 = _run_tui(seq2, str(tmp_path)) + assert "secret payload" in r2.stdout, r2.stdout + + def test_load_remembers_key_file(self, tui_dir): + seq = f"6\nt.key\n{KEY_PWD}\n\n1\nremembers\n{USER_PWD}\n\nq\n" + r = _run_tui(seq, tui_dir) + assert re.search(r"Ciphertext:\s*\n([0-9a-f]{16,})", r.stdout), r.stdout + + def test_wrong_user_password_shows_error(self, tui_dir): + seq = f"6\nt.key\n{KEY_PWD}\n\n2\n{'a' * 64}\nWRONG-{USER_PWD}\n\nq\n" + r = _run_tui(seq, tui_dir) + assert "ChaosCrypt_ERR_" in r.stdout + + def test_wrong_key_password_shows_e003(self, tui_dir): + r = _run_tui("6\nt.key\nWRONG-KEY-PWD\n\nq\n", tui_dir) + assert "_E003" in r.stdout + + def test_language_switch_to_chinese(self, tmp_path): + r = _run_tui("9\n2\n\nq\n", str(tmp_path)) + assert "混沌混淆加密" in r.stdout + assert "请选择操作" in r.stdout + + def test_language_switch_back_to_english(self, tmp_path): + r = _run_tui("9\n2\n\n9\n1\n\nq\n", str(tmp_path)) + assert "Select an action" in r.stdout + + def test_chinese_mode_encrypt_works(self, tui_dir): + seq = (f"6\nt.key\n{KEY_PWD}\n\n9\n2\n\n" + f"1\n中文内容\n{USER_PWD}\n\nq\n") + r = _run_tui(seq, tui_dir) + assert re.search(r"密文:\s*\n([0-9a-f]{16,})", r.stdout), r.stdout + + def test_about_page_has_design_notes(self, tmp_path): + r = _run_tui("a\n\nq\n", str(tmp_path)) + assert "10^5621" in r.stdout + assert "MIT" in r.stdout + assert "Shor" in r.stdout + + def test_key_info_shows_sizes(self, tui_dir): + r = _run_tui(f"6\nt.key\n{KEY_PWD}\n\n7\n\nq\n", tui_dir) + assert "4096" in r.stdout + assert "512" in r.stdout + + def test_invalid_option_reprompts(self, tmp_path): + r = _run_tui("zzz\n\nq\n", str(tmp_path)) + assert "Unrecognised option" in r.stdout + + def test_change_key_password_in_session(self, tui_dir): + seq = f"8\nt.key\n{KEY_PWD}\nnewkeypass\nnewkeypass\n\nq\n" + r = _run_tui(seq, tui_dir) + assert "updated" in r.stdout + + r2 = _run_tui("6\nt.key\nnewkeypass\n\nq\n", tui_dir) + assert "Key file loaded" in r2.stdout + + def test_file_encrypt_decrypt_via_tui(self, tui_dir): + src = os.path.join(tui_dir, "payload.txt") + with open(src, "w", encoding="utf-8") as f: + f.write("TUI file payload") + + seq = (f"6\nt.key\n{KEY_PWD}\n\n" + f"3\n{src}\n{src}.cc\n{USER_PWD}\n\nq\n") + r = _run_tui(seq, tui_dir) + assert os.path.exists(src + ".cc"), r.stdout + + seq2 = (f"6\nt.key\n{KEY_PWD}\n\n" + f"4\n{src}.cc\n{src}.out\n{USER_PWD}\n\nq\n") + r2 = _run_tui(seq2, tui_dir) + assert os.path.exists(src + ".out"), r2.stdout + assert open(src + ".out", encoding="utf-8").read() == "TUI file payload" diff --git a/chaoscrypt/tui.py b/chaoscrypt/tui.py new file mode 100644 index 0000000..b3e5396 --- /dev/null +++ b/chaoscrypt/tui.py @@ -0,0 +1,473 @@ +""" +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 +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) -> None: + self.lang = lang if lang in LANG_NAMES else DEFAULT_LANG + self.key_file = key_file + self.cc = ChaosCrypt() + 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')}") + + 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"), + ("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")), + ] + 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_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 ("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()) diff --git a/docs/API.md b/docs/API.md new file mode 100644 index 0000000..662104b --- /dev/null +++ b/docs/API.md @@ -0,0 +1,463 @@ +# API Reference + +Complete reference for the `chaoscrypt` Python API. + +```python +from chaoscrypt import ChaosCrypt # high-level facade +from chaoscrypt import ChaosCryptCore # raw algorithm +from chaoscrypt import ChaosCryptError # base error class +``` + +--- + +## Package contents + +| Name | Kind | Description | +|---|---|---| +| `ChaosCrypt` | class | Key file management plus encryption helpers | +| `ChaosCryptCore` | class | The algorithm, with no file handling | +| `ChaosCryptError` | exception | Base class for every error raised | +| `encrypt` | function | One-shot encrypt using a key file | +| `decrypt` | function | One-shot decrypt using a key file | +| `create_key` | function | One-shot key file generation | +| `DEFAULT_KEY_FILE` | constant | `"encryption.key"` | +| `KEYFILE_VERSION` | constant | On-disk key file format version (`1`) | +| `__version__` | constant | Library version string | +| `__license__` | constant | `"MIT"` | + +--- + +## `class ChaosCrypt` + +The facade most callers should use. Wraps key file handling around +`ChaosCryptCore`. + +### Constructor + +```python +ChaosCrypt( + key_file: str | None = None, + key_password: str | None = None, + *, + auto_load: bool = False, + default_key_file: str = "encryption.key", +) +``` + +| Parameter | Type | Default | Description | +|---|---|---|---| +| `key_file` | `str \| None` | `None` | Path to a key file | +| `key_password` | `str \| None` | `None` | Password protecting that key file | +| `auto_load` | `bool` | `False` | Load the key file during construction | +| `default_key_file` | `str` | `"encryption.key"` | File name used when `key_file` is omitted | + +When `auto_load=True` and the file cannot be loaded, the corresponding +exception is raised from the constructor. + +```python +cc = ChaosCrypt("my.key", "key-password", auto_load=True) +``` + +### Properties + +#### `loaded -> bool` + +Whether usable key material is currently held in memory. + +```python +cc = ChaosCrypt() +assert cc.loaded is False +cc.create_key("pwd", "my.key") +assert cc.loaded is True +``` + +#### `is_loaded() -> bool` + +Method form of the same check, for call sites that read better that way. + +### Key management + +#### `create_key(key_password, key_file=None, *, overwrite=False) -> str` + +Generate a fresh key file. + +| Parameter | Type | Default | Description | +|---|---|---|---| +| `key_password` | `str` | required | Password that will protect the file | +| `key_file` | `str \| None` | `None` | Destination; defaults to the configured name | +| `overwrite` | `bool` | `False` | Replace an existing file rather than refusing | + +**Returns** the path written. + +**Raises** `ChaosCrypt_ERR_EmptyPassword_E006` for an empty password, or +`ChaosCrypt_ERR_KeyFileExists_E005` if the file exists and `overwrite` is +false. + +```python +cc = ChaosCrypt() +cc.create_key("strong-password", "my.key") +cc.create_key("strong-password", "my.key", overwrite=True) # replace +``` + +Aliases `generate_keys` and `create_key_file` are provided for readability. + +#### `load(key_file=None, key_password=None) -> ChaosCrypt` + +Load a key file from disk. Falls back to the instance attributes, then to the +default file name. Returns `self`, so calls can be chained. + +**Raises** `ChaosCrypt_ERR_KeyFileNotFound_E001`, +`ChaosCrypt_ERR_EmptyPassword_E006`, `ChaosCrypt_ERR_KeyPasswordIncorrect_E003`, +or `ChaosCrypt_ERR_KeyFileCorrupted_E002`. + +```python +cc = ChaosCrypt().load("my.key", "key-password") +``` + +#### `load_from_text(key_text, key_password) -> ChaosCrypt` + +Load key material directly from a key file's contents, without touching disk. +Useful when the key is stored in a password manager or retrieved from a vault. + +```python +text = vault.read("chaoscrypt-key") +cc = ChaosCrypt().load_from_text(text, "key-password") +``` + +#### `export_key_text(key_password) -> str` + +Generate key material and return it as text, writing nothing to disk. The +instance becomes loaded and immediately usable. + +```python +cc = ChaosCrypt() +text = cc.export_key_text("key-password") +vault.write("chaoscrypt-key", text) +token = cc.encrypt("data", "encryption-password") # usable right away +``` + +#### `change_key_password(old_password, new_password, key_file=None) -> str` + +Re-wrap an existing key file under a new password. The key material is +unchanged, so previously encrypted data remains readable. + +**Raises** `ChaosCrypt_ERR_EmptyPassword_E006` if the new password is empty, +or `ChaosCrypt_ERR_KeyFileNotFound_E001` / `ChaosCrypt_ERR_KeyPasswordIncorrect_E003` +if the old password does not unlock the file. + +```python +cc.change_key_password("old-password", "new-password", "my.key") +``` + +#### `info() -> dict` + +Return a summary of the loaded key material. + +```python +{ + "key_file": "my.key", + "version": 1, + "upper_mapping": "QWERTYUIOPASDFGHJKLZXCVBNM", + "lower_mapping": "qwertyuiopasdfghjklzxcvbnm", + "digit_mapping": {...}, + "equal_mapping": {...}, + "flip_pattern": [1, 0, 1, 0, 0, 1, 0, 0, 1, 0], + "long_key_length": 4096, + "short_key_length": 512, + "loaded": True, +} +``` + +The substitution tables describe the structure of your key file. Treat the +result as sensitive. + +**Raises** `ChaosCrypt_ERR_KeyNotLoaded_E004` if nothing is loaded. + +### Encryption + +#### `encrypt(plaintext, password) -> str` + +Encrypt a string, returning a hexadecimal ciphertext. + +```python +token = cc.encrypt("hello world", "encryption-password") +``` + +**Raises** `ChaosCrypt_ERR_KeyNotLoaded_E004`, +`ChaosCrypt_ERR_EmptyPassword_E006`, or `ChaosCrypt_ERR_EmptyPlaintext_E008`. + +#### `decrypt(ciphertext, password) -> str` + +Decrypt a hexadecimal ciphertext back into a string. + +```python +plain = cc.decrypt(token, "encryption-password") +``` + +**Raises** `ChaosCrypt_ERR_MalformedCiphertext_E010` if the input is not +valid hexadecimal, or `ChaosCrypt_ERR_DecryptionFailed_E011` if the password +is wrong, the key file does not match, or the ciphertext was altered. + +#### `encrypt_bytes(data, password) -> str` + +Encrypt arbitrary binary data. Returns a hexadecimal ciphertext. + +```python +raw = open("archive.zip", "rb").read() +token = cc.encrypt_bytes(raw, "encryption-password") +``` + +#### `decrypt_bytes(ciphertext, password) -> bytes` + +Decrypt back into the original binary data. + +```python +restored = cc.decrypt_bytes(token, "encryption-password") +open("archive.restored.zip", "wb").write(restored) +``` + +### File helpers + +#### `encrypt_file(src, password, dst=None) -> str` + +Encrypt a file on disk, writing UTF-8 hexadecimal ciphertext. When `dst` is +omitted, the output path is `src + ".cc"`. Returns the output path. + +**Raises** `ChaosCrypt_ERR_FileReadFailed_E014` or +`ChaosCrypt_ERR_FileWriteFailed_E015`. + +#### `decrypt_file(src, password, dst=None) -> str` + +Decrypt a `.cc` ciphertext file, restoring the original bytes. When `dst` is +omitted, a trailing `.cc` is stripped, or `.out` is appended. Returns the +output path. + +```python +cc.encrypt_file("report.pdf", "encryption-password") +cc.decrypt_file("report.pdf.cc", "encryption-password") +``` + +--- + +## `class ChaosCryptCore` + +The algorithm itself, with no file handling and no user interaction. Use it +when you manage key material yourself — for example by loading it from a +database or a secrets service. + +```python +from chaoscrypt import ChaosCryptCore + +core = ChaosCryptCore() +core.generate_keymaterial() # random key material +token = core.encrypt_text("hello", "password") +assert core.decrypt_text(token, "password") == "hello" +``` + +### Key material methods + +| Method | Description | +|---|---| +| `generate_keymaterial() -> dict` | Generate a complete random key set; leaves the instance loaded | +| `serialize_keys(key_password, save_path) -> str` | Generate and write a key file | +| `load_keys(key_file, key_password) -> None` | Load a key file from disk | +| `load_keys_from_text(text, key_password) -> None` | Load from key file contents | + +### Encryption methods + +| Method | Description | +|---|---| +| `encrypt_text(plaintext, password) -> str` | Encrypt a string to hexadecimal | +| `decrypt_text(ciphertext, password) -> str` | Decrypt to a string | +| `encrypt_bytes(data, password) -> str` | Encrypt binary data | +| `decrypt_bytes(ciphertext, password) -> bytes` | Decrypt to binary data | + +### Attributes + +Set by `generate_keymaterial()` or one of the `load_keys*` methods: + +| Attribute | Type | Description | +|---|---|---| +| `keys_loaded` | `bool` | Whether key material is present | +| `upper_mapping` | `str` | Bijection over `A–Z`, 26 characters | +| `lower_mapping` | `str` | Bijection over `a–z`, 26 characters | +| `digit_mapping` | `dict` | Digits `0–9` to distinct alphanumerics | +| `equal_mapping` | `dict` | Padding counts `0–3` to distinct characters | +| `flip_pattern` | `list[int]` | Ten bits controlling case flipping | +| `long_key` | `str` | 4096 hexadecimal nibbles | +| `short_key` | `str` | 512 hexadecimal nibbles | + +Attributes prefixed with an underscore are internal and not covered by the +compatibility guarantee. + +--- + +## Error hierarchy + +Every error is a subclass of `ChaosCryptError`, so a single `except` clause +catches everything: + +```python +from chaoscrypt import ChaosCryptError + +try: + cc.decrypt(token, "password") +except ChaosCryptError as e: + print(e.message) # ChaosCrypt_ERR_DecryptionFailed_E011 + print(e.code) # E011 + print(e.detail) # DecryptionFailed +``` + +| Code | Class | Raised when | +|---|---|---| +| `E001` | `ChaosCrypt_ERR_KeyFileNotFound_E001` | The key file does not exist | +| `E002` | `ChaosCrypt_ERR_KeyFileCorrupted_E002` | The key file cannot be parsed | +| `E003` | `ChaosCrypt_ERR_KeyPasswordIncorrect_E003` | Wrong key file password | +| `E004` | `ChaosCrypt_ERR_KeyNotLoaded_E004` | Operation needs a key, none loaded | +| `E005` | `ChaosCrypt_ERR_KeyFileExists_E005` | File exists and overwrite not permitted | +| `E006` | `ChaosCrypt_ERR_EmptyPassword_E006` | A required password was missing | +| `E007` | `ChaosCrypt_ERR_PasswordMismatch_E007` | Two password entries differed | +| `E008` | `ChaosCrypt_ERR_EmptyPlaintext_E008` | The plaintext was empty | +| `E009` | `ChaosCrypt_ERR_EmptyCiphertext_E009` | The ciphertext was empty | +| `E010` | `ChaosCrypt_ERR_MalformedCiphertext_E010` | Not valid hexadecimal, or odd length | +| `E011` | `ChaosCrypt_ERR_DecryptionFailed_E011` | Decryption produced invalid data | +| `E012` | `ChaosCrypt_ERR_EncodingFailed_E012` | Base64 or UTF-8 conversion failed | +| `E013` | `ChaosCrypt_ERR_InvalidArgument_E013` | An argument had an invalid value | +| `E014` | `ChaosCrypt_ERR_FileReadFailed_E014` | Reading a file failed | +| `E015` | `ChaosCrypt_ERR_FileWriteFailed_E015` | Writing a file failed | +| `E016` | `ChaosCrypt_ERR_UnsupportedKeyVersion_E016` | Key file version not supported | + +Codes are stable and safe to branch on. The human-readable portion of the +message may be reworded between minor releases. + +### Custom details + +Each error accepts an optional `detail` and `code`, which is useful for +adding context such as a file path: + +```python +from chaoscrypt.errors import ChaosCrypt_ERR_KeyFileNotFound_E001 + +raise ChaosCrypt_ERR_KeyFileNotFound_E001( + detail="KeyFileNotFound:/etc/keys/prod.key", code="E001" +) +``` + +--- + +## Module-level functions + +Convenience wrappers for scripts that perform a single operation. + +### `encrypt(plaintext, password, key_file="encryption.key", key_password=None) -> str` + +Load a key file and encrypt in one call. When `key_password` is omitted it +falls back to `password`, which suits setups where one secret guards both +layers. + +```python +import chaoscrypt + +token = chaoscrypt.encrypt("data", "user-pwd", "my.key", "key-pwd") +``` + +### `decrypt(ciphertext, password, key_file="encryption.key", key_password=None) -> str` + +The inverse of the above. + +```python +plain = chaoscrypt.decrypt(token, "user-pwd", "my.key", "key-pwd") +``` + +### `create_key(key_password, key_file="encryption.key", *, overwrite=False) -> str` + +Generate a key file in one call. Returns the path written. + +```python +chaoscrypt.create_key("key-pwd", "my.key") +``` + +--- + +## Complete example + +```python +"""Encrypt a config file, then restore it.""" + +from chaoscrypt import ChaosCrypt, ChaosCryptError + +KEY_FILE = "secrets.key" +KEY_PASSWORD = "key-file-password" +DATA_PASSWORD = "encryption-password" + + +def main() -> None: + cc = ChaosCrypt() + + # Reuse an existing key file, or create one on first run. + try: + cc.load(KEY_FILE, KEY_PASSWORD) + except ChaosCryptError: + cc.create_key(KEY_PASSWORD, KEY_FILE) + + # Text round trip. + token = cc.encrypt("API_KEY=abc123", DATA_PASSWORD) + print(f"Ciphertext: {token}") + print(f"Restored: {cc.decrypt(token, DATA_PASSWORD)}") + + # File round trip. + cc.encrypt_file("config.json", DATA_PASSWORD) + cc.decrypt_file("config.json.cc", DATA_PASSWORD, "config.restored.json") + + # A wrong password is reported clearly. + try: + cc.decrypt(token, "not-the-password") + except ChaosCryptError as e: + print(f"Rejected as expected: {e} (code {e.code})") + + +if __name__ == "__main__": + main() +``` + +--- + +## Thread safety + +`ChaosCrypt` and `ChaosCryptCore` instances are **not** thread-safe. Key +material is mutable state on the instance, and loading a key while an +encryption is in progress is a data race. + +Either use one instance per thread, or create the instance once and guard it +with a lock: + +```python +import threading +from chaoscrypt import ChaosCrypt + +cc = ChaosCrypt().load("my.key", "key-password") +lock = threading.Lock() + + +def encrypt_safely(text: str, password: str) -> str: + with lock: + return cc.encrypt(text, password) +``` + +The module-level functions create a fresh instance on each call, so they are +safe to use concurrently without a lock — at the cost of reloading the key +file each time. + +--- + +## Compatibility guarantee + +Within a major version: + +- the public API described here will not change incompatibly; +- error codes will not be renumbered; +- the key file format will not change; +- ciphertexts produced by any earlier release will continue to decrypt. + +The underscore-prefixed members of `ChaosCryptCore` are internal and may +change without notice. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md new file mode 100644 index 0000000..5ea32dd --- /dev/null +++ b/docs/ARCHITECTURE.md @@ -0,0 +1,386 @@ +# Architecture + +Internal design of the ChaosCrypt package: how the modules fit together, what +each one is responsible for, and how data flows through the algorithm. + +--- + +## Module map + +``` +chaoscrypt/ +├── __init__.py Public API, the ChaosCrypt facade, module-level helpers +├── _core.py The algorithm (ChaosCryptCore) +├── errors.py The unified error hierarchy +├── cli.py Argument-driven command line interface +├── tui.py Interactive bilingual interface +├── i18n.py UI strings for the TUI +├── py.typed PEP 561 marker +├── tests/ Test suite +├── examples/ Runnable examples +└── legacy/ The original single-file implementation +``` + +### Dependency graph + +``` + __init__.py + / \ + errors.py _core.py + \ / + \ / + \ / + cli.py tui.py + \ | + \ | + i18n.py +``` + +Arrows point from user to dependency. Two properties follow from this shape: + +- **`errors.py` and `_core.py` are leaves.** They import nothing from the rest + of the package, so they can be tested standalone. +- **`tui.py` and `i18n.py` are optional.** A library user importing + `chaoscrypt` never loads them, so the TUI costs nothing when unused. + +--- + +## Module responsibilities + +### `errors.py` + +Defines `ChaosCryptError` and its sixteen subclasses. Each subclass carries a +class-level `CODE` and `DETAIL`, and instances render as +`ChaosCrypt_ERR__`. + +The hierarchy exists so that callers can catch a single type and still branch +on a stable code, rather than matching on message text. + +### `_core.py` + +The algorithm. `ChaosCryptCore` owns: + +- random key material generation; +- key file serialisation and parsing; +- the encryption and decryption pipelines. + +It performs **no file I/O beyond reading and writing the key file it is given**, +and no user interaction at all. Every failure raises a `ChaosCryptError` +subclass. + +This module is a behaviour-preserving port of the original implementation. +The compatibility contract it upholds is described under +[Compatibility](#compatibility-invariants) below. + +### `__init__.py` + +Two jobs: + +1. **Public API surface.** Re-exports the classes, errors and constants that + make up the supported interface, together with `__version__` and + `__license__`. +2. **The `ChaosCrypt` facade.** Wraps `ChaosCryptCore` with key file + management, binary helpers and file-level convenience methods. + +The split lets callers choose their level of control: `ChaosCrypt` for +everyday work, `ChaosCryptCore` when key material is managed elsewhere. + +### `cli.py` + +Argument parsing and command dispatch. Contains no cryptographic logic — it +resolves passwords, reads input, calls the facade, and formats output. + +The invocation contract lives in `main()`: + +```python +def main(argv=None) -> int: + raw = sys.argv[1:] if argv is None else argv + if not raw: # no arguments -> interactive + return run_tui() + ... # arguments -> scriptable +``` + +Dispatch is a plain `if` chain rather than a dynamic registry, so the control +flow is readable at a glance. + +### `tui.py` + +The interactive interface. Menu-driven, dependency-free, and bilingual. + +Input is read through three helpers with defined fallback behaviour: + +| Helper | Behaviour | +|---|---| +| `_ask()` | Prompt with optional default; raises `_Abort` on EOF or Ctrl-C | +| `_ask_secret()` | `getpass` on a TTY, plain `input` when piped | +| `_ask_yes_no()` | Confirmation prompt | + +The `_Abort` exception is the mechanism by which Ctrl-C or EOF at any prompt +returns control to the main menu instead of tearing down the process. + +### `i18n.py` + +A flat dictionary of UI strings keyed by name and language code, plus a +lookup function `t(key, lang)`. Every string is present in both English and +Chinese; a test enforces this. + +English is the default. The TUI can switch language at runtime without +restarting. + +--- + +## Data flow: encryption + +Each stage is a bijection on its input domain, which is what makes the +composition invertible. + +``` +plaintext (str) + │ + │ utf-8 encode arbitrary bytes + ▼ +bytes + │ + │ Base64 (RFC 4648) printable ASCII, A-Z a-z 0-9 + / = + ▼ +Base64 string + │ + │ character remap '+'→'.', '/'→"'", '=' records count + ▼ +remapped string + │ + │ substitution (encrypt_map) two independent 26! bijections + ▼ +substituted string + │ + │ conditional case flip (flip_pattern) 10-bit pattern, non-linear + ▼ +flipped string + │ + │ reverse destroys locality + ▼ +reversed string ── append "|" + encoded padding count ──► + │ + │ XOR with K_long (hex output) 4096-nibble keystream + ▼ +intermediate hex ── append "|" + encoded length ──► + │ + │ XOR with DeriveKey(password, K_short, n) password-derived keystream + ▼ +ciphertext (hexadecimal string) +``` + +The two `|` separators carry metadata between stages. They never appear in +the final output, because the XOR stages fold them into the keystream. + +## Data flow: decryption + +The exact inverse, applied in reverse order: + +``` +ciphertext + │ XOR with derived keystream + ▼ +length marker recovered ──► inner hex + │ XOR with K_long + ▼ +padding marker recovered ──► reversed string + │ reverse + ▼ + │ conditional case flip (same pattern) + ▼ + │ inverse substitution (decrypt_map) + ▼ + │ undo character remap + ▼ + │ Base64 decode + ▼ + │ utf-8 decode + ▼ +plaintext +``` + +--- + +## Key derivation + +`DeriveKey(K_user, K_short, n)` produces a keystream of exactly `n` printable +characters: + +``` +K_user ──┐ + ├──► interleave ──► bit ops ──► group permute ──► reverse ──► expand ──► keystream +K_short ─┘ +``` + +The pipeline is deterministic and length-extensible. Two consequences matter: + +1. **Message length is a derivation parameter.** Two messages of different + lengths produce unrelated keystreams, so recovering one does not help with + another. +2. **The transformation is not invertible.** Recovering a keystream does not + reveal `K_user` or `K_short`. + +Together these mean a known-plaintext attack yields nothing reusable, which is +analysed in [SECURITY.md §6.2](../SECURITY.md). + +--- + +## Key file format + +A key file is a single line of hexadecimal text. + +``` +key file (hex text) + │ + │ XOR with repeated key file password + ▼ +obfuscated payload + │ + │ Base64 decode → reverse → shift by -1 → Base64 decode + ▼ +JSON +``` + +The JSON contains: + +```json +{ + "upper_mapping": "26 characters", + "lower_mapping": "26 characters", + "digit_mapping": {"0": "X", "...": "..."}, + "equal_mapping": {"0": "X", "1": "Y", "2": "Z", "3": "W"}, + "flip_pattern": [1, 0, 1, 0, 0, 1, 0, 0, 1, 0], + "long_key": "4096 hex nibbles", + "short_key": "512 hex nibbles", + "generated_at": "ISO 8601 timestamp" +} +``` + +Confidentiality comes from the password-derived XOR, not from the Base64 +layers, which are a transport encoding. + +### Failure classification + +Because a wrong password and a damaged file both produce unparseable output, +the loader distinguishes them explicitly: + +| Condition | Result | +|---|---| +| Not valid hexadecimal | `E002` corrupted file | +| Empty contents | `E002` corrupted file | +| Parses, but structure is invalid | `E003` wrong password | +| Decodes, but required fields missing | `E002` corrupted file | + +The structural validation step is what separates "you typed the wrong +password" from "this file is damaged", which is the difference between a +useful error message and a confusing one. + +--- + +## Error design + +Every error class follows the same shape: + +```python +class ChaosCryptError(Exception): + CODE = "E000" + DETAIL = "UnknownError" + + def __init__(self, detail=None, code=None): + self.detail = detail or self.DETAIL + self.code = code or self.CODE + self.message = f"ChaosCrypt_ERR_{self.detail}_{self.code}" + super().__init__(self.message) +``` + +Three attributes serve three audiences: + +| Attribute | Audience | Stability | +|---|---|---| +| `code` | Programs | Stable across releases | +| `detail` | Logs and diagnostics | Stable in meaning | +| `message` | Humans | Wording may change | + +`code` is the contract. Branch on it; do not parse `message`. + +--- + +## Compatibility invariants + +The following are guaranteed within a major version, and are enforced by the +test suite rather than merely documented: + +1. **Algorithm equivalence.** The encryption pipeline matches the original + implementation bit for bit. A reference-vector test pins the output for + fixed key material, so any accidental change is caught immediately. +2. **Key file format.** The on-disk format is unchanged, and the default file + name remains `encryption.key`. +3. **Bidirectional interoperability.** Ciphertext and key files move freely + between this library and the original script, in both directions. Dedicated + tests load `legacy/chaoscrypt_legacy.py` and exercise the real code path. +4. **Error codes.** Codes are never renumbered. + +The `legacy/` directory exists to make invariant 3 testable against the actual +original implementation rather than a reimplementation of it. + +--- + +## Design decisions + +**Why two classes rather than one.** `ChaosCryptCore` has no opinion about +where key material comes from. `ChaosCrypt` assumes it comes from a file. Users +who store keys in a database or a secrets manager want the first; users +protecting their own files want the second. Neither has to compromise. + +**Why the TUI is in its own module.** Importing `chaoscrypt` should be cheap +and should not pull in terminal handling. The TUI is imported only when +actually launched. + +**Why `_core.py` is underscore-prefixed.** It signals that the internals of +the algorithm are not part of the stable contract, while `ChaosCryptCore` +itself is public and supported. The distinction is between the class and its +underscore-prefixed members. + +**Why errors carry codes as well as messages.** Human-readable messages get +improved, translated, or reworded. Programs need something that does not +shift underneath them. Separating the two means both can evolve safely. + +**Why validation happens before processing.** A malformed ciphertext is +rejected before any decryption work begins. Without this, garbage input would +produce garbage output that is indistinguishable from success — a failure mode +that is easy to miss precisely because it does not raise. + +--- + +## Testing strategy + +| Layer | Approach | +|---|---| +| Algorithm | Round-trip across text, binary and edge cases; reference vectors pin output | +| Compatibility | Load the legacy implementation and exchange data in both directions | +| Errors | Assert on codes, not messages; verify codes are unique | +| CLI | Subprocess invocation, checking exit codes and JSON payloads | +| TUI | Piped key sequences, checking rendered output | +| i18n | Verify every string exists in both languages | + +TUI tests work because the interface degrades to plain `input` when stdin is +not a TTY. That fallback is required for automation anyway, so it serves both +purposes. + +--- + +## Performance notes + +- **Encryption is linear in message length.** The dominant cost is the two + XOR passes, giving O(n) time and O(n) memory. +- **Longer messages are not disproportionately slower**, because the long key + is cycled rather than stretched — `_get_dynamic_key` repeats `K_long` to + cover the message rather than generating fresh material. +- **The short key covers 512 nibbles**, so key derivation work is bounded and + independent of message size. +- **Base64 introduces a constant 4/3 expansion**, and the hexadecimal encoding + a further 2×. A 1 MB file therefore yields roughly 2.7 MB of ciphertext. + +None of these are bottlenecks in the intended use cases: personal files, +notes, and document-sized payloads. diff --git a/docs/BUILDING.md b/docs/BUILDING.md new file mode 100644 index 0000000..9a3f4b2 --- /dev/null +++ b/docs/BUILDING.md @@ -0,0 +1,356 @@ +# Building and Releasing + +How to build, test, and publish ChaosCrypt. + +--- + +## Requirements + +| Tool | Version | Purpose | +|---|---|---| +| Python | 3.8+ | Runtime and build | +| `build` | 1.0+ | Building distributions | +| `twine` | 4.0+ | Validating and uploading | +| `pytest` | 7.0+ | Running the test suite | + +Install the development dependencies: + +```bash +pip install -e ".[dev]" +``` + +--- + +## Development setup + +```bash +git clone https://git.dvscloud.net/dvs/ChaosCrypt +cd ChaosCrypt +pip install -e ".[dev]" +``` + +An editable install means changes to the source take effect immediately, +without reinstalling. + +--- + +## Running the tests + +```bash +pytest # everything +pytest chaoscrypt/tests/test_chaoscrypt.py # one module +pytest -k roundtrip # by name +pytest -x # stop at first failure +pytest -v # verbose +``` + +With coverage: + +```bash +pytest --cov=chaoscrypt --cov-report=term-missing +``` + +### Test modules + +| Module | Covers | +|---|---| +| `test_chaoscrypt.py` | Round-trips, binary safety, key management, errors, CLI, i18n | +| `test_tui.py` | Interactive interface, driven by piped key sequences | +| `test_legacy_interop.py` | Bidirectional compatibility with the original implementation | + +The TUI tests work because the interface falls back from `getpass` to plain +`input` when stdin is not a terminal. That fallback exists for automation, so +it serves both purposes. + +### Compatibility tests + +`test_legacy_interop.py` imports `chaoscrypt/legacy/chaoscrypt_legacy.py` +directly and exchanges data in both directions: + +```bash +pytest chaoscrypt/tests/test_legacy_interop.py -v +``` + +These tests are the enforcement mechanism for the claim that the algorithm +was ported without any behavioural change. If they fail, the compatibility +promise is broken. + +--- + +## Building distributions + +```bash +python -m build +``` + +This produces two artefacts in `dist/`: + +| Artefact | Contents | +|---|---| +| `chaoscrypt-2.1.6.tar.gz` | Source distribution — everything needed to rebuild | +| `chaoscrypt-2.1.6-py3-none-any.whl` | Wheel — the installed package | + +### What the wheel contains + +Only the importable package: + +``` +chaoscrypt/__init__.py +chaoscrypt/_core.py +chaoscrypt/cli.py +chaoscrypt/tui.py +chaoscrypt/errors.py +chaoscrypt/i18n.py +chaoscrypt/__main__.py +chaoscrypt/py.typed +``` + +`tests/`, `examples/` and `legacy/` sit alongside the package in the source +tree but are excluded from the wheel by the explicit `packages` declaration in +`pyproject.toml`. They ship in the source distribution, because the tests are +useful to anyone building from source. + +### Verifying the artefacts + +```bash +twine check dist/* +``` + +Both files should report `PASSED`. + +Inspect the wheel contents: + +```bash +python -m zipfile -l dist/chaoscrypt-2.1.6-py3-none-any.whl +``` + +--- + +## Testing the build in isolation + +Before publishing, verify the wheel installs and works in a clean environment +with no development dependencies present: + +```bash +# Create a throwaway environment. +python -m venv /tmp/verify +/tmp/verify/bin/pip install dist/chaoscrypt-2.1.6-py3-none-any.whl + +# No third-party dependencies should appear. +/tmp/verify/bin/pip list + +# Exercise the command line. +cd /tmp +/tmp/verify/bin/chaoscrypt --version +/tmp/verify/bin/chaoscrypt keygen -k test.key -P keypass +/tmp/verify/bin/chaoscrypt encrypt "hello" -p userpass -k test.key -P keypass + +# Exercise the API. +/tmp/verify/bin/python -c " +from chaoscrypt import ChaosCrypt +cc = ChaosCrypt('test.key', 'keypass', auto_load=True) +token = cc.encrypt('verify', 'userpass') +assert cc.decrypt(token, 'userpass') == 'verify' +print('clean install verified') +" +``` + +On Windows, use `\tmp\verify\Scripts\` in place of `/tmp/verify/bin/`. + +--- + +## Releasing + +### 1. Update the version + +The version appears in two places and both must agree: + +- `pyproject.toml` — `version = "2.1.6"` +- `chaoscrypt/__init__.py` — `__version__ = "2.1.6"` + +Update the changelog with a new dated section, then verify consistency: + +```bash +python -c " +import chaoscrypt, tomllib +with open('pyproject.toml', 'rb') as f: + meta = tomllib.load(f) +assert chaoscrypt.__version__ == meta['project']['version'], 'version mismatch' +print('versions consistent:', chaoscrypt.__version__) +" +``` + +### 2. Clean previous artefacts + +```bash +rm -rf dist/ build/ *.egg-info chaoscrypt/*.egg-info +``` + +### 3. Run the full test suite + +```bash +pytest +``` + +Do not release with a failing test. + +### 4. Build + +```bash +python -m build +twine check dist/* +``` + +### 5. Test the built wheel + +Run the isolated install procedure from the previous section. + +### 6. Upload + +To TestPyPI first, to confirm the metadata renders correctly: + +```bash +twine upload --repository testpypi dist/* +``` + +Then to PyPI: + +```bash +twine upload dist/* +``` + +Credentials come from `~/.pypirc`, environment variables, or an API token +entered at the prompt. Never commit them. + +### 7. Tag the release + +```bash +git tag -a v2.1.6 -m "ChaosCrypt 2.1.6" +git push origin v2.1.6 +``` + +--- + +## Versioning policy + +ChaosCrypt follows [Semantic Versioning](https://semver.org/): + +| Change | Version bump | +|---|---| +| Breaking API change | Major | +| New functionality, backward compatible | Minor | +| Bug fix or documentation | Patch | + +Additional guarantees for a given major version: + +- the public API will not change incompatibly; +- error codes will not be renumbered; +- the key file format will not change; +- ciphertexts from any earlier release will continue to decrypt. + +The algorithm is frozen. The package layout, documentation and tooling may +evolve freely within a major version. + +--- + +## Continuous integration + +A minimal GitHub Actions workflow: + +```yaml +name: test + +on: [push, pull_request] + +jobs: + test: + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [ubuntu-latest, windows-latest, macos-latest] + python-version: ["3.8", "3.11", "3.13"] + + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + - run: pip install -e ".[dev]" + - run: pytest + - run: python -m build + - run: twine check dist/* +``` + +Testing across operating systems matters here because the TUI and CLI handle +terminal behaviour, path separators and encoding differently on each. + +--- + +## Project layout + +``` +ChaosCrypt/ +├── README.md project overview +├── SECURITY.md design and threat analysis +├── CHANGELOG.md release history +├── LICENSE MIT +├── MANIFEST.in sdist contents +├── pyproject.toml build configuration +├── .gitignore +├── docs/ this directory +│ ├── README.md documentation index +│ ├── API.md Python API reference +│ ├── CLI.md command line reference +│ ├── ARCHITECTURE.md internal design +│ └── BUILDING.md this file +├── dist/ build artefacts (generated) +└── chaoscrypt/ source tree + ├── __init__.py public API and facade + ├── _core.py the algorithm + ├── cli.py command line interface + ├── tui.py interactive interface + ├── errors.py error hierarchy + ├── i18n.py UI strings + ├── __main__.py python -m entry point + ├── py.typed PEP 561 marker + ├── tests/ test suite + ├── examples/ runnable examples + └── legacy/ original implementation +``` + +--- + +## Troubleshooting + +**`error: package directory 'chaoscrypt/chaoscrypt' does not exist`** + +The `package-dir` mapping in `pyproject.toml` is wrong for this layout. The +package lives at `chaoscrypt/`, alongside `tests/` and `examples/`, so the +mapping must be: + +```toml +[tool.setuptools] +packages = ["chaoscrypt"] +package-dir = { "chaoscrypt" = "chaoscrypt" } +``` + +**The wheel contains `tests/` or `examples/`** + +The `packages` list is too broad. It should name only `chaoscrypt`, not use +automatic discovery, because discovery would find the sibling directories. + +**`ModuleNotFoundError: No module named 'chaoscrypt'` after an editable install** + +Check that the install registered the right directory: + +```bash +python -c "import chaoscrypt, os; print(os.path.dirname(chaoscrypt.__file__))" +``` + +The path should point at the repository's `chaoscrypt/` directory. + +**Tests pass locally but fail in CI** + +Most often an encoding issue. The library explicitly uses UTF-8 for text I/O, +but locale settings can still affect terminal behaviour. The TUI tests set +`PYTHONIOENCODING=utf-8` and `NO_COLOR=1` for exactly this reason. diff --git a/docs/CLI.md b/docs/CLI.md new file mode 100644 index 0000000..2fa8069 --- /dev/null +++ b/docs/CLI.md @@ -0,0 +1,408 @@ +# Command Line Reference + +Complete reference for the `chaoscrypt` command. + +``` +chaoscrypt # no arguments -> interactive TUI +chaoscrypt [options] # with arguments -> scriptable CLI +``` + +The same behaviour is available as `python -m chaoscrypt`. + +--- + +## Global options + +These apply before the subcommand. + +| Option | Description | +|---|---| +| `-h`, `--help` | Show help and exit | +| `-V`, `--version` | Show the version and exit | +| `-j`, `--json` | Emit machine-readable JSON on stdout | +| `-q`, `--quiet` | Suppress non-essential human-readable output | + +```bash +chaoscrypt --version +chaoscrypt --json info -k my.key -P keypass +``` + +**Exit codes** + +| Code | Meaning | +|---|---| +| `0` | Success | +| `1` | Runtime error — a `ChaosCryptError` was raised | +| `2` | Usage error — argument parsing failed | + +--- + +## Password options + +Every command that needs a password accepts three forms of each. The pattern +repeats for the **encryption password** and the **key file password**: + +| Encryption password | Key file password | Source | +|---|---|---| +| `-p`, `--pwd PWD` | `-P`, `--key-pwd PWD` | Inline on the command line | +| `--pwd-env VAR` | `--key-pwd-env VAR` | Environment variable `VAR` | +| `--pwd-file PATH` | `--key-pwd-file PATH` | Last non-empty line of `PATH` | + +Precedence is inline, then environment, then file. The password file form +reads the **last non-empty line**, so a trailing newline is harmless: + +```bash +echo 'correct horse battery staple' > ~/.cc-encryption-pwd +chaoscrypt encrypt "data" --pwd-file ~/.cc-encryption-pwd -k my.key -P keypass +``` + +> **Distinguish the two passwords.** `-p`/`--pwd` is the *encryption +> password* protecting your data. `-P`/`--key-pwd` is the *key file password* +> that unlocks the key file. They are independent, and you need both. + +Inline passwords appear in shell history. Prefer an environment variable or a +password file, particularly on shared systems. + +--- + +## `chaoscrypt keygen` + +Generate a new key file. + +``` +chaoscrypt keygen [-k PATH] [-f] [-P PWD | --key-pwd-env VAR | --key-pwd-file PATH] +``` + +| Option | Description | +|---|---| +| `-k`, `--key-file PATH` | Output path (default `encryption.key`) | +| `-f`, `--force` | Overwrite an existing file | + +```bash +chaoscrypt keygen -k my.key -P "key-file-password" +chaoscrypt keygen -k my.key --key-pwd-env CC_KEY_PWD -f +``` + +Output: + +``` +Key file created: /home/user/my.key +``` + +With `--json`: + +```json +{ + "ok": true, + "key_file": "/home/user/my.key" +} +``` + +--- + +## `chaoscrypt encrypt` + +Encrypt a string into a hexadecimal ciphertext. + +``` +chaoscrypt encrypt [TEXT] [-i PATH] [-o PATH] [-k PATH] + [-p PWD | --pwd-env VAR | --pwd-file PATH] + [-P PWD | --key-pwd-env VAR | --key-pwd-file PATH] +``` + +| Argument | Description | +|---|---| +| `TEXT` | Plaintext. Use `-` or omit to read from stdin | +| `-i`, `--in PATH` | Read plaintext from a file | +| `-o`, `--out PATH` | Write ciphertext to a file instead of stdout | +| `-k`, `--key-file PATH` | Key file (default `encryption.key`) | + +```bash +# Direct +chaoscrypt encrypt "hello world" -p mypass -k my.key -P keypass + +# From a file +chaoscrypt encrypt -i note.txt -p mypass -k my.key -P keypass + +# Into a file +chaoscrypt encrypt "hello" -o out.cc -p mypass -k my.key -P keypass + +# From stdin +echo "hello" | chaoscrypt encrypt - -p mypass -k my.key -P keypass +``` + +--- + +## `chaoscrypt decrypt` + +Decrypt a hexadecimal ciphertext back into text. + +``` +chaoscrypt decrypt [TEXT] [-i PATH] [-o PATH] [-k PATH] + [-p PWD | --pwd-env VAR | --pwd-file PATH] + [-P PWD | --key-pwd-env VAR | --key-pwd-file PATH] +``` + +Options are identical to `encrypt`. + +```bash +chaoscrypt decrypt "516a0410..." -p mypass -k my.key -P keypass +chaoscrypt decrypt -i ciphertext.cc -p mypass -k my.key -P keypass +chaoscrypt decrypt - -p mypass -k my.key -P keypass < ciphertext.cc +``` + +A wrong password, a mismatched key file, or an altered ciphertext all raise +`ChaosCrypt_ERR_DecryptionFailed_E011` and exit with code `1`. + +--- + +## `chaoscrypt file` + +Encrypt and decrypt whole files. Binary-safe: the input is read as raw bytes, +so images, archives and executables are handled correctly. + +### `chaoscrypt file encrypt` + +``` +chaoscrypt file encrypt SRC [-o PATH] [-k PATH] [password options] +``` + +Writes UTF-8 hexadecimal ciphertext. Without `-o`, the output path is +`SRC.cc`. + +```bash +chaoscrypt file encrypt photo.png -p mypass -k my.key -P keypass +# -> photo.png.cc +``` + +### `chaoscrypt file decrypt` + +``` +chaoscrypt file decrypt SRC [-o PATH] [-k PATH] [password options] +``` + +Without `-o`, a trailing `.cc` is stripped. + +```bash +chaoscrypt file decrypt photo.png.cc -p mypass -k my.key -P keypass +# -> photo.png + +chaoscrypt file decrypt data.cc -o restored.bin -p mypass -k my.key -P keypass +``` + +--- + +## `chaoscrypt info` + +Show key file metadata. Substitution tables are redacted unless you ask for +them explicitly. + +``` +chaoscrypt info [-k PATH] [--show-maps] [-P PWD | --key-pwd-env VAR | --key-pwd-file PATH] +``` + +| Option | Description | +|---|---| +| `--show-maps` | Also print the substitution tables (sensitive) | + +```bash +chaoscrypt info -k my.key -P keypass +``` + +``` +============================================================== +ChaosCrypt key information +============================================================== +key_file : my.key +version : 1 +upper_mapping : +lower_mapping : +digit_mapping : +equal_mapping : +flip_pattern : [1, 0, 1, 0, 0, 1, 0, 0, 1, 0] +long_key_length : 4096 +short_key_length : 512 +loaded : True +============================================================== +``` + +The substitution tables describe the structure of your key file. Only use +`--show-maps` when you are certain the output is not being logged or +displayed publicly. + +--- + +## `chaoscrypt chpwd` + +Change the key file password. The key material is unchanged, so previously +encrypted data remains readable. + +``` +chaoscrypt chpwd [-k PATH] + [-P PWD | --key-pwd-env VAR | --key-pwd-file PATH] + [--new-pwd PWD | --new-pwd-env VAR | --new-pwd-file PATH] +``` + +```bash +chaoscrypt chpwd -k my.key -P oldpass --new-pwd newpass +chaoscrypt chpwd -k my.key -P oldpass --new-pwd-env CC_NEW_KEY_PWD +``` + +--- + +## `chaoscrypt tui` + +Launch the interactive interface. Identical to running `chaoscrypt` with no +arguments. + +```bash +chaoscrypt tui +``` + +--- + +## JSON output + +Every command supports `--json`, which prints a single JSON object on stdout +and reports errors as JSON on stderr. This is the recommended mode for +scripts and integration. + +```bash +chaoscrypt --json encrypt "data" -p pw -k my.key -P kp +``` + +```json +{ + "ok": true, + "mode": "encrypt", + "ciphertext": "516a0410415613117b10770111604074..." +} +``` + +On failure: + +```json +{ + "ok": false, + "error": "ChaosCrypt_ERR_DecryptionFailed_E011", + "code": "E011" +} +``` + +Parsing with `jq`: + +```bash +CT=$(chaoscrypt --json encrypt "data" -p pw -k my.key -P kp | jq -r .ciphertext) +chaoscrypt decrypt "$CT" -p pw -k my.key -P kp +``` + +--- + +## Pipelines + +The CLI composes cleanly with standard shell tools. `TEXT` set to `-`, or +omitted entirely, reads from stdin; the absence of `-o` writes to stdout. + +```bash +# Encrypt a tar stream without touching disk. +tar czf - ./project | chaoscrypt encrypt - -p pw -k my.key -P kp > project.tgz.cc + +# Restore it. +chaoscrypt decrypt - -p pw -k my.key -P kp < project.tgz.cc | tar xzf - -C ./restored + +# Encrypt every .txt file in a directory. +for f in *.txt; do + chaoscrypt file encrypt "$f" -p pw -k my.key -P kp +done +``` + +--- + +## Shell completion + +Bash, added to `~/.bashrc`: + +```bash +_chaoscrypt_complete() { + local commands="keygen encrypt decrypt file info chpwd tui" + COMPREPLY=( $(compgen -W "$commands" -- "${COMP_WORDS[COMP_CWORD]}") ) +} +complete -F _chaoscrypt_complete chaoscrypt +``` + +PowerShell, added to your profile: + +```powershell +Register-ArgumentCompleter -Native -CommandName chaoscrypt -ScriptBlock { + param($wordToComplete) + 'keygen','encrypt','decrypt','file','info','chpwd','tui' | + Where-Object { $_ -like "$wordToComplete*" } +} +``` + +--- + +## Examples + +### First-time setup + +```bash +chaoscrypt keygen -k ~/.chaoscrypt/prod.key --key-pwd-env CC_KEY_PWD +mkdir -p ~/.chaoscrypt +echo 'my-encryption-password' > ~/.chaoscrypt/pwd +chmod 600 ~/.chaoscrypt/pwd +``` + +### Daily use + +```bash +alias ccenc='chaoscrypt encrypt --pwd-file ~/.chaoscrypt/pwd \ + -k ~/.chaoscrypt/prod.key --key-pwd-env CC_KEY_PWD' +alias ccdec='chaoscrypt decrypt --pwd-file ~/.chaoscrypt/pwd \ + -k ~/.chaoscrypt/prod.key --key-pwd-env CC_KEY_PWD' + +ccenc "sensitive note" +echo "note" | ccenc - +``` + +### Backing up a directory + +```bash +tar czf - ./documents \ + | chaoscrypt encrypt - --pwd-file ~/.chaoscrypt/pwd \ + -k ~/.chaoscrypt/prod.key --key-pwd-env CC_KEY_PWD \ + > documents-$(date +%F).tgz.cc +``` + +### Rotating the key file password + +```bash +chaoscrypt chpwd -k ~/.chaoscrypt/prod.key \ + -P "$OLD_KEY_PWD" --new-pwd "$NEW_KEY_PWD" +``` + +--- + +## Troubleshooting + +| Symptom | Cause | Resolution | +|---|---|---| +| `ChaosCrypt_ERR_KeyFileNotFound_E001` | Wrong key file path | Check `-k` and the working directory | +| `ChaosCrypt_ERR_KeyPasswordIncorrect_E003` | Wrong key file password | Verify the `-P` value | +| `ChaosCrypt_ERR_DecryptionFailed_E011` | Wrong encryption password, mismatched key file, or altered ciphertext | Confirm `-p`, `-k` and that the ciphertext is intact | +| `ChaosCrypt_ERR_MalformedCiphertext_E010` | Ciphertext is not valid hexadecimal, or has an odd length | Check for truncation or stray whitespace | +| `ChaosCrypt_ERR_EmptyPassword_E006` | No password supplied | Provide one of the three password forms | +| `ChaosCrypt_ERR_InvalidArgument_E013` | Environment variable unset, or password file unreadable | Verify the variable is exported and the file is readable | +| Exit code `2` with usage text | Argument parsing failed | Run `chaoscrypt --help` | + +Because the CLI reports the error class in the message, you can branch on the +code rather than parsing prose: + +```bash +if ! chaoscrypt decrypt "$CT" -p pw -k my.key -P kp; then + case "$?" in + 1) echo "check your passwords and key file" ;; + 2) echo "check the command syntax" ;; + esac +fi +``` diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..2ea7722 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,34 @@ +# Documentation + +Reference material for ChaosCrypt. + +| Document | Contents | +|---|---| +| [API.md](API.md) | Complete Python API reference | +| [CLI.md](CLI.md) | Command line reference, pipelines, troubleshooting | +| [ARCHITECTURE.md](ARCHITECTURE.md) | Module map, data flow, design decisions | +| [BUILDING.md](BUILDING.md) | Building, testing and releasing | +| [../SECURITY.md](../SECURITY.md) | Design, key space, threat model, attack analysis | +| [../README.md](../README.md) | Project overview and quick start | +| [../CHANGELOG.md](../CHANGELOG.md) | Release history | + +--- + +## Where to start + +**Evaluating whether ChaosCrypt suits your use case** +Read the [Scope](../README.md#scope) section of the README, then +[SECURITY.md](../SECURITY.md) for the full analysis. + +**Using the library in Python** +[API.md](API.md) — start with the `ChaosCrypt` facade and the error table. + +**Using the command line** +[CLI.md](CLI.md) — covers every subcommand, plus pipelines and shell aliases. + +**Understanding how it works** +[ARCHITECTURE.md](ARCHITECTURE.md) for the code structure, and +[SECURITY.md §3](../SECURITY.md) for the algorithm itself. + +**Contributing or building a release** +[BUILDING.md](BUILDING.md). diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..c8f7f2c --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,116 @@ +[build-system] +requires = ["setuptools>=77", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "chaoscrypt" +version = "2.1.6" +description = "A chaos-based obfuscation cipher with a bilingual TUI, a full CLI and a clean Python API." +readme = "README.md" +requires-python = ">=3.8" +license = "MIT" +license-files = ["LICENSE"] +authors = [ + { name = "Dvs (DvsXT)", email = "dvs6666@163.com" }, +] +maintainers = [ + { name = "Dvs (DvsXT)", email = "dvs6666@163.com" }, +] +keywords = [ + "encryption", + "cipher", + "obfuscation", + "chaos", + "xor", + "keystream", + "tui", + "cli", + "education", +] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Environment :: Console", + "Intended Audience :: Developers", + "Intended Audience :: Education", + "Intended Audience :: End Users/Desktop", + "Natural Language :: Chinese (Simplified)", + "Natural Language :: English", + "Operating System :: OS Independent", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Topic :: Education", + "Topic :: Security :: Cryptography", + "Topic :: Utilities", +] + +# No third-party runtime dependencies: works immediately after `pip install`. +dependencies = [] + +[project.optional-dependencies] +dev = [ + "build>=1.0", + "twine>=4.0", + "pytest>=7.0", + "pytest-cov>=4.0", +] + +[project.urls] +Homepage = "https://git.dvscloud.net/dvs/ChaosCrypt" +Documentation = "https://git.dvscloud.net/dvs/ChaosCrypt/src/branch/main/docs" +Source = "https://git.dvscloud.net/dvs/ChaosCrypt" +Changelog = "https://git.dvscloud.net/dvs/ChaosCrypt/src/branch/main/CHANGELOG.md" +"Security Policy" = "https://git.dvscloud.net/dvs/ChaosCrypt/src/branch/main/SECURITY.md" +"Issue Tracker" = "https://git.dvscloud.net/dvs/ChaosCrypt/issues" + +[project.scripts] +chaoscrypt = "chaoscrypt.cli:cli_main" + +# --------------------------------------------------------------------------- +# Layout +# --------------------------------------------------------------------------- +# ChaosCrypt/ repository root: docs and build artefacts +# ├── README.md SECURITY.md LICENSE CHANGELOG.md +# ├── docs/ +# ├── pyproject.toml +# ├── dist/ +# └── chaoscrypt/ source tree +# ├── __init__.py the importable package +# ├── _core.py cli.py tui.py errors.py i18n.py +# ├── tests/ +# ├── examples/ +# └── legacy/ +# +# The package sits alongside tests/, examples/ and legacy/ in the same +# directory, so the distribution contents are stated explicitly. Automatic +# discovery would treat those directories as namespace packages and ship them +# in the wheel. +# --------------------------------------------------------------------------- +[tool.setuptools] +py-modules = [] +packages = ["chaoscrypt"] + +[tool.setuptools.package-data] +chaoscrypt = ["py.typed"] + +[tool.pytest.ini_options] +testpaths = ["chaoscrypt/tests"] +addopts = "-q" +filterwarnings = [ + "error::DeprecationWarning:chaoscrypt.*", +] + +[tool.coverage.run] +source = ["chaoscrypt"] + +[tool.coverage.report] +exclude_lines = [ + "pragma: no cover", + "if TYPE_CHECKING:", + "if __name__ == .__main__.:", +] diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..35a97cc --- /dev/null +++ b/setup.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python3 +""" +Compatibility shim for legacy build tooling. + +ChaosCrypt is configured entirely through ``pyproject.toml``. This file exists +only so that older tools which expect a ``setup.py`` — pip versions predating +PEP 517 support, ``python setup.py`` invocations, and some packaging scripts — +still function. + +All metadata lives in ``pyproject.toml``; nothing is declared here. The call to +``setup()`` with no arguments lets setuptools read the authoritative +configuration from the project file, so there is exactly one source of truth. + +Building is normally done with:: + + python -m build + +which produces a source distribution and a wheel in ``dist/``. +""" + +from setuptools import setup + +if __name__ == "__main__": + setup()