Compare commits
4
Commits
bad851f741
...
v4.2.6
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dd49043171 | ||
|
|
24a36d6fb4 | ||
|
|
017972d8b4 | ||
|
|
2529edac1d |
+49
-15
@@ -1,20 +1,54 @@
|
|||||||
# 运行时数据(聊天记录/账户/服务器状态)
|
# Byte-compiled / optimized / DLL files
|
||||||
data/
|
|
||||||
server_data/
|
|
||||||
ChaosCryptChat/data/
|
|
||||||
ChaosCryptChat/server_data/
|
|
||||||
|
|
||||||
# 密钥文件(严禁上传!)
|
|
||||||
*.key
|
|
||||||
|
|
||||||
# Python 缓存
|
|
||||||
__pycache__/
|
__pycache__/
|
||||||
*.pyc
|
*.py[cod]
|
||||||
|
*$py.class
|
||||||
|
|
||||||
# 媒体缓存
|
# Distribution / packaging
|
||||||
media/
|
build/
|
||||||
|
dist/
|
||||||
|
*.egg-info/
|
||||||
|
*.egg
|
||||||
|
.eggs/
|
||||||
|
wheels/
|
||||||
|
|
||||||
# 系统文件
|
# Test / coverage
|
||||||
Thumbs.db
|
.pytest_cache/
|
||||||
|
.coverage
|
||||||
|
.coverage.*
|
||||||
|
htmlcov/
|
||||||
|
.tox/
|
||||||
|
.nox/
|
||||||
|
coverage.xml
|
||||||
|
|
||||||
|
# Virtual environments
|
||||||
|
venv/
|
||||||
|
.venv/
|
||||||
|
env/
|
||||||
|
ENV/
|
||||||
|
|
||||||
|
# Editors / IDEs
|
||||||
|
.idea/
|
||||||
|
.vscode/
|
||||||
|
*.swp
|
||||||
|
*.swo
|
||||||
|
*~
|
||||||
|
|
||||||
|
# OS
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
desktop.ini
|
desktop.ini
|
||||||
|
|
||||||
|
# 🔐 密钥文件与密文 —— 绝不提交!
|
||||||
|
*.key
|
||||||
|
encryption.key
|
||||||
|
*.cc
|
||||||
|
!tests/**/*.key
|
||||||
|
!examples/**/*.key
|
||||||
|
|
||||||
|
# 密码文件
|
||||||
|
*.pwd
|
||||||
|
.pwd
|
||||||
|
|
||||||
|
# 构建产物
|
||||||
|
*.whl
|
||||||
|
*.tar.gz
|
||||||
|
|||||||
+203
@@ -0,0 +1,203 @@
|
|||||||
|
# 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/).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## [4.2.6] — 2026-09-27
|
||||||
|
|
||||||
|
Self-describing artefacts, a byte pipeline worth using, and a large performance
|
||||||
|
pass. This release changes the on-disk format incompatibly and is the first
|
||||||
|
version intended to be deployed rather than experimented with.
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- **Self-describing header on every artefact.** Each key file and ciphertext now
|
||||||
|
begins with a magic value, two fixed markers, and a complete JSON
|
||||||
|
configuration record that states how the payload was produced. A reader never
|
||||||
|
has to be told the mode, the encoding or the intermediate representation: it
|
||||||
|
reads them. See [docs/FORMAT.md](docs/FORMAT.md).
|
||||||
|
|
||||||
|
```
|
||||||
|
69CES
|
||||||
|
385aeff1f4179a744c8fb0c5ae4702d325f6230d059f4251135c2536409dee93
|
||||||
|
{"alg":"chaoscrypt","kind":"ciphertext","mode":"turbo","out":"hex",...}
|
||||||
|
2025ea4e4b4b93803f2ccadeaf318d1957ce42ff5409410f660348be96a4c0f2
|
||||||
|
<payload>
|
||||||
|
```
|
||||||
|
|
||||||
|
- **Two new error codes**, for the two ways a header can be wrong:
|
||||||
|
- `E017 MissingMagicHeader` — the input is not a CES artefact at all
|
||||||
|
- `E018 MalformedHeader` — a marker is missing, the JSON is unusable, a
|
||||||
|
required field is absent, or `kind` does not match
|
||||||
|
|
||||||
|
- **Byte pipeline for `turbo` and `raw`.** Between the XOR layers the payload is
|
||||||
|
now carried as raw bytes rather than hexadecimal text. This removes a
|
||||||
|
doubling of the payload at each layer: expansion drops from **5.33x to 2.00x**
|
||||||
|
and throughput rises by roughly **4x**. The old behaviour is still available
|
||||||
|
as `mid="hex"`.
|
||||||
|
|
||||||
|
- **Selectable output encoding** for `turbo` and `raw`: `hex` (2.00x) or
|
||||||
|
`base64` (1.33x).
|
||||||
|
|
||||||
|
- **Legacy compatibility API**, for artefacts written before the header existed:
|
||||||
|
- `wrap_legacy(text, is_key)` — synthesise a minimal header and return a
|
||||||
|
well-formed artefact
|
||||||
|
- `decrypt_legacy(text, password, is_key)` — read an artefact that may predate
|
||||||
|
the header
|
||||||
|
- `decrypt_legacy_auto(text, password)` — as above, probing whether the input
|
||||||
|
is a key file or a ciphertext
|
||||||
|
- `load_legacy_keys(text, key_password)` — load a pre-header key file
|
||||||
|
|
||||||
|
Legacy support is a *wrapper* around the ordinary path, never a lenient branch
|
||||||
|
inside it: the payload is given a header and then read normally, so the strict
|
||||||
|
path stays strict.
|
||||||
|
|
||||||
|
- **Frozen reference vectors** covering eleven cases across every mode,
|
||||||
|
encoding and intermediate representation, plus five error cases.
|
||||||
|
|
||||||
|
- **Documentation**: `docs/FORMAT.md` as the normative format specification,
|
||||||
|
`docs/benchmark.md` with measured throughput and the profiling behind it, and
|
||||||
|
a rewritten `SECURITY.md` covering the four modes.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- **Default mode is `fast`**, which is byte-for-byte compatible with the
|
||||||
|
original algorithm and roughly 30x quicker.
|
||||||
|
|
||||||
|
- **Substitution, case flipping and the printable fold** run through
|
||||||
|
`bytes.translate` over precomputed 256-entry tables.
|
||||||
|
|
||||||
|
- **XOR layers** use a single big-integer operation instead of a per-byte loop
|
||||||
|
with `%02x` formatting.
|
||||||
|
|
||||||
|
- **Keystream derivation** caches the length-independent base material, and the
|
||||||
|
expansion uses cached translation tables rather than `str.join` over a
|
||||||
|
generator.
|
||||||
|
|
||||||
|
- **`_get_dynamic_key`** repeats the long key by multiplication rather than
|
||||||
|
`key += long_key` in a loop. The loop version was quadratic: covering a
|
||||||
|
5.6 MB intermediate took 866 ms and dominated the 1 MiB timings. The same
|
||||||
|
work now takes about 3 ms, with identical output.
|
||||||
|
|
||||||
|
- **`_derive_final_key`** decodes only the prefix of the hex round trip that
|
||||||
|
the output actually consumes, rather than the whole thing.
|
||||||
|
|
||||||
|
- **The decrypt path** no longer copies or scans the full artefact: a redundant
|
||||||
|
`strip()`, a full-string `int(payload, 16)` validation, and three whole-string
|
||||||
|
slices in `strip_header` were all removed. Decryption throughput roughly
|
||||||
|
doubled at 512 KiB, from 34 MB/s to 87 MB/s.
|
||||||
|
|
||||||
|
- **Version raised to 4.2.6.**
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
1. Key material derivation is no longer quadratic. `_get_dynamic_key` was the
|
||||||
|
worst offender, and `_expand_keystream_slow` shared the pattern.
|
||||||
|
2. Two hex-intermediate pipelines were asymmetric, so a `turbo` or `raw`
|
||||||
|
artefact produced with `mid="hex"` could not be read back. Both are now
|
||||||
|
exact mirrors.
|
||||||
|
3. `change_key_password` and `export_key_text` wrote artefacts without a header,
|
||||||
|
producing files this library then refused to load.
|
||||||
|
4. The constructor accepted `encoding="base64"` while the header records
|
||||||
|
`out="base"`. Both spellings are now accepted, so a caller can read a header
|
||||||
|
and pass the value straight back in.
|
||||||
|
5. A payload that is not valid hexadecimal now reports `E010`
|
||||||
|
(MalformedCiphertext) rather than `E011` (DecryptionFailed). The distinction
|
||||||
|
matters: the first means the artefact is malformed, the second means the
|
||||||
|
password or key is wrong.
|
||||||
|
6. The TUI's encoding menu referenced a missing translation and displayed the
|
||||||
|
key name instead of the description.
|
||||||
|
|
||||||
|
### Security
|
||||||
|
|
||||||
|
- **Format break from pre-4.2.6 artefacts.** Headerless input is rejected with
|
||||||
|
`E017`; use the compatibility API to read old material. Old scripts cannot
|
||||||
|
read new artefacts. This is deliberate and documented, not an oversight.
|
||||||
|
- **`fast` is not a weaker mode**: it performs the same arithmetic and produces
|
||||||
|
the same bytes. The test suite asserts this against the frozen vectors.
|
||||||
|
- **`raw` with a hex intermediate is the weakest configuration** and is
|
||||||
|
documented as such: fewer structural layers stand between an attacker and the
|
||||||
|
substituted text.
|
||||||
|
- The header is metadata. It adds no secrecy and is not authenticated; an
|
||||||
|
application that must detect header tampering should MAC the whole artefact.
|
||||||
|
|
||||||
|
### Performance
|
||||||
|
|
||||||
|
Measured on the machine described in [docs/benchmark.md](docs/benchmark.md),
|
||||||
|
hex output, keystream cache warm.
|
||||||
|
|
||||||
|
| Mode / mid | 64 KiB | 1 MiB | 16 MiB | 128 MiB | 1024 MiB |
|
||||||
|
|---|---:|---:|---:|---:|---:|
|
||||||
|
| `raw` bt enc | 26.9 | 57.3 | 63.4 | 59.4 | 47.9 |
|
||||||
|
| `raw` bt dec | 60.6 | 61.0 | 69.0 | 64.5 | 31.7 |
|
||||||
|
| `raw` hex enc | 20.7 | 19.3 | 18.9 | 18.2 | — |
|
||||||
|
| `raw` hex dec | 20.2 | 21.8 | 22.7 | 18.0 | — |
|
||||||
|
|
||||||
|
Throughput in MB/s. It holds steady across four orders of magnitude, which is
|
||||||
|
what a linear algorithm looks like.
|
||||||
|
|
||||||
|
For scale, the original implementation managed **0.08 MB/s** — about twelve
|
||||||
|
seconds per megabyte.
|
||||||
|
|
||||||
|
### Compatibility
|
||||||
|
|
||||||
|
- `reference` and `fast` produce payloads byte-for-byte identical to the
|
||||||
|
original algorithm; only the header is new.
|
||||||
|
- `turbo` and `raw` define their own formats, and their payloads differ by
|
||||||
|
`out` and `mid`. An artefact is read with the parameters it carries, and there
|
||||||
|
is no fallback between them.
|
||||||
|
- The key file format carries a header but is otherwise unchanged.
|
||||||
|
- Artefacts written before the header existed are readable only through the
|
||||||
|
compatibility API.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## [2.1.6] — 2026-09-27
|
||||||
|
|
||||||
|
Packaging release. The algorithm is unchanged; this version restructures the
|
||||||
|
project as a distributable library.
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Bilingual interactive TUI, English and Chinese, switchable at runtime.
|
||||||
|
- Full command line interface: `keygen`, `encrypt`, `decrypt`, `file`, `info`,
|
||||||
|
`chpwd`, `tui`.
|
||||||
|
- Unified error hierarchy: sixteen named types rendering as
|
||||||
|
`ChaosCrypt_ERR_<Detail>_<Code>`.
|
||||||
|
- Binary and file support.
|
||||||
|
- Key management helpers: `change_key_password`, `export_key_text`,
|
||||||
|
`load_from_text`.
|
||||||
|
- Packaging: `pyproject.toml`, `setup.py` shim, `MANIFEST.in`, `py.typed`.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
1. The `-p` and `-P` option groups both registered `--pwd`, so the CLI could
|
||||||
|
not start at all.
|
||||||
|
2. A wrong key file password was reported as file corruption (`E002`).
|
||||||
|
3. `export_key_text` produced key material without loading it into the instance.
|
||||||
|
4. **Non-hexadecimal input was accepted as ciphertext and silently decrypted
|
||||||
|
into garbage**, making corruption indistinguishable from success.
|
||||||
|
5. The TUI failed under piped input, because `getpass` requires a TTY.
|
||||||
|
6. After generating a key file, the TUI kept looking at the default file name.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## [2.0.0] — Original release
|
||||||
|
|
||||||
|
The original single-file implementation of the ChaosCrypt cipher.
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Random system key generation.
|
||||||
|
- Password-protected key file wrapping.
|
||||||
|
- Layered encryption: Base64, substitution, conditional case flipping,
|
||||||
|
whole-message reversal, and two XOR stages.
|
||||||
|
- Interactive menu for encryption, decryption and key management.
|
||||||
|
|
||||||
|
[4.2.6]: https://git.dvscloud.net/dvs/ChaosCrypt/releases/tag/v4.2.6
|
||||||
|
[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
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -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☁️ 服务器已停止")
|
|
||||||
@@ -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 未经审计,不是标准密码学算法,可能存在未知风险。
|
||||||
|
仅限用于:混淆式加密、个人自用、研究教学。
|
||||||
|
请勿用于真实产品。因擅自用于真实产品导致的任何事故,开发者不承担责任。
|
||||||
+31
@@ -0,0 +1,31 @@
|
|||||||
|
# Files included in the source distribution.
|
||||||
|
#
|
||||||
|
# The development directories (tests/, examples/, legacy/) sit inside the
|
||||||
|
# package directory in the source tree. They are covered below so the sdist
|
||||||
|
# carries them, but they must never reach the wheel: the explicit `packages`
|
||||||
|
# list in pyproject.toml keeps them out.
|
||||||
|
|
||||||
|
include README.md
|
||||||
|
include LICENSE
|
||||||
|
include SECURITY.md
|
||||||
|
include CHANGELOG.md
|
||||||
|
include pyproject.toml
|
||||||
|
include setup.py
|
||||||
|
include .gitignore
|
||||||
|
|
||||||
|
recursive-include docs *.md
|
||||||
|
recursive-include bench *.py
|
||||||
|
|
||||||
|
# The installable package.
|
||||||
|
include chaoscrypt/*.py
|
||||||
|
include chaoscrypt/py.typed
|
||||||
|
|
||||||
|
# Development material shipped in the sdist only.
|
||||||
|
recursive-include chaoscrypt/tests *.py *.json
|
||||||
|
recursive-include chaoscrypt/examples *.py
|
||||||
|
recursive-include chaoscrypt/legacy *.py *.md
|
||||||
|
|
||||||
|
global-exclude *.py[cod]
|
||||||
|
global-exclude __pycache__/*
|
||||||
|
global-exclude .DS_Store
|
||||||
|
global-exclude *.key
|
||||||
@@ -1,536 +1,328 @@
|
|||||||
|
# ChaosCrypt
|
||||||
|
|
||||||
# 🔐 ChaosCrypt - Chaos Encryption System (v2.0)
|
**A chaos-based obfuscation cipher with a self-describing format, four
|
||||||
|
performance modes, a bilingual TUI, a full CLI, and a clean Python API.**
|
||||||
|
|
||||||
**A fully self-designed, quantum-resistant, math-attack-resistant symmetric encryption system**
|
[](https://www.python.org/)
|
||||||
|
[](LICENSE)
|
||||||
*No NIST, no elliptic curves, no prime factorization—only randomness itself*
|
[](#installation)
|
||||||
|
|
||||||
**v2.0 New Addition 💬 ChaosCryptChat: End-to-end encrypted chat system (text/images/files/voice) built on ChaosCrypt**
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 📖 Table of Contents
|
## Scope
|
||||||
|
|
||||||
1. [Project Overview](#project-overview)
|
ChaosCrypt is an **unaudited, non-standardised** cipher. It is built for three
|
||||||
2. [Design Philosophy](#design-philosophy)
|
purposes:
|
||||||
3. [Core Features](#core-features)
|
|
||||||
4. [Encryption Workflow](#encryption-workflow)
|
| | Purpose | What it means in practice |
|
||||||
5. [Security Analysis](#security-analysis)
|
|---|---|---|
|
||||||
6. [Why This Is Actually Secure (No-BS Edition)](#why-this-is-actually-secure-no-bs-edition)
|
| 1 | **Obfuscation** | Making data unreadable to casual inspection |
|
||||||
7. [Quick Start](#quick-start)
|
| 2 | **Personal use** | Protecting your own notes, journals and backups |
|
||||||
8. [Usage Guide](#usage-guide)
|
| 3 | **Research & teaching** | Studying how layered obfuscation behaves |
|
||||||
9. [API Reference](#api-reference)
|
|
||||||
10. [FAQ](#faq)
|
**If you need standardised cryptography, use a standardised cipher.** AES-GCM
|
||||||
11. [💬 ChaosCryptChat](#-chaoscryptchat-chaos-encrypted-chat)
|
or ChaCha20-Poly1305 from a vetted library such as
|
||||||
12. [Project Structure](#project-structure)
|
[`cryptography`](https://cryptography.io) are the right tools for production
|
||||||
13. [Disclaimer](#disclaimer)
|
systems, regulated data, and long-lived secrets.
|
||||||
|
|
||||||
|
See [SECURITY.md](SECURITY.md) for the full design and threat analysis, and
|
||||||
|
[docs/FORMAT.md](docs/FORMAT.md) for the normative format specification.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Project Overview
|
## Every artefact describes itself
|
||||||
|
|
||||||
**ChaosCrypt** is a fully self-designed symmetric encryption system. It relies on no third-party crypto libraries (only `base64` for encoding)—all encryption logic is original.
|
Each key file and ciphertext begins with a header that states how it was made.
|
||||||
|
A reader never has to be told the mode, the encoding, or anything else — it
|
||||||
**Core idea**: Replace **mathematical structure** with **randomness**, replace **algebraic equations** with **multi-layer obfuscation**, and use an **immense key space** to completely shut down brute force.
|
reads them from the artefact.
|
||||||
|
|
||||||
> This is not an improvement on existing algorithms—it's a redefinition of what "secure" means.
|
|
||||||
|
|
||||||
**v2.0 New**: Built **ChaosCryptChat**, an end-to-end encrypted chat system on top of the ChaosCrypt kernel, bringing chaos encryption to real-time communication.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Design Philosophy
|
|
||||||
|
|
||||||
There's a consensus in the crypto world: *"Only NIST-certified, mathematically elegant, academically vetted algorithms are secure."*
|
|
||||||
|
|
||||||
ChaosCrypt says:
|
|
||||||
|
|
||||||
> **"You're not wrong, but I don't buy it."**
|
|
||||||
|
|
||||||
- **Dual_EC_DRBG** is still fresh—NIST standard, NSA backdoor, the whole world fooled for years.
|
|
||||||
- **RSA** is mathematically beautiful, right? Standard, right? **Shor kills it instantly.**
|
|
||||||
- **AES** has a clean structure, a well-reasoned S-Box, right? **Grover gives you a square-root speedup.**
|
|
||||||
|
|
||||||
**ChaosCrypt takes another path:**
|
|
||||||
|
|
||||||
> **No math structure. No explainability. No one's stamp of approval.**
|
|
||||||
> **Your only move is brute force—and the space is so large the universe can't hold it.**
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Core Features
|
|
||||||
|
|
||||||
| Feature | Description |
|
|
||||||
|---------|-------------|
|
|
||||||
| 🔑 **Two-factor protection** | System key file (`.key`) + user password |
|
|
||||||
| 🧩 **Fully random keys** | Substitution tables, flip patterns, long key, short key all randomly generated |
|
|
||||||
| 📁 **Key persistence** | Keys stored obfuscated (Base64 + reversal + shift) to prevent casual reading |
|
|
||||||
| 🔁 **Reusable OTP** | Key length ≥ plaintext length, eliminating periodic patterns—OTP-level security |
|
|
||||||
| 🛡️ **Quantum-resistant** | No math structure, so Shor/Grover can't speed up brute force |
|
|
||||||
| 🚫 **Zero third-party deps** | No OpenSSL, no Crypto, no nothing |
|
|
||||||
| 📦 **Ready to use** | Interactive menu, multiple key file support |
|
|
||||||
| 🐍 **Pure Python** | Just Python 3.6+, no extra dependencies |
|
|
||||||
| 💬 **Encrypted Chat (v2.0)** | ChaosCryptChat: E2E text/images/files/voice, P2P + central server modes |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Encryption Workflow
|
|
||||||
|
|
||||||
```
|
```
|
||||||
Plaintext
|
69CES
|
||||||
↓
|
385aeff1f4179a744c8fb0c5ae4702d325f6230d059f4251135c2536409dee93
|
||||||
① Base64 encode
|
{"alg":"chaoscrypt","kind":"ciphertext","mode":"turbo","out":"hex","mid":"bt",...}
|
||||||
↓
|
2025ea4e4b4b93803f2ccadeaf318d1957ce42ff5409410f660348be96a4c0f2
|
||||||
② Random substitution (26 uppercase + 26 lowercase fully shuffled)
|
<payload>
|
||||||
↓
|
|
||||||
③ Case flip (10‑bit random pattern)
|
|
||||||
↓
|
|
||||||
④ String reversal
|
|
||||||
↓
|
|
||||||
⑤ Dynamic XOR (4096‑bit long key)
|
|
||||||
↓
|
|
||||||
⑥ Final XOR (user password + 512‑bit short key derived)
|
|
||||||
↓
|
|
||||||
Ciphertext (hex)
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Every random parameter comes from the `.key` file. The user password is only used in the final key derivation step.
|
The consequence is deliberate: **input without a valid header is rejected**
|
||||||
|
(`E017`), rather than guessed at. A ciphertext decrypted under the wrong
|
||||||
### Key Derivation Flow
|
parameters produces garbage that looks like a wrong password, and the header
|
||||||
|
removes that ambiguity entirely.
|
||||||
```
|
|
||||||
User password + short_key (512 bits)
|
|
||||||
↓
|
|
||||||
Interleave → bitwise mixing → block permutation → reversal
|
|
||||||
↓
|
|
||||||
Expand to target length (three transformation modes cycled)
|
|
||||||
↓
|
|
||||||
Final key (length ≥ plaintext)
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Security Analysis
|
|
||||||
|
|
||||||
### 1. No Mathematical Equations to Write
|
|
||||||
|
|
||||||
| Traditional Alg | Equation Form | Attack Vector |
|
|
||||||
|-----------------|---------------|---------------|
|
|
||||||
| RSA | c = m^e mod n | Number field sieve, Shor |
|
|
||||||
| AES | State = SBox ∘ ShiftRow ∘ MixCol ∘ AddRoundKey | Differential, Grover |
|
|
||||||
| ECC | Q = kP | Discrete log, Shor |
|
|
||||||
| **ChaosCrypt** | **No meaningful equation can be written** | **Brute force only** |
|
|
||||||
|
|
||||||
> Why: substitution is table lookup, flip pattern is a hardcoded array, key derivation is a black-box mix—every step is "random table lookup" with no parseable algebraic structure.
|
|
||||||
|
|
||||||
### 2. Key Space (Brute‑Force Difficulty)
|
|
||||||
|
|
||||||
| Component | Space Size | Approx. Value |
|
|
||||||
|-----------|------------|---------------|
|
|
||||||
| `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‑bit hex) | 16⁴⁰⁹⁶ | ~10⁴⁹³² |
|
|
||||||
| `short_key` (512‑bit hex) | 16⁵¹² | ~10⁶¹⁶ |
|
|
||||||
| `flip_pattern` | 2¹⁰ | ~10³ |
|
|
||||||
| User password (min 8 chars) | ~10⁸ | |
|
|
||||||
|
|
||||||
**Total search space ≈ 10⁵⁶³²**
|
|
||||||
|
|
||||||
**Comparisons**:
|
|
||||||
|
|
||||||
- Atoms in the observable universe: ≈ 10⁸⁰
|
|
||||||
- AES‑256 key space: ≈ 10⁷⁷
|
|
||||||
- RSA‑2048 key space: ≈ 10⁶¹⁶
|
|
||||||
- **ChaosCrypt: ≈ 10⁵⁶³²** (10⁵⁵⁵⁵ × AES)
|
|
||||||
|
|
||||||
> **Even if every atom in the universe were a quantum computer, they couldn't exhaust this space before the heat death of the cosmos.**
|
|
||||||
|
|
||||||
### 3. Quantum Resistance
|
|
||||||
|
|
||||||
| Quantum Alg | Target | Effect on ChaosCrypt |
|
|
||||||
|-------------|--------|----------------------|
|
|
||||||
| **Shor** | Integer factorization, discrete log | ❌ **Ineffective** – no number‑theoretic structure |
|
|
||||||
| **Grover** | Symmetric encryption speedup | ❌ **Ineffective** – space 10⁵⁶³², sqrt gives 10²⁸¹⁶, still >> 10⁸⁰ |
|
|
||||||
|
|
||||||
**Conclusion: ChaosCrypt is fully immune to known quantum attacks.**
|
|
||||||
|
|
||||||
### 4. Classical Attack Vectors
|
|
||||||
|
|
||||||
| Attack | Feasible? | Reason |
|
|
||||||
|--------|-----------|--------|
|
|
||||||
| Frequency analysis | ❌ | Random substitution destroys frequency patterns |
|
|
||||||
| Periodicity analysis | ❌ | Key length ≥ plaintext, no cycles |
|
|
||||||
| Known‑plaintext attack | ❌ | Nonlinear ops → overdetermined system with no solution |
|
|
||||||
| Chosen‑plaintext attack | ❌ | Even controllable input can't invert the black‑box mapping |
|
|
||||||
| Differential/linear | ❌ | No algebraic structure to build differential chains |
|
|
||||||
| Brute force | ❌ | Space 10⁵⁶³², physically impossible |
|
|
||||||
|
|
||||||
**The only real threat**: Theft of `.key` file + password (client‑side compromise, unrelated to the algorithm).
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Why This Is Actually Secure (No‑BS Edition)
|
|
||||||
|
|
||||||
**Bottom line: It's secure — genuinely secure.** 🤷♂️
|
|
||||||
|
|
||||||
Look, not every encryption algorithm has to revolve around elliptic curves and prime factorization, waiting for NIST to stamp it "secure." That's not security—that's **a monopoly.** 🤣
|
|
||||||
|
|
||||||
And let's not forget **Dual_EC_DRBG** — NIST‑certified, standardized, used worldwide for years… and it had an NSA backdoor baked in. So much for standards.
|
|
||||||
|
|
||||||
So don't give me "academic verification," "third‑party audit," or "standard certification." I'll ask you one question:
|
|
||||||
|
|
||||||
**Are only those "standard" algorithms allowed to be secure?**
|
|
||||||
|
|
||||||
- **Secure ≠ mathematically complex**
|
|
||||||
- **Secure ≠ NIST‑approved**
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
Let's see how those "standard" algorithms fare:
|
|
||||||
|
|
||||||
| Algorithm | Key Space | Quantum Fate |
|
|
||||||
|-----------|-----------|--------------|
|
|
||||||
| AES‑256 | 10⁷⁷ | Grover halves it to 10³⁸ → theoretically breakable |
|
|
||||||
| RSA‑2048 | 10⁶¹⁶ | Shor kills it instantly 🔥 |
|
|
||||||
| ECC | 10⁶¹⁶ | Same, Shor shuts it down |
|
|
||||||
|
|
||||||
Now look at this:
|
|
||||||
|
|
||||||
| Algorithm | Key Space | Quantum Fate |
|
|
||||||
|-----------|-----------|--------------|
|
|
||||||
| **ChaosCrypt** | **10⁵⁶³²** | **Shor has nothing to attack, Grover barely scratches it** ✅ |
|
|
||||||
|
|
||||||
**10⁵⁶³² — what does that mean?**
|
|
||||||
|
|
||||||
The universe has ~10⁸⁰ atoms. Even if every atom were a quantum computer running from the Big Bang to now, they wouldn't finish a fraction of this space.
|
|
||||||
|
|
||||||
AES's 10⁷⁷ is a grain of sand compared to the Milky Way.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
**RSA is beautiful, right? Standard? Mathematically elegant?**
|
|
||||||
|
|
||||||
But precisely because it's **too mathematical**, Shor one‑shots it.
|
|
||||||
|
|
||||||
**The prettier the math, the clearer the structure, the happier the attacker** — because you have equations they can solve, patterns they can exploit, structure they can dismantle.
|
|
||||||
|
|
||||||
My algorithm?
|
|
||||||
|
|
||||||
- Substitution? Randomly shuffled — no pattern.
|
|
||||||
- Flip pattern? Hardcoded array — no equation.
|
|
||||||
- Key derivation? Black‑box mix — unsolvable.
|
|
||||||
|
|
||||||
**An attacker can't even write an equation. There's no algebraic handle to grab.**
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
**So what's wrong with this algorithm?**
|
|
||||||
|
|
||||||
- ❌ No "third‑party security audit"
|
|
||||||
- ❌ No "algorithm standard certification"
|
|
||||||
- ❌ No "academic validation"
|
|
||||||
- ❌ And it "looks pretty amateur"
|
|
||||||
|
|
||||||
**Other than that, absolutely nothing.** 🤷♂️
|
|
||||||
|
|
||||||
Looks amateur? Fine. **Can you break it? No.**
|
|
||||||
|
|
||||||
Security is about **real‑world results**, not **reviews** or **certifications**.
|
|
||||||
|
|
||||||
- Dual_EC_DRBG had certs, standards, audits — and a backdoor.
|
|
||||||
- This has none of that — and **you can't break it.**
|
|
||||||
|
|
||||||
**If hackers can crack it, it's garbage. If they can't, it's the real deal.**
|
|
||||||
|
|
||||||
Seriously — **find a flaw. I dare you.** 😏🔥
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 💬 ChaosCryptChat (v2.0 New)
|
|
||||||
|
|
||||||
**ChaosCryptChat** is an end‑to‑end encrypted chat system built on the ChaosCrypt kernel. All content (text, images, files, voice) is chaos‑encrypted before sending—servers and middlemen cannot read any messages.
|
|
||||||
|
|
||||||
### Core Features
|
|
||||||
|
|
||||||
| Feature | Description |
|
|
||||||
|---------|-------------|
|
|
||||||
| 🔗 **End‑to‑end encryption** | All messages encrypted client‑side; server only relays, holds no group keys |
|
|
||||||
| ☁️ **Two group modes** | 🔗 P2P direct + ☁️ Central server (NAT traversal) |
|
|
||||||
| 🎤 **Voice messages** | Record → chaos encrypt → send → decrypt & play |
|
|
||||||
| 🖼️ **Images / Files** | Binary data encrypted with ChaosCrypt, supports any file type |
|
|
||||||
| 👥 **Group management** | Create, join, group name, announcements, kick, owner approval |
|
|
||||||
| 🚫 **Message recall** | Recall within 2 minutes of sending |
|
|
||||||
| 🔑 **Per‑user keys** | Each user has an independent authentication key to prevent impersonation |
|
|
||||||
| 📜 **History** | SQLite local storage (persists across restarts) |
|
|
||||||
| 🛡️ **HMAC verification** | Every message carries an HMAC signature to prevent tampering and forgery |
|
|
||||||
| 📱 **Key sharing** | Group key can be shared via copy / QR code / file |
|
|
||||||
|
|
||||||
### Two Group Modes
|
|
||||||
|
|
||||||
**① End‑to‑End (P2P) Group**: The group owner acts as the server; members connect directly to the owner's host. Ideal for LAN or public‑IP environments. The owner generates the group key and shares it with members.
|
|
||||||
|
|
||||||
**② Central Server Group**: Run `server.py` (public IP) to handle NAT traversal. The server only handles user authentication, group membership, and message relaying—**it does not hold group keys and cannot decrypt any messages.**
|
|
||||||
|
|
||||||
### Quick Start
|
|
||||||
|
|
||||||
#### Launch the Chat Client
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cd ChaosCryptChat
|
|
||||||
python qtmain.py
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Launch the Central Server (optional, for public/NAT scenarios)
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cd ChaosCryptChat
|
|
||||||
python server.py 8666
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Install Dependencies
|
|
||||||
|
|
||||||
```bash
|
|
||||||
pip install PyQt5 # Required, GUI
|
|
||||||
pip install pygame # Audio playback (optional)
|
|
||||||
pip install sounddevice numpy # Recording (optional, or pyaudio)
|
|
||||||
pip install Pillow # Image display (optional)
|
|
||||||
pip install qrcode # Group key QR codes (optional)
|
|
||||||
```
|
|
||||||
|
|
||||||
> Only PyQt5 is required; all others are optional. Missing dependencies disable their respective features gracefully.
|
|
||||||
|
|
||||||
### Usage Workflow
|
|
||||||
|
|
||||||
1. **Register / Login**: Create a local account on startup (PBKDF2 password hash, auto‑login supported)
|
|
||||||
2. **Create a Group**: Click 「📡 Create Group」, copy the group key or generate a QR code to share with friends
|
|
||||||
3. **Join a Group**: Click 「📥 Join Group」, paste the group key or scan the QR code
|
|
||||||
4. **Start Chatting**: Send text, images, files, voice messages; right‑click to recall, share, or download; group owners can kick, set announcements, and change group names
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Quick Start
|
|
||||||
|
|
||||||
### Installation
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Clone the repository
|
|
||||||
git clone https://gitcode.com/dvsxt/chaoscrypt.git
|
|
||||||
git clone https://github.com/dvs-dvsxt/ChaosCrypt.git
|
|
||||||
cd chaoscrypt
|
|
||||||
|
|
||||||
# Core module has zero dependencies — Python 3.6+ only
|
|
||||||
# ChaosCryptChat requires PyQt5
|
|
||||||
```
|
|
||||||
|
|
||||||
### Five‑Minute Example
|
|
||||||
|
|
||||||
```python
|
```python
|
||||||
from chaoscrypt import EncryptionSystem
|
from chaoscrypt import ChaosCrypt
|
||||||
|
|
||||||
# Initialize (auto‑loads default key; generates one if missing)
|
cc = ChaosCrypt(key_file="my.key", key_password="key-file-password",
|
||||||
crypto = EncryptionSystem()
|
auto_load=True)
|
||||||
|
|
||||||
# Encrypt
|
# whatever produced this, it will be read correctly
|
||||||
cipher = crypto.encrypt("Hello World", user_password="MyP@ssw0rd2024!")
|
plain = cc.decrypt(open("message.ces").read(), "encryption-password")
|
||||||
print(cipher)
|
|
||||||
|
|
||||||
# Decrypt
|
|
||||||
plain = crypto.decrypt(cipher, user_password="MyP@ssw0rd2024!")
|
|
||||||
print(plain) # Hello World
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Command‑Line Interactive Mode
|
---
|
||||||
|
|
||||||
|
## Performance modes
|
||||||
|
|
||||||
|
Four modes, selectable at construction, on the command line, and from the TUI.
|
||||||
|
|
||||||
|
| Mode | Algorithm | Ciphertext | Compatible with pre-4.2.6 material |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `reference` | the original algorithm, character pipeline | 5.33x | payload identical |
|
||||||
|
| `fast` *(default)* | same algorithm, bulk operations | 5.33x | payload identical |
|
||||||
|
| `turbo` | SHAKE256 keystream, byte pipeline | 2.00x / 1.33x | no |
|
||||||
|
| `raw` | SHAKE256 plus the long-key layer | 2.00x / 1.33x | no |
|
||||||
|
|
||||||
|
`turbo` and `raw` take two extra settings:
|
||||||
|
|
||||||
|
| Setting | Values | Meaning |
|
||||||
|
|---|---|---|
|
||||||
|
| `encoding` | `hex` (default), `base64` | final output encoding: 2.00x or 1.33x expansion |
|
||||||
|
| `mid` | `bt` (default), `hex` | whether bytes or hexadecimal text are carried between the XOR layers |
|
||||||
|
|
||||||
|
```python
|
||||||
|
from chaoscrypt import ChaosCrypt
|
||||||
|
|
||||||
|
cc = ChaosCrypt(mode="raw", encoding="base64", mid="bt")
|
||||||
|
```
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python chaoscrypt.py
|
chaoscrypt encrypt "hello" -p pw -k my.key -P kp --mode raw --encoding base64
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Measured throughput
|
||||||
|
|
||||||
|
Hex output, `raw` mode, 1 MiB payloads and above:
|
||||||
|
|
||||||
|
| mid | Encrypt | Decrypt | Ciphertext |
|
||||||
|
|---|---:|---:|---:|
|
||||||
|
| `bt` (default) | **57–63 MB/s** | **61–73 MB/s** | 2.00x |
|
||||||
|
| `hex` | 18–21 MB/s | 18–23 MB/s | 8.00x |
|
||||||
|
|
||||||
|
Throughput holds steady from 64 KiB to 1 GiB, which is what a linear algorithm
|
||||||
|
looks like. Full figures, including the profiling behind them, are in
|
||||||
|
[docs/benchmark.md](docs/benchmark.md).
|
||||||
|
|
||||||
|
For scale: the original implementation managed **0.08 MB/s**, about twelve
|
||||||
|
seconds per megabyte.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Usage Guide
|
## Reading artefacts from before 4.2.6
|
||||||
|
|
||||||
### Interactive Menu
|
Artefacts written before the header existed have none. They are read through a
|
||||||
|
compatibility API, which synthesises a minimal header and then uses the ordinary
|
||||||
|
path — so the strict path stays strict, and there is no lenient branch inside
|
||||||
|
it.
|
||||||
|
|
||||||
```
|
|
||||||
Please select an action:
|
|
||||||
1. Encrypt using the default key
|
|
||||||
2. Decrypt using the default key
|
|
||||||
3. Generate a new key (overwrite default)
|
|
||||||
4. Encrypt using a specified key file
|
|
||||||
5. Decrypt using a specified key file
|
|
||||||
6. Generate a key and save to current folder
|
|
||||||
7. View current key info
|
|
||||||
8. Exit
|
|
||||||
```
|
|
||||||
|
|
||||||
### Key File
|
|
||||||
|
|
||||||
Keys are stored in an obfuscated format to prevent casual reading. Contents include:
|
|
||||||
|
|
||||||
- `upper_mapping` – random substitution for uppercase letters
|
|
||||||
- `lower_mapping` – random substitution for lowercase letters
|
|
||||||
- `digit_mapping` – digit‑to‑character mapping
|
|
||||||
- `equal_mapping` – equal‑sign mapping
|
|
||||||
- `long_key` – 4096‑bit hexadecimal key
|
|
||||||
- `short_key` – 512‑bit hexadecimal key
|
|
||||||
- `generated_at` – timestamp
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## API Reference
|
|
||||||
|
|
||||||
### `EncryptionSystem(key_file=None)`
|
|
||||||
|
|
||||||
Initialize the encryption system.
|
|
||||||
|
|
||||||
**Parameters:**
|
|
||||||
- `key_file` (str, optional) – path to the key file. If `None`, loads `encryption.key`; generates one if missing.
|
|
||||||
|
|
||||||
**Example:**
|
|
||||||
```python
|
```python
|
||||||
# Use default key
|
from chaoscrypt import ChaosCrypt
|
||||||
crypto = EncryptionSystem()
|
|
||||||
|
|
||||||
# Use a custom key file
|
cc = ChaosCrypt(key_file="my.key", key_password="key-file-password",
|
||||||
crypto = EncryptionSystem("my_key.key")
|
auto_load=True)
|
||||||
|
|
||||||
|
# a ciphertext with no header
|
||||||
|
plain = cc.decrypt_legacy("72370655031311011c111f261365172716020b69",
|
||||||
|
"encryption-password")
|
||||||
|
|
||||||
|
# a key file with no header
|
||||||
|
cc.load_legacy_keys(open("old.key", encoding="utf-8").read(), "key-password")
|
||||||
|
|
||||||
|
# or modernise one, once
|
||||||
|
open("new.key", "w", encoding="utf-8").write(
|
||||||
|
cc.wrap_legacy(open("old.key", encoding="utf-8").read(), is_key=True)
|
||||||
|
)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
`decrypt_legacy_auto` probes whether the artefact is a key file or a ciphertext,
|
||||||
|
so the caller does not have to know. See
|
||||||
|
[docs/FORMAT.md §12](docs/FORMAT.md) for the legacy standard.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### `encrypt(plaintext, user_password)`
|
## Installation
|
||||||
|
|
||||||
Encrypt plaintext.
|
```bash
|
||||||
|
pip install chaoscrypt
|
||||||
|
```
|
||||||
|
|
||||||
**Parameters:**
|
**Requires** Python 3.8 or newer. No third-party runtime dependencies.
|
||||||
- `plaintext` (str) – text to encrypt
|
|
||||||
- `user_password` (str) – user password
|
|
||||||
|
|
||||||
**Returns:**
|
---
|
||||||
- `str` – hexadecimal ciphertext
|
|
||||||
|
## Three ways to use it
|
||||||
|
|
||||||
|
### 1. As a library
|
||||||
|
|
||||||
**Example:**
|
|
||||||
```python
|
```python
|
||||||
cipher = crypto.encrypt("Hello", "myPass123")
|
from chaoscrypt import ChaosCrypt
|
||||||
|
|
||||||
|
cc = ChaosCrypt()
|
||||||
|
cc.create_key("key-file-password", "my.key")
|
||||||
|
|
||||||
|
token = cc.encrypt("hello world", "encryption-password")
|
||||||
|
assert cc.decrypt(token, "encryption-password") == "hello world"
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
Binary data and files:
|
||||||
|
|
||||||
### `decrypt(ciphertext, user_password)`
|
|
||||||
|
|
||||||
Decrypt ciphertext.
|
|
||||||
|
|
||||||
**Parameters:**
|
|
||||||
- `ciphertext` (str) – hexadecimal ciphertext
|
|
||||||
- `user_password` (str) – user password
|
|
||||||
|
|
||||||
**Returns:**
|
|
||||||
- `str` – decrypted plaintext, or an error message on failure
|
|
||||||
|
|
||||||
**Example:**
|
|
||||||
```python
|
```python
|
||||||
plain = crypto.decrypt("a1b2c3...", "myPass123")
|
cc = ChaosCrypt("my.key", "key-file-password", auto_load=True)
|
||||||
|
|
||||||
|
raw = open("photo.png", "rb").read()
|
||||||
|
open("photo.cc", "w").write(cc.encrypt_bytes(raw, "encryption-password"))
|
||||||
|
|
||||||
|
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 `ChaosCryptError` and renders as
|
||||||
|
`ChaosCrypt_ERR_<Detail>_<Code>`:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from chaoscrypt import ChaosCrypt, ChaosCryptError
|
||||||
|
|
||||||
|
try:
|
||||||
|
ChaosCrypt().load("my.key", "wrong-password")
|
||||||
|
except ChaosCryptError as e:
|
||||||
|
print(e) # ChaosCrypt_ERR_KeyPasswordIncorrect_E003
|
||||||
|
print(e.code) # E003
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. As a command line tool
|
||||||
|
|
||||||
|
**No arguments** launches the interactive TUI. **With arguments** it is a
|
||||||
|
scriptable CLI:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
chaoscrypt keygen -k my.key --key-pwd-env KEY_PWD
|
||||||
|
chaoscrypt encrypt "hello world" -p mypass -k my.key -P keypass
|
||||||
|
chaoscrypt decrypt "1a2b3c..." -p mypass -k my.key -P keypass
|
||||||
|
chaoscrypt file encrypt photo.png -p mypass -k my.key -P keypass
|
||||||
|
chaoscrypt info -k my.key -P keypass --json
|
||||||
|
chaoscrypt chpwd -k my.key -P oldpass --new-pwd newpass
|
||||||
|
```
|
||||||
|
|
||||||
|
`-p`/`--pwd` is the **encryption password**; `-P`/`--key-pwd` is the **key file
|
||||||
|
password**. Passwords may come inline, from an environment variable, or from a
|
||||||
|
file.
|
||||||
|
|
||||||
|
**Exit codes:** `0` success, `1` runtime error, `2` usage error. See
|
||||||
|
[docs/CLI.md](docs/CLI.md) for the full reference.
|
||||||
|
|
||||||
|
### 3. As an interactive TUI
|
||||||
|
|
||||||
|
```bash
|
||||||
|
chaoscrypt
|
||||||
|
```
|
||||||
|
|
||||||
|
```
|
||||||
|
+================================================================+
|
||||||
|
| ChaosCrypt - Chaos Obfuscation Cipher v4.2.6 |
|
||||||
|
+================================================================+
|
||||||
|
[*] Key file loaded my.key [fast]
|
||||||
|
|
||||||
|
------------------------------------------------------------------
|
||||||
|
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
|
||||||
|
[m] Performance mode
|
||||||
|
[e] Output encoding
|
||||||
|
[a] About / security notice
|
||||||
|
[q] Quit
|
||||||
|
------------------------------------------------------------------
|
||||||
|
```
|
||||||
|
|
||||||
|
Bilingual (option `[9]`), passwords are not echoed, and the interface degrades
|
||||||
|
cleanly when output is piped.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Error codes
|
||||||
|
|
||||||
|
| Code | Meaning |
|
||||||
|
|---|---|
|
||||||
|
| `E001` | Key file not found |
|
||||||
|
| `E002` | Key file corrupted |
|
||||||
|
| `E003` | Key file password incorrect |
|
||||||
|
| `E004` | No key loaded |
|
||||||
|
| `E005` | Key file already exists |
|
||||||
|
| `E006` | A required password was missing |
|
||||||
|
| `E007` | Password mismatch |
|
||||||
|
| `E008` | Empty plaintext |
|
||||||
|
| `E009` | Empty ciphertext |
|
||||||
|
| `E010` | Malformed payload (not valid hexadecimal, or bad length) |
|
||||||
|
| `E011` | Decryption failed (wrong password, wrong key, or tampered) |
|
||||||
|
| `E012` | Encoding failure |
|
||||||
|
| `E013` | Invalid argument |
|
||||||
|
| `E014` | File read failed |
|
||||||
|
| `E015` | File write failed |
|
||||||
|
| `E016` | Unsupported key file version |
|
||||||
|
| `E017` | **Missing magic header** — not a CES artefact |
|
||||||
|
| `E018` | **Malformed header** — marker missing, JSON unusable, or `kind` mismatch |
|
||||||
|
|
||||||
|
Codes are stable and safe to branch on.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Documentation
|
||||||
|
|
||||||
|
| Document | Contents |
|
||||||
|
|---|---|
|
||||||
|
| [SECURITY.md](SECURITY.md) | Design, key space, threat model, attack analysis |
|
||||||
|
| [docs/FORMAT.md](docs/FORMAT.md) | **Normative format specification**, with examples |
|
||||||
|
| [docs/benchmark.md](docs/benchmark.md) | Measured throughput and the profiling behind it |
|
||||||
|
| [docs/API.md](docs/API.md) | Complete Python API reference |
|
||||||
|
| [docs/CLI.md](docs/CLI.md) | Command line reference and troubleshooting |
|
||||||
|
| [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) | Internal design and module map |
|
||||||
|
| [docs/BUILDING.md](docs/BUILDING.md) | Building, testing and releasing |
|
||||||
|
| [CHANGELOG.md](CHANGELOG.md) | Release history |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 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/
|
||||||
|
├── pyproject.toml
|
||||||
|
├── dist/
|
||||||
|
└── chaoscrypt/
|
||||||
|
├── __init__.py public API and the ChaosCrypt facade
|
||||||
|
├── _core.py the algorithm and the pipelines
|
||||||
|
├── _header.py the self-describing header
|
||||||
|
├── 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, including frozen vectors
|
||||||
|
├── examples/ runnable examples
|
||||||
|
└── legacy/ the original implementation, for reference
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### `generate_keys(save_path=None)`
|
## Licence
|
||||||
|
|
||||||
Generate new random keys and save them.
|
[MIT](LICENSE) — provided as-is, without warranty of any kind.
|
||||||
|
|
||||||
**Parameters:**
|
ChaosCrypt has not been independently audited. It is intended for obfuscation,
|
||||||
- `save_path` (str, optional) – save path; defaults to `key_{timestamp}.key`
|
personal use, and research or teaching. Do not deploy it where an audited,
|
||||||
|
standardised cryptographic primitive is required.
|
||||||
**Returns:**
|
|
||||||
- `str` – the saved file path
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### `print_keys()`
|
|
||||||
|
|
||||||
Print the current key information.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## FAQ
|
|
||||||
|
|
||||||
**Q: Has this algorithm been audited?**
|
|
||||||
A: No. But we believe **no audit ≠ insecure** — Dual_EC_DRBG was audited and backdoored. Audits are references, not truth.
|
|
||||||
|
|
||||||
**Q: Why not just use AES?**
|
|
||||||
A: AES is great, but it's a "standard" algorithm with algebraic structure, and Grover can speed it up. We chose a different path — **fully random, structure‑free, and enormous.**
|
|
||||||
|
|
||||||
**Q: What if an attacker gets the `.key` file and the ciphertext, but not the password?**
|
|
||||||
A: Then they're left with brute‑forcing the password. If the password is 12+ characters strong, that's years of work.
|
|
||||||
|
|
||||||
**Q: What if the attacker gets the `.key`, ciphertext, and password?**
|
|
||||||
A: Then your system isn't "crypto broken" — it's "keys stolen." That's a client‑side security issue, which no encryption algorithm can prevent.
|
|
||||||
|
|
||||||
**Q: Is there a mathematical proof for this?**
|
|
||||||
A: Yes. The proof is:
|
|
||||||
- No mathematical model can be constructed → no algebraic attacks
|
|
||||||
- Key space 10⁵⁶³² → brute force impossible
|
|
||||||
- Quantum speedups don't help → quantum‑resistant
|
|
||||||
|
|
||||||
This proof is stronger than any "reduction to a hard problem" — because **there's no structure to reduce, only exhaustive search.**
|
|
||||||
|
|
||||||
**Q: It looks so amateurish — is it actually usable?**
|
|
||||||
A: Looking amateur and being secure have nothing to do with each other. Can you break it or not? **Try it.**
|
|
||||||
|
|
||||||
**Q: Is ChaosCryptChat secure?**
|
|
||||||
A: End‑to‑end — messages are encrypted client‑side with the group key; the server forwards only ciphertext and holds no keys. Even if the server is breached, chat contents remain private.
|
|
||||||
|
|
||||||
**Q: How do I share the group key?**
|
|
||||||
A: After creating a group, the owner can share the key via copied text, QR code, or key file. Use a trusted channel to avoid MITM interception.
|
|
||||||
|
|
||||||
**Q: Does ChaosCryptChat require a public IP?**
|
|
||||||
A: No. Use P2P for LAN; for cross‑network, the central server (`server.py`) relays traffic to handle NAT.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Project Structure
|
|
||||||
|
|
||||||
```
|
|
||||||
chaoscrypt/
|
|
||||||
├── chaoscrypt.py # Main program (encrypt/decrypt/key management)
|
|
||||||
├── README.md # This document
|
|
||||||
├── SECURITY.md # Security details
|
|
||||||
└── ChaosCryptChat/ # 💬 Encrypted Chat (v2.0 new)
|
|
||||||
├── qtmain.py # PyQt5 chat client (E2E encrypted)
|
|
||||||
└── server.py # ☁️ Central server (NAT traversal / message relay)
|
|
||||||
```
|
|
||||||
|
|
||||||
The core is just three files with zero dependencies; ChaosCryptChat is the v2.0 addition.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Disclaimer
|
|
||||||
|
|
||||||
> **This system is for educational and research purposes only.**
|
|
||||||
> The author assumes no liability for data loss due to key file leakage, password theft, or client‑side compromise.
|
|
||||||
> In production, ensure the `.key` file and user password are stored securely, and enforce strong password policies.
|
|
||||||
> **ChaosCryptChat** servers do not hold group keys, but they do log login information and relay metadata—choose your server wisely.
|
|
||||||
> Group keys are shared by the group owner; transmit them over trusted channels. Even if the server is compromised, historical chat content remains private.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 📜 License
|
|
||||||
|
|
||||||
MIT License — you are free to use, modify, and distribute, but please retain the original attribution.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 🙏 Acknowledgments
|
|
||||||
|
|
||||||
Thank you to everyone who read this document carefully.
|
|
||||||
You are among the few who judge security by **logic**, not by **credentials**.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
**"Security should be defined by the difficulty of attack, not by a stamp from an institution."**
|
|
||||||
— ChaosCrypt Design Philosophy
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
**Happy Encrypting! 🔐**
|
|
||||||
|
|||||||
+700
-667
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,404 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""
|
||||||
|
ChaosCrypt benchmark suite
|
||||||
|
==========================
|
||||||
|
|
||||||
|
Measures the throughput of every public operation in ChaosCrypt.
|
||||||
|
|
||||||
|
Run it from the repository root so the package is importable:
|
||||||
|
|
||||||
|
python bench/benchmark.py
|
||||||
|
python bench/benchmark.py --budget 0.05 --repeats 3
|
||||||
|
python bench/benchmark.py --sizes 64,1024,65536
|
||||||
|
python bench/benchmark.py --groups Text,Binary
|
||||||
|
|
||||||
|
Why this design
|
||||||
|
---------------
|
||||||
|
* Every operation is dispatched to a process pool with one worker per CPU
|
||||||
|
core, so the whole suite completes in a single parallel wave.
|
||||||
|
* Windows uses the ``spawn`` start method, which means **lambdas and closures
|
||||||
|
cannot be pickled** and therefore cannot be sent to a worker. Every
|
||||||
|
benchmark is expressed as a *spec*: a plain, picklable dict describing the
|
||||||
|
operation and its parameters. Each worker rebuilds the callable locally.
|
||||||
|
* Inside a worker each task is warmed up, the loop count is auto-calibrated to
|
||||||
|
fill a small time budget, and the reported figure is the best of N repeats.
|
||||||
|
That way both fast operations (microseconds) and slow ones (hundreds of
|
||||||
|
milliseconds) are measured meaningfully.
|
||||||
|
|
||||||
|
What is measured
|
||||||
|
----------------
|
||||||
|
ChaosCrypt has two distinct costs, and they are reported separately:
|
||||||
|
|
||||||
|
* **Key setup** — generating key material, and loading a key file. Dominated by
|
||||||
|
``os.urandom`` calls for the former and by a 4096-nibble XOR for the latter.
|
||||||
|
* **Per-message work** — the actual encrypt/decrypt pipelines, which are
|
||||||
|
linear in message length: Base64, substitution, case flipping, reversal and
|
||||||
|
two XOR passes.
|
||||||
|
|
||||||
|
Output is a set of tables grouped by category, sorted by speed within each
|
||||||
|
group, plus a summary of wall clock, failures and memory footprint.
|
||||||
|
|
||||||
|
See ``docs/benchmark.md`` for the published results and the discussion.
|
||||||
|
"""
|
||||||
|
import argparse
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from concurrent.futures import ProcessPoolExecutor, as_completed
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- defaults
|
||||||
|
DEFAULT_BUDGET = 0.03 # seconds of measurement per task
|
||||||
|
DEFAULT_REPEATS = 1 # best of N
|
||||||
|
KB = 1024
|
||||||
|
MB = 1024 * 1024
|
||||||
|
|
||||||
|
GROUPS = ["KeySetup", "Text", "Binary", "File", "Error", "Overhead"]
|
||||||
|
|
||||||
|
|
||||||
|
# =================================================================== timing
|
||||||
|
def _timeit(call, budget):
|
||||||
|
"""Warm up, auto-calibrate, and return (seconds_per_op, iterations)."""
|
||||||
|
call() # warm-up
|
||||||
|
n = 1
|
||||||
|
while True:
|
||||||
|
t0 = time.perf_counter()
|
||||||
|
for _ in range(n):
|
||||||
|
call()
|
||||||
|
dt = time.perf_counter() - t0
|
||||||
|
if dt >= budget or n >= (1 << 22):
|
||||||
|
break
|
||||||
|
n = max(n * 2, int(n * budget / max(dt, 1e-9)))
|
||||||
|
t0 = time.perf_counter()
|
||||||
|
for _ in range(n):
|
||||||
|
call()
|
||||||
|
return (time.perf_counter() - t0) / n, n
|
||||||
|
|
||||||
|
|
||||||
|
def _payload(size):
|
||||||
|
"""Deterministic payload, identical in every worker (no RNG involved)."""
|
||||||
|
seed = b"ChaosCrypt-benchmark-payload-"
|
||||||
|
return (seed * (size // len(seed) + 2))[:size]
|
||||||
|
|
||||||
|
|
||||||
|
def run_spec(args):
|
||||||
|
"""Executed inside a worker process. ``args`` = (spec, budget, repeats)."""
|
||||||
|
spec, budget, repeats = args
|
||||||
|
sys.path.insert(0, spec["root"])
|
||||||
|
try:
|
||||||
|
call, unit_bytes, unit_ops = _build(spec)
|
||||||
|
best = float("inf")
|
||||||
|
iters = 0
|
||||||
|
for _ in range(max(1, repeats)):
|
||||||
|
sec, n = _timeit(call, budget)
|
||||||
|
best = min(best, sec)
|
||||||
|
iters = n
|
||||||
|
except Exception as e: # noqa: BLE001
|
||||||
|
return {"name": spec["name"], "group": spec["group"],
|
||||||
|
"error": f"{type(e).__name__}: {e}"}
|
||||||
|
res = {"name": spec["name"], "group": spec["group"],
|
||||||
|
"sec_per_op": best, "ops_per_sec": unit_ops / best, "iters": iters}
|
||||||
|
if unit_bytes:
|
||||||
|
res["mb_per_sec"] = (unit_bytes * unit_ops) / best / MB
|
||||||
|
return res
|
||||||
|
|
||||||
|
|
||||||
|
# =================================================================== builders
|
||||||
|
def _fixed_core():
|
||||||
|
"""A ChaosCryptCore with deterministic key material, rebuilt per worker.
|
||||||
|
|
||||||
|
Using fixed material keeps measurements comparable between runs, and the
|
||||||
|
determinism means a warm-up cannot accidentally leave stale state.
|
||||||
|
"""
|
||||||
|
import hashlib
|
||||||
|
from chaoscrypt._core import ChaosCryptCore
|
||||||
|
|
||||||
|
def det_hex(n, seed):
|
||||||
|
out = []
|
||||||
|
h = hashlib.sha256(seed.encode()).digest()
|
||||||
|
while len(out) * 64 < n:
|
||||||
|
h = hashlib.sha256(h).digest()
|
||||||
|
out.append(h.hex())
|
||||||
|
return "".join(out)[:n]
|
||||||
|
|
||||||
|
c = ChaosCryptCore()
|
||||||
|
c.upper_mapping = "BCDEFGHIJKLMNOPQRSTUVWXYZA"
|
||||||
|
c.lower_mapping = "bcdefghijklmnopqrstuvwxyza"
|
||||||
|
c.digit_mapping = {str(i): ch for i, ch in enumerate("ABCDEFGHIJ")}
|
||||||
|
c.equal_mapping = {"0": "W", "1": "X", "2": "Z", "3": "Y"}
|
||||||
|
c.flip_pattern = [1, 0, 1, 0, 0, 1, 0, 0, 1, 0]
|
||||||
|
c.long_key = det_hex(4096, "bench-long")
|
||||||
|
c.short_key = det_hex(512, "bench-short")
|
||||||
|
c.digit_reverse = {v: k for k, v in c.digit_mapping.items()}
|
||||||
|
c.equal_reverse = {v: k for k, v in c.equal_mapping.items()}
|
||||||
|
c._build_maps()
|
||||||
|
c.keys_loaded = True
|
||||||
|
return c
|
||||||
|
|
||||||
|
|
||||||
|
def _rotating_core():
|
||||||
|
"""A core that regenerates key material on every call (key-setup cost)."""
|
||||||
|
from chaoscrypt._core import ChaosCryptCore
|
||||||
|
core = ChaosCryptCore()
|
||||||
|
|
||||||
|
def go():
|
||||||
|
core.generate_keymaterial()
|
||||||
|
return go
|
||||||
|
|
||||||
|
|
||||||
|
def _keystream(core, password, length):
|
||||||
|
"""Pre-derive the password keystream so its cost is excluded from XOR loops."""
|
||||||
|
return core._derive_final_key(password, length)
|
||||||
|
|
||||||
|
|
||||||
|
def _build(spec):
|
||||||
|
"""Map a spec to (callable, unit_bytes, unit_ops)."""
|
||||||
|
op = spec["op"]
|
||||||
|
sz = spec.get("size", 0)
|
||||||
|
pwd = spec.get("password", "benchmark-password")
|
||||||
|
|
||||||
|
# ---- key setup ----------------------------------------------------
|
||||||
|
if op == "generate_keymaterial":
|
||||||
|
return _rotating_core(), None, 1
|
||||||
|
|
||||||
|
if op == "load_keys_from_text":
|
||||||
|
import tempfile
|
||||||
|
from chaoscrypt import ChaosCrypt
|
||||||
|
tmp = tempfile.mkdtemp()
|
||||||
|
path = os.path.join(tmp, "bench.key")
|
||||||
|
src = ChaosCrypt()
|
||||||
|
src.create_key(pwd, path)
|
||||||
|
with open(path, "r") as f:
|
||||||
|
text = f.read()
|
||||||
|
from chaoscrypt._core import ChaosCryptCore
|
||||||
|
fresh = ChaosCryptCore()
|
||||||
|
return (lambda: fresh.load_keys_from_text(text, pwd)), None, 1
|
||||||
|
|
||||||
|
core = _fixed_core()
|
||||||
|
|
||||||
|
# ---- text ---------------------------------------------------------
|
||||||
|
if op == "encrypt_text":
|
||||||
|
pt = _payload(sz).decode("ascii", "ignore")
|
||||||
|
return (lambda: core.encrypt_text(pt, pwd)), sz, 1
|
||||||
|
|
||||||
|
if op == "decrypt_text":
|
||||||
|
pt = _payload(sz).decode("ascii", "ignore")
|
||||||
|
ct = core.encrypt_text(pt, pwd)
|
||||||
|
return (lambda: core.decrypt_text(ct, pwd)), sz, 1
|
||||||
|
|
||||||
|
# ---- binary -------------------------------------------------------
|
||||||
|
if op == "encrypt_bytes":
|
||||||
|
data = _payload(sz)
|
||||||
|
return (lambda: core.encrypt_bytes(data, pwd)), sz, 1
|
||||||
|
|
||||||
|
if op == "decrypt_bytes":
|
||||||
|
data = _payload(sz)
|
||||||
|
ct = core.encrypt_bytes(data, pwd)
|
||||||
|
return (lambda: core.decrypt_bytes(ct, pwd)), sz, 1
|
||||||
|
|
||||||
|
# ---- internal stages, to show where the time actually goes ---------
|
||||||
|
if op == "stage_b64encode":
|
||||||
|
import base64
|
||||||
|
data = _payload(sz)
|
||||||
|
return (lambda: base64.b64encode(data)), sz, 1
|
||||||
|
|
||||||
|
if op == "stage_substitute":
|
||||||
|
text = _payload(sz).decode("ascii", "ignore")
|
||||||
|
return (lambda: core._substitute_letters(text, core.encrypt_map)), sz, 1
|
||||||
|
|
||||||
|
if op == "stage_flip":
|
||||||
|
text = _payload(sz).decode("ascii", "ignore")
|
||||||
|
return (lambda: core._apply_flip(text)), sz, 1
|
||||||
|
|
||||||
|
if op == "stage_xor_long":
|
||||||
|
text = _payload(sz).decode("ascii", "ignore")
|
||||||
|
key = core._get_dynamic_key(len(text))
|
||||||
|
return (lambda: core._xor_encrypt_with_key(text, key)), sz, 1
|
||||||
|
|
||||||
|
if op == "stage_derive_key":
|
||||||
|
return (lambda: core._derive_final_key(pwd, sz)), None, 1
|
||||||
|
|
||||||
|
# ---- key file handling --------------------------------------------
|
||||||
|
if op == "keyfile_encrypt":
|
||||||
|
blob = _payload(sz).decode("ascii", "ignore")
|
||||||
|
return (lambda: core._xor_encrypt_data(blob, pwd)), sz, 1
|
||||||
|
|
||||||
|
if op == "keyfile_obfuscate":
|
||||||
|
keys = {
|
||||||
|
"upper_mapping": core.upper_mapping,
|
||||||
|
"lower_mapping": core.lower_mapping,
|
||||||
|
"digit_mapping": core.digit_mapping,
|
||||||
|
"equal_mapping": core.equal_mapping,
|
||||||
|
"flip_pattern": core.flip_pattern,
|
||||||
|
"long_key": core.long_key,
|
||||||
|
"short_key": core.short_key,
|
||||||
|
}
|
||||||
|
return (lambda: core._obfuscate_keys(keys)), None, 1
|
||||||
|
|
||||||
|
# ---- overhead -----------------------------------------------------
|
||||||
|
if op == "random_4096_hex":
|
||||||
|
return (lambda: core._generate_long_key(4096)), None, 1
|
||||||
|
|
||||||
|
if op == "random_512_hex":
|
||||||
|
return (lambda: core._generate_short_key(512)), None, 1
|
||||||
|
|
||||||
|
if op == "shuffle_52":
|
||||||
|
return (lambda: (core._generate_random_alphabet(),
|
||||||
|
core._generate_random_alphabet(True))), None, 1
|
||||||
|
|
||||||
|
raise ValueError("unknown op: " + op)
|
||||||
|
|
||||||
|
|
||||||
|
# =================================================================== spec table
|
||||||
|
def make_specs(sizes, groups=None, root="."):
|
||||||
|
"""Build the task list. ``sizes`` is a list of (label, byte-size)."""
|
||||||
|
S = []
|
||||||
|
a = S.append
|
||||||
|
|
||||||
|
def add(op, name, group, size=0, extra=None):
|
||||||
|
spec = {"op": op, "name": name, "group": group, "size": size, "root": root}
|
||||||
|
if extra:
|
||||||
|
spec.update(extra)
|
||||||
|
a(spec)
|
||||||
|
|
||||||
|
# Key setup
|
||||||
|
add("generate_keymaterial", "generate_keymaterial()", "KeySetup")
|
||||||
|
add("load_keys_from_text", "load_keys_from_text()", "KeySetup")
|
||||||
|
add("keyfile_obfuscate", "obfuscate_keys()", "KeySetup")
|
||||||
|
add("keyfile_encrypt", "keyfile XOR wrap [1KB]", "KeySetup", KB)
|
||||||
|
for label, size in sizes:
|
||||||
|
add("random_4096_hex", "long key 4096 nibbles", "KeySetup")
|
||||||
|
break
|
||||||
|
add("random_512_hex", "short key 512 nibbles", "KeySetup")
|
||||||
|
add("shuffle_52", "alphabet shuffles (2x)", "KeySetup")
|
||||||
|
|
||||||
|
# Text
|
||||||
|
for label, size in sizes:
|
||||||
|
add("encrypt_text", f"encrypt_text [{label}]", "Text", size)
|
||||||
|
add("decrypt_text", f"decrypt_text [{label}]", "Text", size)
|
||||||
|
|
||||||
|
# Binary
|
||||||
|
for label, size in sizes:
|
||||||
|
add("encrypt_bytes", f"encrypt_bytes [{label}]", "Binary", size)
|
||||||
|
add("decrypt_bytes", f"decrypt_bytes [{label}]", "Binary", size)
|
||||||
|
|
||||||
|
# Internal stages (1 KiB only: they are per-byte costs)
|
||||||
|
add("stage_b64encode", "stage: Base64 encode [1KB]", "Overhead", KB)
|
||||||
|
add("stage_substitute", "stage: substitution [1KB]", "Overhead", KB)
|
||||||
|
add("stage_flip", "stage: case flip [1KB]", "Overhead", KB)
|
||||||
|
add("stage_xor_long", "stage: XOR long key [1KB]", "Overhead", KB)
|
||||||
|
add("stage_derive_key", "stage: derive keystream [1KB]", "Overhead", KB)
|
||||||
|
|
||||||
|
if groups:
|
||||||
|
want = {g.lower() for g in groups}
|
||||||
|
S = [s for s in S if s["group"].lower() in want]
|
||||||
|
return S
|
||||||
|
|
||||||
|
|
||||||
|
# =================================================================== reporting
|
||||||
|
def report(results, wall, cores, mem_note=None):
|
||||||
|
ok = [r for r in results if "error" not in r]
|
||||||
|
bad = [r for r in results if "error" in r]
|
||||||
|
groups = {}
|
||||||
|
for r in ok:
|
||||||
|
groups.setdefault(r["group"], []).append(r)
|
||||||
|
|
||||||
|
for g in GROUPS:
|
||||||
|
rows = groups.get(g)
|
||||||
|
if not rows:
|
||||||
|
continue
|
||||||
|
rows.sort(key=lambda r: r["sec_per_op"])
|
||||||
|
print("=" * 96)
|
||||||
|
print(f" {g}")
|
||||||
|
print("=" * 96)
|
||||||
|
print(f" {'operation':42s} {'ops/sec':>15s} {'us/op':>10s} "
|
||||||
|
f"{'MB/s':>10s} {'iters':>10s}")
|
||||||
|
print(" " + "-" * 92)
|
||||||
|
for r in rows:
|
||||||
|
mbs = f"{r['mb_per_sec']:10.2f}" if "mb_per_sec" in r else f"{'-':>10s}"
|
||||||
|
print(f" {r['name']:42s} {r['ops_per_sec']:15,.0f} "
|
||||||
|
f"{r['sec_per_op'] * 1e6:10.3f} {mbs} {r['iters']:10,d}")
|
||||||
|
print()
|
||||||
|
|
||||||
|
if bad:
|
||||||
|
print("=" * 96)
|
||||||
|
print(" FAILED")
|
||||||
|
print("=" * 96)
|
||||||
|
for r in bad:
|
||||||
|
print(f" {r['name']:42s} {r['error']}")
|
||||||
|
print()
|
||||||
|
|
||||||
|
print("=" * 96)
|
||||||
|
print(f" {len(ok)} OK | {len(bad)} failed | wall clock {wall:.2f}s | {cores} cores")
|
||||||
|
if mem_note:
|
||||||
|
print(f" {mem_note}")
|
||||||
|
print("=" * 96)
|
||||||
|
|
||||||
|
|
||||||
|
# =================================================================== main
|
||||||
|
def main(argv=None):
|
||||||
|
ap = argparse.ArgumentParser(
|
||||||
|
description="ChaosCrypt benchmark suite (multiprocess)",
|
||||||
|
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||||
|
)
|
||||||
|
ap.add_argument("--budget", type=float, default=DEFAULT_BUDGET,
|
||||||
|
help="seconds of measurement per task")
|
||||||
|
ap.add_argument("--repeats", type=int, default=DEFAULT_REPEATS,
|
||||||
|
help="take the best of N measurement rounds")
|
||||||
|
ap.add_argument("--sizes", default="64,1024",
|
||||||
|
help="comma-separated payload sizes in bytes")
|
||||||
|
ap.add_argument("--workers", type=int, default=0,
|
||||||
|
help="worker processes (0 = one per CPU core)")
|
||||||
|
ap.add_argument("--groups", default="",
|
||||||
|
help="comma-separated category filter, e.g. 'Text,Binary'")
|
||||||
|
args = ap.parse_args(argv)
|
||||||
|
|
||||||
|
root = os.getcwd()
|
||||||
|
sizes = []
|
||||||
|
for s in args.sizes.split(","):
|
||||||
|
s = s.strip()
|
||||||
|
if not s:
|
||||||
|
continue
|
||||||
|
n = int(s)
|
||||||
|
label = f"{n}B" if n < KB else (f"{n // KB}KB" if n < MB else f"{n // MB}MB")
|
||||||
|
sizes.append((label, n))
|
||||||
|
if not sizes:
|
||||||
|
ap.error("no valid --sizes given")
|
||||||
|
|
||||||
|
groups = [g.strip() for g in args.groups.split(",") if g.strip()]
|
||||||
|
specs = make_specs(sizes, groups or None, root=root)
|
||||||
|
if not specs:
|
||||||
|
ap.error("no benchmarks selected for the given --groups / --sizes")
|
||||||
|
cores = os.cpu_count() or 4
|
||||||
|
workers = args.workers or min(cores, len(specs))
|
||||||
|
|
||||||
|
print(f"[*] ChaosCrypt benchmark: {len(specs)} tasks / {workers} workers "
|
||||||
|
f"({cores} cores)", flush=True)
|
||||||
|
print(f"[*] budget {args.budget}s x {args.repeats} repeats, "
|
||||||
|
f"sizes {[l for l, _ in sizes]}"
|
||||||
|
+ (f", groups {groups}" if groups else "") + "\n", flush=True)
|
||||||
|
|
||||||
|
t0 = time.perf_counter()
|
||||||
|
results = []
|
||||||
|
with ProcessPoolExecutor(max_workers=workers) as ex:
|
||||||
|
futs = [ex.submit(run_spec, (s, args.budget, args.repeats)) for s in specs]
|
||||||
|
for i, f in enumerate(as_completed(futs), 1):
|
||||||
|
results.append(f.result())
|
||||||
|
print(f"\r {i}/{len(specs)}", end="", flush=True)
|
||||||
|
wall = time.perf_counter() - t0
|
||||||
|
print(f"\n[*] wall clock: {wall:.2f}s\n")
|
||||||
|
|
||||||
|
note = None
|
||||||
|
try:
|
||||||
|
import resource # POSIX only
|
||||||
|
ru = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
|
||||||
|
note = f"peak RSS {ru / 1024:.1f} MB"
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
report(results, wall, cores, note)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,554 @@
|
|||||||
|
"""
|
||||||
|
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,
|
||||||
|
ENCODINGS,
|
||||||
|
ENC_HEX,
|
||||||
|
ENC_BASE64,
|
||||||
|
DEFAULT_ENCODING,
|
||||||
|
MIDS,
|
||||||
|
MID_BYTES,
|
||||||
|
MID_HEX,
|
||||||
|
DEFAULT_MID,
|
||||||
|
MODE_REFERENCE,
|
||||||
|
MODE_FAST,
|
||||||
|
MODE_TURBO,
|
||||||
|
MODE_RAW,
|
||||||
|
MODES,
|
||||||
|
DEFAULT_MODE,
|
||||||
|
)
|
||||||
|
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__ = "4.2.6"
|
||||||
|
__author__ = "Dvs (DvsXT)"
|
||||||
|
__license__ = "MIT"
|
||||||
|
__all__ = [
|
||||||
|
"__version__",
|
||||||
|
"__author__",
|
||||||
|
"__license__",
|
||||||
|
"DEFAULT_KEY_FILE",
|
||||||
|
"KEYFILE_VERSION",
|
||||||
|
"MODE_REFERENCE",
|
||||||
|
"MODE_FAST",
|
||||||
|
"MODE_TURBO",
|
||||||
|
"MODE_RAW",
|
||||||
|
"MODES",
|
||||||
|
"ENCODINGS",
|
||||||
|
"ENC_HEX",
|
||||||
|
"ENC_BASE64",
|
||||||
|
"DEFAULT_ENCODING",
|
||||||
|
"MIDS",
|
||||||
|
"MID_BYTES",
|
||||||
|
"MID_HEX",
|
||||||
|
"DEFAULT_MID",
|
||||||
|
"DEFAULT_MODE",
|
||||||
|
"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,
|
||||||
|
mode: str = DEFAULT_MODE,
|
||||||
|
encoding: str = DEFAULT_ENCODING,
|
||||||
|
mid: str = DEFAULT_MID,
|
||||||
|
) -> None:
|
||||||
|
self.core = ChaosCryptCore(mode, encoding=encoding, mid=mid)
|
||||||
|
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"<ChaosCrypt {state} key_file={self.key_file!r}>"
|
||||||
|
|
||||||
|
# ==================================================================
|
||||||
|
# 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)
|
||||||
|
|
||||||
|
# The returned text is exactly what would have been written to a key
|
||||||
|
# file, so it carries the header too.
|
||||||
|
document = self.core._emit(text, "key")
|
||||||
|
self.key_password = key_password
|
||||||
|
return document
|
||||||
|
|
||||||
|
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)
|
||||||
|
|
||||||
|
# Every artefact carries a header, key files included. Writing the bare
|
||||||
|
# payload here would produce a file this library then refuses to load.
|
||||||
|
document = self.core._emit(encrypted, "key")
|
||||||
|
with open(target, 'w') as f:
|
||||||
|
f.write(document)
|
||||||
|
|
||||||
|
self.key_password = new_password
|
||||||
|
return target
|
||||||
|
|
||||||
|
# ==================================================================
|
||||||
|
# Performance settings
|
||||||
|
# ==================================================================
|
||||||
|
@property
|
||||||
|
def mode(self) -> str:
|
||||||
|
"""The active performance mode."""
|
||||||
|
return self.core.mode
|
||||||
|
|
||||||
|
@property
|
||||||
|
def encoding(self) -> str:
|
||||||
|
"""The active output encoding (used by turbo and raw)."""
|
||||||
|
return self.core.encoding
|
||||||
|
|
||||||
|
@property
|
||||||
|
def mid(self) -> str:
|
||||||
|
"""The active intermediate representation (used by turbo and raw)."""
|
||||||
|
return self.core.mid
|
||||||
|
|
||||||
|
def set_mid(self, mid: str) -> "ChaosCrypt":
|
||||||
|
"""Change the intermediate representation in place.
|
||||||
|
|
||||||
|
Only affects ``turbo`` and ``raw``; ``reference`` and ``fast`` are
|
||||||
|
character pipelines and always report ``hex``.
|
||||||
|
"""
|
||||||
|
self.core.mid = mid
|
||||||
|
return self
|
||||||
|
|
||||||
|
def set_encoding(self, encoding: str) -> "ChaosCrypt":
|
||||||
|
"""Change the output encoding in place.
|
||||||
|
|
||||||
|
Only affects ``turbo`` and ``raw``; ``reference`` and ``fast`` always
|
||||||
|
emit hex. Output decoded with the wrong encoding will fail rather than
|
||||||
|
silently produce garbage, so a ciphertext and its encoding must be kept
|
||||||
|
together.
|
||||||
|
"""
|
||||||
|
self.core.encoding = encoding
|
||||||
|
return self
|
||||||
|
|
||||||
|
# ==================================================================
|
||||||
|
# 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)
|
||||||
@@ -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())
|
||||||
+1899
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,348 @@
|
|||||||
|
"""
|
||||||
|
ChaosCrypt self-describing header.
|
||||||
|
|
||||||
|
Every key file and every ciphertext produced by this system begins with a
|
||||||
|
header that states exactly how the payload was produced. Nothing is inferred
|
||||||
|
from context, and nothing is accepted without a header.
|
||||||
|
|
||||||
|
Layout
|
||||||
|
------
|
||||||
|
|
||||||
|
b"69CES" magic bytes (hex 3639434553)
|
||||||
|
<BEGIN_MARKER> fixed hex marker (64 bytes)
|
||||||
|
{"kind": ..., ...} UTF-8 JSON configuration
|
||||||
|
<END_MARKER> fixed hex marker (64 bytes)
|
||||||
|
<payload> the key material or the ciphertext
|
||||||
|
|
||||||
|
The configuration JSON is complete on its own: it records the kind of payload,
|
||||||
|
the performance mode, whether the intermediate representation was bytes or hex,
|
||||||
|
the output encoding, the algorithm version, and the parameters needed to
|
||||||
|
reproduce the decryption path. A payload whose header is missing, truncated or
|
||||||
|
self-inconsistent is rejected rather than guessed at.
|
||||||
|
|
||||||
|
Rationale
|
||||||
|
---------
|
||||||
|
Earlier releases relied on the caller to remember which mode and encoding had
|
||||||
|
been used. That is a silent-corruption hazard: a ciphertext decrypted with the
|
||||||
|
wrong mode produces garbage that is indistinguishable from a wrong password.
|
||||||
|
Recording the parameters next to the ciphertext removes the ambiguity, and
|
||||||
|
rejecting headerless input removes the guesswork.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
from typing import Any, Dict, Optional
|
||||||
|
|
||||||
|
from .errors import (
|
||||||
|
ChaosCrypt_ERR_MissingMagicHeader_E017,
|
||||||
|
ChaosCrypt_ERR_MalformedHeader_E018,
|
||||||
|
)
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"ENCODING_TO_OUT",
|
||||||
|
"OUT_TO_ENCODING",
|
||||||
|
"DEFAULT_MID",
|
||||||
|
"FIELD_IS_OLD",
|
||||||
|
"FIELD_OLD_IS_KEY",
|
||||||
|
"build_legacy_header",
|
||||||
|
"is_legacy",
|
||||||
|
"MAGIC",
|
||||||
|
"MAGIC_HEX",
|
||||||
|
"MAGIC_LIST",
|
||||||
|
"BEGIN_MARKER",
|
||||||
|
"END_MARKER",
|
||||||
|
"HEADER_VERSION",
|
||||||
|
"build_header",
|
||||||
|
"read_header",
|
||||||
|
"strip_header",
|
||||||
|
"has_magic",
|
||||||
|
]
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Fixed values
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
#: Magic bytes at the very start of every ChaosCrypt artefact.
|
||||||
|
MAGIC = b"69CES"
|
||||||
|
|
||||||
|
#: The same magic as hex text and as a list of byte values, for callers that
|
||||||
|
#: find one of those representations more convenient.
|
||||||
|
MAGIC_HEX = "3639434553"
|
||||||
|
MAGIC_LIST = [54, 57, 67, 69, 83]
|
||||||
|
|
||||||
|
#: Marker that opens the configuration block. Fixed, recorded verbatim.
|
||||||
|
BEGIN_MARKER = (
|
||||||
|
"385aeff1f4179a744c8fb0c5ae4702d325f6230d059f4251135c2536409dee93"
|
||||||
|
)
|
||||||
|
|
||||||
|
#: Marker that closes the configuration block.
|
||||||
|
END_MARKER = (
|
||||||
|
"2025ea4e4b4b93803f2ccadeaf318d1957ce42ff5409410f660348be96a4c0f2"
|
||||||
|
)
|
||||||
|
|
||||||
|
#: Version of the header format itself, independent of the algorithm version.
|
||||||
|
HEADER_VERSION = 1
|
||||||
|
|
||||||
|
#: Values accepted for the ``kind`` field.
|
||||||
|
KIND_CIPHERTEXT = "ciphertext"
|
||||||
|
KIND_KEY = "key"
|
||||||
|
KINDS = (KIND_CIPHERTEXT, KIND_KEY)
|
||||||
|
|
||||||
|
#: Values accepted for the ``mid`` (intermediate representation) field.
|
||||||
|
MID_BYTES = "bt"
|
||||||
|
MID_HEX = "hex"
|
||||||
|
MIDS = (MID_BYTES, MID_HEX)
|
||||||
|
|
||||||
|
#: Default intermediate representation for the byte-pipeline modes.
|
||||||
|
DEFAULT_MID = MID_BYTES
|
||||||
|
|
||||||
|
#: Values accepted for the ``out`` (output encoding) field.
|
||||||
|
OUT_HEX = "hex"
|
||||||
|
OUT_BASE = "base"
|
||||||
|
OUTS = (OUT_HEX, OUT_BASE)
|
||||||
|
|
||||||
|
#: Mapping from the constructor's encoding names to the header's vocabulary.
|
||||||
|
#: The constructor accepts ENC_HEX/ENC_BASE64; the header records OUT_HEX/OUT_BASE.
|
||||||
|
ENCODING_TO_OUT = {
|
||||||
|
"hex": OUT_HEX,
|
||||||
|
"base64": OUT_BASE,
|
||||||
|
}
|
||||||
|
#: And the reverse, for reading a header back into a constructor value.
|
||||||
|
OUT_TO_ENCODING = {v: k for k, v in ENCODING_TO_OUT.items()}
|
||||||
|
|
||||||
|
#: Required fields in every configuration block. Missing any one of these makes
|
||||||
|
#: the header invalid; the header is never partially trusted.
|
||||||
|
#: Field marking an artefact as produced by the pre-header implementation.
|
||||||
|
#: When present and true, **every other configuration field is ignored**; the
|
||||||
|
#: artefact is decrypted by the legacy path (see ``_core``). It is optional: a
|
||||||
|
#: normal artefact does not carry it at all.
|
||||||
|
FIELD_IS_OLD = "is_old"
|
||||||
|
|
||||||
|
#: Field naming what a legacy artefact is: true for a key file, false for a
|
||||||
|
#: ciphertext. Only meaningful alongside ``is_old``. Optional.
|
||||||
|
FIELD_OLD_IS_KEY = "old_is_key"
|
||||||
|
|
||||||
|
REQUIRED_FIELDS = (
|
||||||
|
"kind",
|
||||||
|
"v",
|
||||||
|
"mode",
|
||||||
|
"mid",
|
||||||
|
"out",
|
||||||
|
"alg",
|
||||||
|
"kdf",
|
||||||
|
"keybits",
|
||||||
|
"ksum",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Building
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def build_header(config: Dict[str, Any]) -> str:
|
||||||
|
"""Render a full header for ``config``.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
config: The configuration dictionary. It must contain every name in
|
||||||
|
:data:`REQUIRED_FIELDS`.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The header as text, ready to be prefixed to a payload.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ChaosCrypt_ERR_MalformedHeader_E018: a required field is absent, or a
|
||||||
|
field holds a value outside its permitted set.
|
||||||
|
"""
|
||||||
|
# Legacy records carry only is_old and old_is_key; the strict field checks
|
||||||
|
# below do not apply to them.
|
||||||
|
legacy = bool(config.get(FIELD_IS_OLD))
|
||||||
|
|
||||||
|
if not legacy:
|
||||||
|
missing = [f for f in REQUIRED_FIELDS if f not in config]
|
||||||
|
if missing:
|
||||||
|
raise ChaosCrypt_ERR_MalformedHeader_E018(
|
||||||
|
detail="MissingConfigFields:" + ",".join(missing), code="E018"
|
||||||
|
)
|
||||||
|
|
||||||
|
if legacy:
|
||||||
|
body = json.dumps(config, ensure_ascii=False, sort_keys=True,
|
||||||
|
separators=(",", ":"))
|
||||||
|
return (MAGIC.decode("ascii") + BEGIN_MARKER + body + END_MARKER)
|
||||||
|
|
||||||
|
if config["kind"] not in KINDS:
|
||||||
|
raise ChaosCrypt_ERR_MalformedHeader_E018(
|
||||||
|
detail="BadKind:" + str(config["kind"]), code="E018"
|
||||||
|
)
|
||||||
|
if config["mid"] not in MIDS:
|
||||||
|
raise ChaosCrypt_ERR_MalformedHeader_E018(
|
||||||
|
detail="BadMid:" + str(config["mid"]), code="E018"
|
||||||
|
)
|
||||||
|
if config["out"] not in OUTS:
|
||||||
|
raise ChaosCrypt_ERR_MalformedHeader_E018(
|
||||||
|
detail="BadOut:" + str(config["out"]), code="E018"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Deterministic key order so identical configurations render identically.
|
||||||
|
body = json.dumps(config, ensure_ascii=False, sort_keys=True,
|
||||||
|
separators=(",", ":"))
|
||||||
|
|
||||||
|
return (
|
||||||
|
MAGIC.decode("ascii")
|
||||||
|
+ BEGIN_MARKER
|
||||||
|
+ body
|
||||||
|
+ END_MARKER
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def build_legacy_header(is_key: bool = False) -> str:
|
||||||
|
"""Render the minimal header used to wrap a pre-header artefact.
|
||||||
|
|
||||||
|
A legacy artefact has no header of its own, so one is synthesised before it
|
||||||
|
enters the normal decryption path. The synthesised header carries only the
|
||||||
|
two fields that matter -- ``is_old`` and ``old_is_key`` -- because once
|
||||||
|
``is_old`` is true every other field is ignored.
|
||||||
|
|
||||||
|
This keeps a single code path: the library always decrypts something that
|
||||||
|
has a header. Legacy support is a wrapper around that path, not a second
|
||||||
|
implementation of it.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
is_key: Whether the artefact is a key file rather than a ciphertext.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
A complete header, ready to be prefixed to a legacy payload.
|
||||||
|
"""
|
||||||
|
body = json.dumps(
|
||||||
|
{FIELD_IS_OLD: True, FIELD_OLD_IS_KEY: bool(is_key)},
|
||||||
|
ensure_ascii=False, sort_keys=True, separators=(",", ":"),
|
||||||
|
)
|
||||||
|
return MAGIC.decode("ascii") + BEGIN_MARKER + body + END_MARKER
|
||||||
|
|
||||||
|
|
||||||
|
def is_legacy(text: str) -> bool:
|
||||||
|
"""Whether ``text`` is a headed legacy artefact.
|
||||||
|
|
||||||
|
Returns ``False`` for anything that is not a parseable header, so callers
|
||||||
|
can use this as a test rather than a validator.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
cfg = read_header(text)
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
return bool(cfg.get(FIELD_IS_OLD))
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Parsing
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def has_magic(text: str) -> bool:
|
||||||
|
"""Whether ``text`` begins with the ChaosCrypt magic bytes."""
|
||||||
|
return text.startswith(MAGIC.decode("ascii"))
|
||||||
|
|
||||||
|
|
||||||
|
def read_header(text: str) -> Dict[str, Any]:
|
||||||
|
"""Parse the header from ``text`` and return its configuration.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ChaosCrypt_ERR_MissingMagicHeader_E017: ``text`` does not start with the
|
||||||
|
magic. Callers must not attempt to guess the format.
|
||||||
|
ChaosCrypt_ERR_MalformedHeader_E018: a marker is missing or the JSON is
|
||||||
|
invalid or incomplete.
|
||||||
|
"""
|
||||||
|
if not text:
|
||||||
|
raise ChaosCrypt_ERR_MissingMagicHeader_E017(
|
||||||
|
detail="EmptyInput", code="E017"
|
||||||
|
)
|
||||||
|
|
||||||
|
magic = MAGIC.decode("ascii")
|
||||||
|
if not text.startswith(magic):
|
||||||
|
raise ChaosCrypt_ERR_MissingMagicHeader_E017()
|
||||||
|
|
||||||
|
body_at = len(magic)
|
||||||
|
|
||||||
|
if not text.startswith(BEGIN_MARKER, body_at):
|
||||||
|
raise ChaosCrypt_ERR_MalformedHeader_E018(
|
||||||
|
detail="MissingBeginMarker", code="E018"
|
||||||
|
)
|
||||||
|
body_at += len(BEGIN_MARKER)
|
||||||
|
|
||||||
|
end_at = text.find(END_MARKER, body_at)
|
||||||
|
if end_at < 0:
|
||||||
|
raise ChaosCrypt_ERR_MalformedHeader_E018(
|
||||||
|
detail="MissingEndMarker", code="E018"
|
||||||
|
)
|
||||||
|
|
||||||
|
body = text[body_at:end_at]
|
||||||
|
try:
|
||||||
|
config = json.loads(body)
|
||||||
|
except Exception:
|
||||||
|
raise ChaosCrypt_ERR_MalformedHeader_E018(
|
||||||
|
detail="InvalidHeaderJson", code="E018"
|
||||||
|
)
|
||||||
|
|
||||||
|
if not isinstance(config, dict):
|
||||||
|
raise ChaosCrypt_ERR_MalformedHeader_E018(
|
||||||
|
detail="HeaderJsonNotObject", code="E018"
|
||||||
|
)
|
||||||
|
|
||||||
|
# A legacy artefact carries only is_old and old_is_key. Everything else is
|
||||||
|
# meaningless for it, so the required-field check is skipped entirely --
|
||||||
|
# requiring kind/mode/... here would reject the very artefacts this branch
|
||||||
|
# exists to read.
|
||||||
|
if config.get(FIELD_IS_OLD):
|
||||||
|
if FIELD_OLD_IS_KEY in config and not isinstance(
|
||||||
|
config[FIELD_OLD_IS_KEY], bool
|
||||||
|
):
|
||||||
|
raise ChaosCrypt_ERR_MalformedHeader_E018(
|
||||||
|
detail="OldIsKeyNotBoolean", code="E018"
|
||||||
|
)
|
||||||
|
return config
|
||||||
|
|
||||||
|
missing = [f for f in REQUIRED_FIELDS if f not in config]
|
||||||
|
if missing:
|
||||||
|
raise ChaosCrypt_ERR_MalformedHeader_E018(
|
||||||
|
detail="MissingConfigFields:" + ",".join(missing), code="E018"
|
||||||
|
)
|
||||||
|
|
||||||
|
return config
|
||||||
|
|
||||||
|
|
||||||
|
def _payload_offset(text: str) -> int:
|
||||||
|
"""Index at which the payload begins, or ``-1`` if the header is unusable.
|
||||||
|
|
||||||
|
Markers are located by index so no intermediate copy of the payload is
|
||||||
|
made. The payload can be tens of megabytes; slicing the whole string three
|
||||||
|
times, as an earlier version did, costs three full copies per call and shows
|
||||||
|
up directly in throughput.
|
||||||
|
"""
|
||||||
|
magic = MAGIC.decode("ascii")
|
||||||
|
if not text.startswith(magic):
|
||||||
|
return -1
|
||||||
|
body_at = len(magic)
|
||||||
|
if not text.startswith(BEGIN_MARKER, body_at):
|
||||||
|
return -1
|
||||||
|
body_at += len(BEGIN_MARKER)
|
||||||
|
end_at = text.find(END_MARKER, body_at)
|
||||||
|
if end_at < 0:
|
||||||
|
return -1
|
||||||
|
return end_at + len(END_MARKER)
|
||||||
|
|
||||||
|
|
||||||
|
def strip_header(text: str) -> str:
|
||||||
|
"""Return the payload that follows the header.
|
||||||
|
|
||||||
|
The header is validated on the way through, so a malformed header raises
|
||||||
|
rather than yielding a payload.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ChaosCrypt_ERR_MissingMagicHeader_E017: no magic present.
|
||||||
|
ChaosCrypt_ERR_MalformedHeader_E018: header could not be parsed.
|
||||||
|
"""
|
||||||
|
if not has_magic(text):
|
||||||
|
raise ChaosCrypt_ERR_MissingMagicHeader_E017()
|
||||||
|
read_header(text) # validate the record itself
|
||||||
|
offset = _payload_offset(text)
|
||||||
|
if offset < 0:
|
||||||
|
raise ChaosCrypt_ERR_MalformedHeader_E018(
|
||||||
|
detail="MissingEndMarker", code="E018"
|
||||||
|
)
|
||||||
|
return text[offset:] # a single slice
|
||||||
@@ -0,0 +1,687 @@
|
|||||||
|
"""
|
||||||
|
ChaosCrypt command line interface.
|
||||||
|
|
||||||
|
Invocation contract:
|
||||||
|
|
||||||
|
* ``chaoscrypt`` with no arguments launches the interactive TUI;
|
||||||
|
* ``chaoscrypt <command> ...`` 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__, MODES, DEFAULT_MODE,
|
||||||
|
ENCODINGS, DEFAULT_ENCODING, MIDS, DEFAULT_MID)
|
||||||
|
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_global_flags(parser: argparse.ArgumentParser) -> None:
|
||||||
|
"""Re-register the global output flags on a subcommand.
|
||||||
|
|
||||||
|
``--json`` and ``--quiet`` are also accepted before the subcommand. Adding
|
||||||
|
them here as well lets users write either form, which is what most people
|
||||||
|
reach for first::
|
||||||
|
|
||||||
|
chaoscrypt --json info -k my.key -P keypwd
|
||||||
|
chaoscrypt info -k my.key -P keypwd --json
|
||||||
|
|
||||||
|
The values are merged in :func:`main` by taking whichever was set.
|
||||||
|
"""
|
||||||
|
parser.add_argument(
|
||||||
|
"-j", "--json", action="store_true", default=False,
|
||||||
|
dest="json_local",
|
||||||
|
help="emit machine-readable JSON on stdout",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"-q", "--quiet", action="store_true", default=False,
|
||||||
|
dest="quiet_local",
|
||||||
|
help="suppress non-essential human-readable output",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--mode", choices=MODES, default=None, dest="mode_local", metavar="MODE",
|
||||||
|
help="performance mode: reference / fast / turbo / raw",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--encoding", choices=ENCODINGS, default=None, dest="encoding_local",
|
||||||
|
metavar="ENC", help="output encoding for turbo/raw: hex / base64",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--mid", choices=MIDS, default=None, dest="mid_local", metavar="MID",
|
||||||
|
help="intermediate representation for turbo/raw: bt / hex",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
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",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--mid", choices=MIDS, default=None, metavar="MID",
|
||||||
|
help=(
|
||||||
|
"intermediate representation for turbo/raw: 'bt' (bytes, default, "
|
||||||
|
"2.00x expansion) or 'hex' (hexadecimal text, ~4x). Ignored by "
|
||||||
|
"reference/fast."
|
||||||
|
),
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--encoding", choices=ENCODINGS, default=None, metavar="ENC",
|
||||||
|
help=(
|
||||||
|
"output encoding for turbo/raw: 'hex' (2.00x expansion) or "
|
||||||
|
"'base64' (1.33x). Ignored by reference/fast, which always emit "
|
||||||
|
f"hex. Default: {DEFAULT_ENCODING}"
|
||||||
|
),
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--mode", choices=MODES, default=None, metavar="MODE",
|
||||||
|
help=(
|
||||||
|
"performance mode. "
|
||||||
|
"'reference' is the original algorithm (slowest, baseline); "
|
||||||
|
"'fast' is bit-for-bit identical to it but uses C-level bulk "
|
||||||
|
"operations; 'turbo' derives the keystream with SHAKE256 and is "
|
||||||
|
"far faster, but its ciphertexts are not interchangeable with the "
|
||||||
|
f"other two. Default: {DEFAULT_MODE}"
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
sub = parser.add_subparsers(dest="command", metavar="<command>")
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------ keygen
|
||||||
|
p_keygen = sub.add_parser(
|
||||||
|
"keygen", help="generate a new key file",
|
||||||
|
description="Generate a new ChaosCrypt key file.",
|
||||||
|
)
|
||||||
|
_add_global_flags(p_keygen)
|
||||||
|
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.",
|
||||||
|
)
|
||||||
|
_add_global_flags(p_enc)
|
||||||
|
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.",
|
||||||
|
)
|
||||||
|
_add_global_flags(p_dec)
|
||||||
|
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="<action>")
|
||||||
|
|
||||||
|
p_fe = file_sub.add_parser("encrypt", help="encrypt a file to .cc")
|
||||||
|
_add_global_flags(p_fe)
|
||||||
|
p_fe.add_argument("src", help="source file")
|
||||||
|
p_fe.add_argument(
|
||||||
|
"-o", "--out", dest="out_file", metavar="PATH",
|
||||||
|
help="output path (default: <src>.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")
|
||||||
|
_add_global_flags(p_fd)
|
||||||
|
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.",
|
||||||
|
)
|
||||||
|
_add_global_flags(p_info)
|
||||||
|
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.",
|
||||||
|
)
|
||||||
|
_add_global_flags(p_chpwd)
|
||||||
|
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(mode=args.mode, encoding=args.encoding, mid=args.mid)
|
||||||
|
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(mode=args.mode, encoding=args.encoding, mid=args.mid)
|
||||||
|
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(mode=args.mode, encoding=args.encoding, mid=args.mid)
|
||||||
|
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(mode=args.mode, encoding=args.encoding, mid=args.mid)
|
||||||
|
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"<hidden, {len(info[k])} chars>"
|
||||||
|
|
||||||
|
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(mode=args.mode, encoding=args.encoding, mid=args.mid)
|
||||||
|
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)
|
||||||
|
|
||||||
|
# `--json` / `--quiet` are accepted both before and after the subcommand.
|
||||||
|
# The subparser writes to separate destinations so that an unset
|
||||||
|
# subcommand flag cannot clobber an explicitly set global one; the two are
|
||||||
|
# merged here.
|
||||||
|
args.json = bool(getattr(args, "json", False)
|
||||||
|
or getattr(args, "json_local", False))
|
||||||
|
args.quiet = bool(getattr(args, "quiet", False)
|
||||||
|
or getattr(args, "quiet_local", False))
|
||||||
|
args.mode = (getattr(args, "mode", None)
|
||||||
|
or getattr(args, "mode_local", None)
|
||||||
|
or DEFAULT_MODE)
|
||||||
|
args.encoding = (getattr(args, "encoding", None)
|
||||||
|
or getattr(args, "encoding_local", None)
|
||||||
|
or DEFAULT_ENCODING)
|
||||||
|
args.mid = (getattr(args, "mid", None)
|
||||||
|
or getattr(args, "mid_local", None)
|
||||||
|
or DEFAULT_MID)
|
||||||
|
|
||||||
|
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()
|
||||||
@@ -0,0 +1,159 @@
|
|||||||
|
"""
|
||||||
|
Unified error types for ChaosCrypt.
|
||||||
|
|
||||||
|
Every failure raised by this library is a subclass of :class:`ChaosCryptError`,
|
||||||
|
and every instance renders as::
|
||||||
|
|
||||||
|
ChaosCrypt_ERR_<short description>_<code>
|
||||||
|
|
||||||
|
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",
|
||||||
|
"ChaosCrypt_ERR_MissingMagicHeader_E017",
|
||||||
|
"ChaosCrypt_ERR_MalformedHeader_E018",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
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_<detail>_<code>`` 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.",
|
||||||
|
)
|
||||||
|
|
||||||
|
ChaosCrypt_ERR_MissingMagicHeader_E017 = _define(
|
||||||
|
"ChaosCrypt_ERR_MissingMagicHeader_E017", "MissingMagicHeader", "E017",
|
||||||
|
"The input does not begin with the ChaosCrypt magic header. Every key file "
|
||||||
|
"and ciphertext produced by this system carries a self-describing header; "
|
||||||
|
"input without one is rejected outright.",
|
||||||
|
)
|
||||||
|
ChaosCrypt_ERR_MalformedHeader_E018 = _define(
|
||||||
|
"ChaosCrypt_ERR_MalformedHeader_E018", "MalformedHeader", "E018",
|
||||||
|
"The ChaosCrypt header is present but could not be parsed: a marker is "
|
||||||
|
"missing, the JSON is invalid, or a required field is absent.",
|
||||||
|
)
|
||||||
@@ -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()
|
||||||
@@ -0,0 +1,279 @@
|
|||||||
|
"""
|
||||||
|
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_mode": {"en": "Performance mode", "zh": "性能模式"},
|
||||||
|
"menu_encoding": {"en": "Output encoding", "zh": "输出编码"},
|
||||||
|
"info_encoding": {"en": "Output encoding", "zh": "输出编码"},
|
||||||
|
"encoding_prompt": {"en": "Select output encoding", "zh": "请选择输出编码"},
|
||||||
|
"encoding_hex_desc": {
|
||||||
|
"en": "hex - 2 characters per byte, 2.00x expansion",
|
||||||
|
"zh": "hex - 每字节 2 字符,膨胀 2.00 倍",
|
||||||
|
},
|
||||||
|
"encoding_base64_desc": {
|
||||||
|
"en": "base64 - 4 characters per 3 bytes, 1.33x expansion",
|
||||||
|
"zh": "base64 - 每 3 字节 4 字符,膨胀 1.33 倍",
|
||||||
|
},
|
||||||
|
"encoding_changed": {"en": "Encoding set to", "zh": "输出编码已设为"},
|
||||||
|
"encoding_note": {
|
||||||
|
"en": "(only affects turbo and raw; reference and fast always emit hex)",
|
||||||
|
"zh": "(仅影响 turbo 与 raw;reference 与 fast 恒为 hex)",
|
||||||
|
},
|
||||||
|
"info_mode": {"en": "Performance mode", "zh": "性能模式"},
|
||||||
|
"mode_prompt": {
|
||||||
|
"en": "Select performance mode",
|
||||||
|
"zh": "请选择性能模式",
|
||||||
|
},
|
||||||
|
"mode_reference_desc": {
|
||||||
|
"en": "reference - original algorithm, slowest, ciphertext compatible",
|
||||||
|
"zh": "reference - 原版算法,最慢,密文兼容",
|
||||||
|
},
|
||||||
|
"mode_fast_desc": {
|
||||||
|
"en": "fast - identical ciphertext, C-level bulk operations",
|
||||||
|
"zh": "fast - 密文相同,C 级批量运算",
|
||||||
|
},
|
||||||
|
"mode_turbo_desc": {
|
||||||
|
"en": "turbo - SHAKE256 keystream, much faster, own ciphertext format",
|
||||||
|
"zh": "turbo - SHAKE256 密钥流,极快,独立密文格式",
|
||||||
|
},
|
||||||
|
"mode_raw_desc": {
|
||||||
|
"en": "raw - bytes throughout, fastest, smallest output, weakest",
|
||||||
|
"zh": "raw - 全程字节,最快,输出最小,强度最低",
|
||||||
|
},
|
||||||
|
"mode_changed": {"en": "Mode set to", "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())
|
||||||
@@ -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.
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""Test-vector loading helper.
|
||||||
|
|
||||||
|
Mirrors the loader used by the sibling ``purepycrypto`` project so the two
|
||||||
|
repositories share the same layout convention: a ``vectors/`` directory next to
|
||||||
|
the tests, one JSON file per subject, loaded by name.
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
|
||||||
|
VEC_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "vectors")
|
||||||
|
|
||||||
|
|
||||||
|
def path_for(name):
|
||||||
|
"""Absolute path of ``vectors/<name>.json``."""
|
||||||
|
return os.path.join(VEC_DIR, name + ".json")
|
||||||
|
|
||||||
|
|
||||||
|
def load(name):
|
||||||
|
"""Load ``vectors/<name>.json`` and return the parsed dictionary."""
|
||||||
|
with open(path_for(name), "r", encoding="utf-8") as f:
|
||||||
|
return json.load(f)
|
||||||
|
|
||||||
|
|
||||||
|
def available():
|
||||||
|
"""Names of every vector file present, without the ``.json`` suffix."""
|
||||||
|
if not os.path.isdir(VEC_DIR):
|
||||||
|
return []
|
||||||
|
return sorted(
|
||||||
|
f[:-5] for f in os.listdir(VEC_DIR) if f.endswith(".json")
|
||||||
|
)
|
||||||
@@ -0,0 +1,712 @@
|
|||||||
|
"""
|
||||||
|
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_payload_is_hex(self, loaded):
|
||||||
|
from chaoscrypt._header import strip_header
|
||||||
|
ct = strip_header(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_every_ciphertext_carries_a_header(self, loaded):
|
||||||
|
from chaoscrypt._header import MAGIC, read_header
|
||||||
|
ct = loaded.encrypt("data", USER_PWD)
|
||||||
|
assert ct.startswith(MAGIC.decode())
|
||||||
|
cfg = read_header(ct)
|
||||||
|
assert cfg["kind"] == "ciphertext"
|
||||||
|
|
||||||
|
def test_headerless_ciphertext_rejected(self, loaded):
|
||||||
|
"""Input without the magic header is not a CES artefact."""
|
||||||
|
with pytest.raises(ChaosCryptError) as ei:
|
||||||
|
loaded.decrypt("zzzz-not-hex", USER_PWD)
|
||||||
|
assert ei.value.code == "E017"
|
||||||
|
|
||||||
|
def test_headerless_odd_length_rejected(self, loaded):
|
||||||
|
with pytest.raises(ChaosCryptError) as ei:
|
||||||
|
loaded.decrypt("abc", USER_PWD)
|
||||||
|
assert ei.value.code == "E017"
|
||||||
|
|
||||||
|
def test_empty_ciphertext_rejected(self, loaded):
|
||||||
|
with pytest.raises(ChaosCryptError) as ei:
|
||||||
|
loaded.decrypt("", USER_PWD)
|
||||||
|
assert ei.value.code == "E009"
|
||||||
|
|
||||||
|
def test_malformed_payload_rejected(self, loaded):
|
||||||
|
"""A valid header with a broken payload fails on the payload."""
|
||||||
|
from chaoscrypt._header import build_header
|
||||||
|
bad = build_header(loaded.core.header_config("ciphertext")) + "zzzz"
|
||||||
|
with pytest.raises(ChaosCryptError) as ei:
|
||||||
|
loaded.decrypt(bad, USER_PWD)
|
||||||
|
assert ei.value.code == "E010"
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 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_key_file_carries_a_header(self, tmp_path):
|
||||||
|
from chaoscrypt._header import MAGIC, read_header
|
||||||
|
path = str(tmp_path / "hdr.key")
|
||||||
|
ChaosCrypt().create_key(KEY_PWD, path)
|
||||||
|
text = open(path, encoding="utf-8").read()
|
||||||
|
assert text.startswith(MAGIC.decode())
|
||||||
|
cfg = read_header(text)
|
||||||
|
assert cfg["kind"] == "key"
|
||||||
|
assert cfg["alg"] == "chaoscrypt"
|
||||||
|
|
||||||
|
def test_headerless_key_file_rejected(self, tmp_path):
|
||||||
|
path = tmp_path / "bare.key"
|
||||||
|
path.write_text("deadbeef" * 200, encoding="utf-8")
|
||||||
|
with pytest.raises(ChaosCryptError) as ei:
|
||||||
|
ChaosCrypt().load(str(path), KEY_PWD)
|
||||||
|
assert ei.value.code == "E017"
|
||||||
|
|
||||||
|
def test_key_file_rejected_as_ciphertext(self, tmp_path):
|
||||||
|
path = str(tmp_path / "k2.key")
|
||||||
|
ChaosCrypt().create_key(KEY_PWD, path)
|
||||||
|
text = open(path, encoding="utf-8").read()
|
||||||
|
cc = ChaosCrypt()
|
||||||
|
cc.load(path, KEY_PWD)
|
||||||
|
with pytest.raises(ChaosCryptError) as ei:
|
||||||
|
cc.decrypt(text, USER_PWD)
|
||||||
|
assert ei.value.code == "E018"
|
||||||
|
|
||||||
|
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 == "E017"
|
||||||
|
|
||||||
|
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 in ("E002", "E017")
|
||||||
|
|
||||||
|
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):
|
||||||
|
from chaoscrypt._header import MAGIC, read_header
|
||||||
|
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"
|
||||||
|
assert text.startswith(MAGIC.decode())
|
||||||
|
assert read_header(text)["kind"] == "key"
|
||||||
|
|
||||||
|
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_encrypted_file_carries_a_header(self, loaded, tmp_path):
|
||||||
|
from chaoscrypt._header import MAGIC
|
||||||
|
src = tmp_path / "h.txt"
|
||||||
|
src.write_text("header check", encoding="utf-8")
|
||||||
|
out = loaded.encrypt_file(str(src), USER_PWD)
|
||||||
|
assert open(out, encoding="utf-8").read().startswith(MAGIC.decode())
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
The artefact carries a header, so the payload is taken from it first;
|
||||||
|
the chain that follows is the original one, unchanged.
|
||||||
|
"""
|
||||||
|
from chaoscrypt._header import strip_header
|
||||||
|
text = "compat check compatibility"
|
||||||
|
ct = strip_header(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):
|
||||||
|
"""The payload of a new key file must satisfy the original format."""
|
||||||
|
from chaoscrypt._header import strip_header
|
||||||
|
_, path = keyfile
|
||||||
|
core = ChaosCryptCore()
|
||||||
|
with open(path, "r") as f:
|
||||||
|
enc = strip_header(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):
|
||||||
|
from chaoscrypt import __version__
|
||||||
|
r = self._run(["--version"])
|
||||||
|
assert r.returncode == 0
|
||||||
|
assert __version__ 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_json_flag_accepted_before_and_after_subcommand(self, tmp_path):
|
||||||
|
"""--json must work in either position, not only before the subcommand."""
|
||||||
|
kf = str(tmp_path / "pos.key")
|
||||||
|
self._run(["keygen", "-k", kf, "-P", KEY_PWD])
|
||||||
|
|
||||||
|
for args in (
|
||||||
|
["--json", "info", "-k", kf, "-P", KEY_PWD],
|
||||||
|
["info", "-k", kf, "-P", KEY_PWD, "--json"],
|
||||||
|
):
|
||||||
|
r = self._run(args)
|
||||||
|
assert r.returncode == 0, r.stderr
|
||||||
|
assert json.loads(r.stdout)["ok"] is True, args
|
||||||
|
|
||||||
|
def test_quiet_flag_accepted_before_and_after_subcommand(self, tmp_path):
|
||||||
|
kf = str(tmp_path / "q.key")
|
||||||
|
self._run(["keygen", "-k", kf, "-P", KEY_PWD])
|
||||||
|
|
||||||
|
for args in (
|
||||||
|
["--quiet", "encrypt", "x", "-p", USER_PWD, "-k", kf, "-P", KEY_PWD],
|
||||||
|
["encrypt", "x", "-p", USER_PWD, "-k", kf, "-P", KEY_PWD, "--quiet"],
|
||||||
|
):
|
||||||
|
r = self._run(args)
|
||||||
|
assert r.returncode == 0, r.stderr
|
||||||
|
assert r.stdout.strip() == "", args
|
||||||
|
|
||||||
|
def test_plain_output_is_bare_ciphertext(self, tmp_path):
|
||||||
|
"""Without --json the artefact goes to stdout on its own.
|
||||||
|
|
||||||
|
"On its own" means no JSON envelope around it. The artefact does contain
|
||||||
|
the word ``ciphertext`` inside its header's ``kind`` field, so the check
|
||||||
|
is for the envelope rather than for the word.
|
||||||
|
"""
|
||||||
|
from chaoscrypt._header import MAGIC, strip_header
|
||||||
|
kf = str(tmp_path / "p.key")
|
||||||
|
self._run(["keygen", "-k", kf, "-P", KEY_PWD])
|
||||||
|
r = self._run(["encrypt", "x", "-p", USER_PWD, "-k", kf, "-P", KEY_PWD])
|
||||||
|
out = r.stdout.strip()
|
||||||
|
|
||||||
|
assert out
|
||||||
|
assert not out.startswith("{"), "unexpected JSON envelope"
|
||||||
|
assert out.startswith(MAGIC.decode())
|
||||||
|
int(strip_header(out), 16)
|
||||||
|
|
||||||
|
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):
|
||||||
|
"""Key material moves between instances through the key file scheme."""
|
||||||
|
from chaoscrypt._header import build_legacy_header
|
||||||
|
c = ChaosCryptCore()
|
||||||
|
data = c.generate_keymaterial()
|
||||||
|
ct = c.encrypt_text("core direct", USER_PWD)
|
||||||
|
assert c.decrypt_text(ct, USER_PWD) == "core direct"
|
||||||
|
|
||||||
|
# load_keys_from_text now requires a header, as every artefact does.
|
||||||
|
# A minimal one is enough when the material is already at hand.
|
||||||
|
text = build_legacy_header(is_key=True) + \
|
||||||
|
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
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""
|
||||||
|
Legacy interoperability: deliberately removed.
|
||||||
|
|
||||||
|
Until 4.2.6 the library could exchange key files and ciphertexts with the
|
||||||
|
original single-file script. That interoperability was given up when the
|
||||||
|
self-describing header was introduced: every artefact now begins with a magic
|
||||||
|
value, two fixed markers and a configuration record, and a reader rejects
|
||||||
|
anything without one.
|
||||||
|
|
||||||
|
The break is intentional in both directions:
|
||||||
|
|
||||||
|
* a key file written by this version cannot be read by the original script;
|
||||||
|
* a ciphertext written by this version cannot be decrypted by the original
|
||||||
|
script;
|
||||||
|
* artefacts written before the header existed are rejected with
|
||||||
|
``E017 MissingMagicHeader``.
|
||||||
|
|
||||||
|
Reading old material is still possible through the compatibility API, which
|
||||||
|
synthesises a minimal header and then uses the ordinary path. That is covered
|
||||||
|
by ``test_header.py``; there is nothing left to assert here.
|
||||||
|
|
||||||
|
The original implementation is kept under ``legacy/`` for reference only.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.skip(reason="interoperability with pre-4.2.6 artefacts was "
|
||||||
|
"intentionally dropped when the header was added; "
|
||||||
|
"see the compatibility API instead")
|
||||||
|
def test_legacy_interop_removed():
|
||||||
|
"""Placeholder so the removal shows up in the test report."""
|
||||||
|
assert True
|
||||||
@@ -0,0 +1,416 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""
|
||||||
|
Performance-mode tests.
|
||||||
|
|
||||||
|
Four modes exist:
|
||||||
|
|
||||||
|
reference the original algorithm, character pipeline
|
||||||
|
fast same algorithm, bulk-operation implementation, identical output
|
||||||
|
turbo SHAKE256 keystream, byte pipeline, own ciphertext format
|
||||||
|
raw byte pipeline with the long-key layer retained
|
||||||
|
|
||||||
|
``reference`` and ``fast`` produce indistinguishable ciphertexts and always use
|
||||||
|
hex. ``turbo`` and ``raw`` accept either ``hex`` or ``base64`` output, and
|
||||||
|
either a ``bt`` (bytes) or ``hex`` intermediate representation.
|
||||||
|
|
||||||
|
Every artefact carries a self-describing header, so anything that inspects the
|
||||||
|
ciphertext body strips it first, and anything that feeds headerless input
|
||||||
|
expects ``E017``.
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from chaoscrypt import (
|
||||||
|
ChaosCrypt,
|
||||||
|
ChaosCryptCore,
|
||||||
|
ChaosCryptError,
|
||||||
|
MODES,
|
||||||
|
MODE_REFERENCE,
|
||||||
|
MODE_FAST,
|
||||||
|
MODE_TURBO,
|
||||||
|
MODE_RAW,
|
||||||
|
DEFAULT_MODE,
|
||||||
|
ENCODINGS,
|
||||||
|
ENC_HEX,
|
||||||
|
ENC_BASE64,
|
||||||
|
MIDS,
|
||||||
|
MID_BYTES,
|
||||||
|
MID_HEX,
|
||||||
|
)
|
||||||
|
from chaoscrypt._header import MAGIC, strip_header, read_header
|
||||||
|
|
||||||
|
from ._vectors import load
|
||||||
|
|
||||||
|
KEY_PWD = "mode-key-password"
|
||||||
|
USER_PWD = "mode-user-password"
|
||||||
|
|
||||||
|
SAMPLES = [
|
||||||
|
"hello",
|
||||||
|
"hello world",
|
||||||
|
"emoji test",
|
||||||
|
"a",
|
||||||
|
"x" * 300,
|
||||||
|
"Mixed 123!@#$%^&*",
|
||||||
|
"line1\nline2\ttabbed",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _payload(text: str) -> str:
|
||||||
|
"""The payload of an artefact, with its self-describing header removed."""
|
||||||
|
return strip_header(text)
|
||||||
|
|
||||||
|
|
||||||
|
def _core(mode, vectors, enc="hex", mid="bt"):
|
||||||
|
"""A ChaosCryptCore in ``mode`` carrying the frozen key material."""
|
||||||
|
km = vectors["key_material"]
|
||||||
|
c = ChaosCryptCore(mode, "hash", enc, mid)
|
||||||
|
c.upper_mapping = km["upper_mapping"]
|
||||||
|
c.lower_mapping = km["lower_mapping"]
|
||||||
|
c.digit_mapping = km["digit_mapping"]
|
||||||
|
c.equal_mapping = km["equal_mapping"]
|
||||||
|
c.flip_pattern = km["flip_pattern"]
|
||||||
|
c.long_key = km["long_key"]
|
||||||
|
c.short_key = km["short_key"]
|
||||||
|
c.digit_reverse = {v: k for k, v in c.digit_mapping.items()}
|
||||||
|
c.equal_reverse = {v: k for k, v in c.equal_mapping.items()}
|
||||||
|
c._build_maps()
|
||||||
|
c.keys_loaded = True
|
||||||
|
return c
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module")
|
||||||
|
def vectors():
|
||||||
|
return load("chaoscrypt_reference")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module")
|
||||||
|
def cores(vectors):
|
||||||
|
return {m: _core(m, vectors) for m in MODES}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def keyfile(tmp_path):
|
||||||
|
path = str(tmp_path / "modes.key")
|
||||||
|
ChaosCrypt().create_key(KEY_PWD, path)
|
||||||
|
return path
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Mode surface
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
class TestModeSurface:
|
||||||
|
def test_all_four_modes_are_exported(self):
|
||||||
|
assert MODES == (MODE_REFERENCE, MODE_FAST, MODE_TURBO, MODE_RAW)
|
||||||
|
|
||||||
|
def test_default_mode_is_fast(self):
|
||||||
|
assert DEFAULT_MODE == MODE_FAST
|
||||||
|
|
||||||
|
def test_core_defaults_to_the_default_mode(self):
|
||||||
|
assert ChaosCryptCore().mode == DEFAULT_MODE
|
||||||
|
|
||||||
|
def test_unknown_mode_is_rejected(self):
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
ChaosCryptCore("turbo-charged")
|
||||||
|
|
||||||
|
def test_valid_mode_is_accepted(self):
|
||||||
|
for m in MODES:
|
||||||
|
assert ChaosCryptCore(m).mode == m
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# reference and fast
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
class TestReferenceAndFast:
|
||||||
|
def test_reference_reproduces_frozen_vectors(self, cores, vectors):
|
||||||
|
core = cores[MODE_REFERENCE]
|
||||||
|
pwd = vectors["passwords"]["user_password"]
|
||||||
|
for case in vectors["cases"]:
|
||||||
|
if case.get("mode", "fast") not in ("reference", "fast"):
|
||||||
|
continue
|
||||||
|
got = _payload(core.encrypt_text(case["plaintext"], pwd))
|
||||||
|
want = _payload(case["ciphertext"])
|
||||||
|
assert got == want, f"reference drifted for {case['id']}"
|
||||||
|
|
||||||
|
def test_fast_is_indistinguishable_from_reference(self, cores, vectors):
|
||||||
|
"""The whole point of `fast`: same bytes, less time."""
|
||||||
|
pwd = vectors["passwords"]["user_password"]
|
||||||
|
for case in vectors["cases"]:
|
||||||
|
a = cores[MODE_REFERENCE].encrypt_text(case["plaintext"], pwd)
|
||||||
|
b = cores[MODE_FAST].encrypt_text(case["plaintext"], pwd)
|
||||||
|
# payloads identical; only the recorded mode differs
|
||||||
|
assert _payload(a) == _payload(b), case["id"]
|
||||||
|
assert read_header(a)["mode"] == MODE_REFERENCE
|
||||||
|
assert read_header(b)["mode"] == MODE_FAST
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("text", SAMPLES)
|
||||||
|
def test_fast_matches_reference_on_samples(self, cores, text):
|
||||||
|
a = _payload(cores[MODE_REFERENCE].encrypt_text(text, USER_PWD))
|
||||||
|
b = _payload(cores[MODE_FAST].encrypt_text(text, USER_PWD))
|
||||||
|
assert a == b
|
||||||
|
|
||||||
|
def test_agree_on_large_input(self, cores):
|
||||||
|
big = "A" * 40_000
|
||||||
|
a = _payload(cores[MODE_REFERENCE].encrypt_text(big, USER_PWD))
|
||||||
|
b = _payload(cores[MODE_FAST].encrypt_text(big, USER_PWD))
|
||||||
|
assert a == b
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("mode", [MODE_REFERENCE, MODE_FAST])
|
||||||
|
def test_ciphertext_payload_is_hex(self, cores, mode):
|
||||||
|
int(_payload(cores[mode].encrypt_text("data", USER_PWD)), 16)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# turbo and raw
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
class TestTurboAndRaw:
|
||||||
|
@pytest.mark.parametrize("mode", [MODE_TURBO, MODE_RAW])
|
||||||
|
@pytest.mark.parametrize("text", SAMPLES)
|
||||||
|
def test_roundtrip(self, cores, mode, text):
|
||||||
|
ct = cores[mode].encrypt_text(text, USER_PWD)
|
||||||
|
assert cores[mode].decrypt_text(ct, USER_PWD) == text
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("mode", [MODE_TURBO, MODE_RAW])
|
||||||
|
@pytest.mark.parametrize("size", [1, 2, 255, 4096])
|
||||||
|
def test_binary_roundtrip(self, cores, mode, size):
|
||||||
|
raw = os.urandom(size)
|
||||||
|
ct = cores[mode].encrypt_bytes(raw, USER_PWD)
|
||||||
|
assert cores[mode].decrypt_bytes(ct, USER_PWD) == raw
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("mode", MODES)
|
||||||
|
def test_every_ciphertext_carries_a_header(self, cores, mode):
|
||||||
|
ct = cores[mode].encrypt_text("data", USER_PWD)
|
||||||
|
assert ct.startswith(MAGIC.decode())
|
||||||
|
assert read_header(ct)["kind"] == "ciphertext"
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("mode", [MODE_TURBO, MODE_RAW])
|
||||||
|
def test_wrong_password_fails(self, cores, mode):
|
||||||
|
ct = cores[mode].encrypt_text("secret", USER_PWD)
|
||||||
|
with pytest.raises(ChaosCryptError):
|
||||||
|
cores[mode].decrypt_text(ct, "wrong-password")
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Intermediates and encodings
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
class TestIntermediatesAndEncodings:
|
||||||
|
@pytest.mark.parametrize("mode", [MODE_TURBO, MODE_RAW])
|
||||||
|
@pytest.mark.parametrize("mid", MIDS)
|
||||||
|
@pytest.mark.parametrize("enc", ENCODINGS)
|
||||||
|
def test_all_combinations_round_trip(self, vectors, mode, mid, enc):
|
||||||
|
c = _core(mode, vectors, enc, mid)
|
||||||
|
for text in SAMPLES:
|
||||||
|
ct = c.encrypt_text(text, USER_PWD)
|
||||||
|
assert c.decrypt_text(ct, USER_PWD) == text, (mode, mid, enc)
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("mode", [MODE_TURBO, MODE_RAW])
|
||||||
|
@pytest.mark.parametrize("mid", MIDS)
|
||||||
|
def test_binary_round_trip_all_mids(self, vectors, mode, mid):
|
||||||
|
c = _core(mode, vectors, "hex", mid)
|
||||||
|
raw = os.urandom(2_000)
|
||||||
|
assert c.decrypt_bytes(c.encrypt_bytes(raw, USER_PWD), USER_PWD) == raw
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("mid", MIDS)
|
||||||
|
def test_header_records_the_mid(self, vectors, mid):
|
||||||
|
for mode in (MODE_TURBO, MODE_RAW):
|
||||||
|
c = _core(mode, vectors, "hex", mid)
|
||||||
|
cfg = read_header(c.encrypt_text("x", USER_PWD))
|
||||||
|
assert cfg["mid"] == mid, mode
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("enc", ENCODINGS)
|
||||||
|
def test_header_records_the_encoding(self, vectors, enc):
|
||||||
|
for mode in (MODE_TURBO, MODE_RAW):
|
||||||
|
c = _core(mode, vectors, enc, "bt")
|
||||||
|
cfg = read_header(c.encrypt_text("x", USER_PWD))
|
||||||
|
want = "base" if enc == ENC_BASE64 else "hex"
|
||||||
|
assert cfg["out"] == want, mode
|
||||||
|
|
||||||
|
def test_legacy_modes_always_report_hex(self, vectors):
|
||||||
|
for mode in (MODE_REFERENCE, MODE_FAST):
|
||||||
|
c = _core(mode, vectors, ENC_BASE64, MID_HEX)
|
||||||
|
cfg = read_header(c.encrypt_text("x", USER_PWD))
|
||||||
|
assert cfg["out"] == "hex"
|
||||||
|
assert cfg["mid"] == "hex"
|
||||||
|
|
||||||
|
def test_hex_artefact_is_larger_than_bt(self, vectors):
|
||||||
|
"""A hex intermediate doubles the payload at each layer."""
|
||||||
|
big = "A" * 5_000
|
||||||
|
sizes = {}
|
||||||
|
for mid in MIDS:
|
||||||
|
c = _core(MODE_TURBO, vectors, "hex", mid)
|
||||||
|
sizes[mid] = len(_payload(c.encrypt_text(big, USER_PWD)))
|
||||||
|
assert sizes[MID_HEX] > sizes[MID_BYTES]
|
||||||
|
|
||||||
|
def test_base64_output_is_smaller_than_hex(self, vectors):
|
||||||
|
big = "A" * 5_000
|
||||||
|
sizes = {}
|
||||||
|
for enc in ENCODINGS:
|
||||||
|
c = _core(MODE_TURBO, vectors, enc, MID_BYTES)
|
||||||
|
sizes[enc] = len(_payload(c.encrypt_text(big, USER_PWD)))
|
||||||
|
assert sizes[ENC_BASE64] < sizes[ENC_HEX]
|
||||||
|
|
||||||
|
def test_hex_payload_is_hex(self, vectors):
|
||||||
|
c = _core(MODE_TURBO, vectors, "hex", MID_BYTES)
|
||||||
|
int(_payload(c.encrypt_text("data", USER_PWD)), 16)
|
||||||
|
|
||||||
|
def test_base64_payload_is_base64(self, vectors):
|
||||||
|
import base64 as b64
|
||||||
|
c = _core(MODE_TURBO, vectors, ENC_BASE64, MID_BYTES)
|
||||||
|
b64.b64decode(_payload(c.encrypt_text("data", USER_PWD)).encode(),
|
||||||
|
validate=True)
|
||||||
|
|
||||||
|
def test_unknown_encoding_rejected(self):
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
ChaosCryptCore(MODE_TURBO, encoding="base85")
|
||||||
|
|
||||||
|
def test_unknown_mid_rejected(self):
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
ChaosCryptCore(MODE_TURBO, mid="nonsense")
|
||||||
|
|
||||||
|
def test_mid_aliases_are_accepted(self):
|
||||||
|
"""'bytes' is an accepted spelling of 'bt', and 'base' of 'base64'."""
|
||||||
|
assert ChaosCryptCore(MODE_TURBO, mid="bytes").mid == MID_BYTES
|
||||||
|
assert ChaosCryptCore(MODE_TURBO, encoding="base").encoding == ENC_BASE64
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# The header decides how an artefact is read
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
class TestHeaderDrivesDecryption:
|
||||||
|
def test_a_misconfigured_reader_still_works(self, vectors):
|
||||||
|
"""The artefact states its own parameters; the reader need not."""
|
||||||
|
writer = _core(MODE_TURBO, vectors, ENC_BASE64, MID_HEX)
|
||||||
|
ct = writer.encrypt_text("header rules", USER_PWD)
|
||||||
|
|
||||||
|
reader = _core(MODE_TURBO, vectors, "hex", MID_BYTES) # wrong on both
|
||||||
|
assert reader.decrypt_text(ct, USER_PWD) == "header rules"
|
||||||
|
|
||||||
|
def test_headerless_input_is_rejected(self, cores):
|
||||||
|
for mode in MODES:
|
||||||
|
with pytest.raises(ChaosCryptError) as ei:
|
||||||
|
cores[mode].decrypt_text("72370655cafe", USER_PWD)
|
||||||
|
assert ei.value.code == "E017", mode
|
||||||
|
|
||||||
|
def test_malformed_payload_is_rejected(self, vectors):
|
||||||
|
from chaoscrypt._header import build_header
|
||||||
|
c = _core(MODE_TURBO, vectors)
|
||||||
|
bad = build_header(c.header_config("ciphertext")) + "zz"
|
||||||
|
with pytest.raises(ChaosCryptError) as ei:
|
||||||
|
c.decrypt_text(bad, USER_PWD)
|
||||||
|
assert ei.value.code == "E010"
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Key material must still contribute
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
class TestKeyMaterialContributes:
|
||||||
|
@pytest.mark.parametrize("mode", MODES)
|
||||||
|
def test_long_key_contributes(self, vectors, mode):
|
||||||
|
a = _core(mode, vectors)
|
||||||
|
b = _core(mode, vectors)
|
||||||
|
b.long_key = "0" * 4096
|
||||||
|
b._build_maps()
|
||||||
|
assert (a.encrypt_text("UPPER and lower", USER_PWD)
|
||||||
|
!= b.encrypt_text("UPPER and lower", USER_PWD))
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("mode", MODES)
|
||||||
|
def test_short_key_contributes(self, vectors, mode):
|
||||||
|
a = _core(mode, vectors)
|
||||||
|
b = _core(mode, vectors)
|
||||||
|
b.short_key = "0" * 512
|
||||||
|
b._build_maps()
|
||||||
|
assert (a.encrypt_text("UPPER and lower", USER_PWD)
|
||||||
|
!= b.encrypt_text("UPPER and lower", USER_PWD))
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("mode", MODES)
|
||||||
|
def test_password_contributes(self, vectors, mode):
|
||||||
|
c = _core(mode, vectors)
|
||||||
|
assert (c.encrypt_text("same", "pw-a") != c.encrypt_text("same", "pw-b"))
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("mode", MODES)
|
||||||
|
def test_substitution_tables_contribute(self, vectors, mode):
|
||||||
|
a = _core(mode, vectors)
|
||||||
|
b = _core(mode, vectors)
|
||||||
|
b.upper_mapping = "ZYXWVUTSRQPONMLKJIHGFEDCBA"
|
||||||
|
b._build_maps()
|
||||||
|
# both cases present, so upper_mapping cannot be bypassed
|
||||||
|
assert (a.encrypt_text("UPPER and lower", USER_PWD)
|
||||||
|
!= b.encrypt_text("UPPER and lower", USER_PWD))
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("mode", MODES)
|
||||||
|
def test_lower_mapping_contributes(self, vectors, mode):
|
||||||
|
a = _core(mode, vectors)
|
||||||
|
b = _core(mode, vectors)
|
||||||
|
b.lower_mapping = "zyxwvutsrqponmlkjihgfedcba"
|
||||||
|
b._build_maps()
|
||||||
|
assert (a.encrypt_text("UPPER and lower", USER_PWD)
|
||||||
|
!= b.encrypt_text("UPPER and lower", USER_PWD))
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("mode", MODES)
|
||||||
|
def test_flip_pattern_contributes(self, vectors, mode):
|
||||||
|
a = _core(mode, vectors)
|
||||||
|
b = _core(mode, vectors)
|
||||||
|
b.flip_pattern = [0] * 10
|
||||||
|
sample = "UPPER and lower"
|
||||||
|
assert (a.encrypt_text(sample, USER_PWD)
|
||||||
|
!= b.encrypt_text(sample, USER_PWD))
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Public API
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
class TestPublicAPI:
|
||||||
|
@pytest.mark.parametrize("mode", MODES)
|
||||||
|
def test_facade_roundtrip(self, keyfile, mode):
|
||||||
|
cc = ChaosCrypt(key_file=keyfile, key_password=KEY_PWD,
|
||||||
|
auto_load=True, mode=mode)
|
||||||
|
ct = cc.encrypt("facade mode test", USER_PWD)
|
||||||
|
assert cc.decrypt(ct, USER_PWD) == "facade mode test"
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("enc", ENCODINGS)
|
||||||
|
def test_facade_supports_encoding(self, keyfile, enc):
|
||||||
|
cc = ChaosCrypt(key_file=keyfile, key_password=KEY_PWD, auto_load=True,
|
||||||
|
mode=MODE_TURBO, encoding=enc)
|
||||||
|
ct = cc.encrypt("encoding via facade", USER_PWD)
|
||||||
|
assert cc.decrypt(ct, USER_PWD) == "encoding via facade"
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("mid", MIDS)
|
||||||
|
def test_facade_supports_mid(self, keyfile, mid):
|
||||||
|
cc = ChaosCrypt(key_file=keyfile, key_password=KEY_PWD, auto_load=True,
|
||||||
|
mode=MODE_TURBO, mid=mid)
|
||||||
|
ct = cc.encrypt("mid via facade", USER_PWD)
|
||||||
|
assert cc.decrypt(ct, USER_PWD) == "mid via facade"
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("mode", MODES)
|
||||||
|
def test_facade_file_roundtrip(self, keyfile, tmp_path, mode):
|
||||||
|
cc = ChaosCrypt(key_file=keyfile, key_password=KEY_PWD,
|
||||||
|
auto_load=True, mode=mode)
|
||||||
|
payload = os.urandom(1_500)
|
||||||
|
src = tmp_path / "payload.bin"
|
||||||
|
src.write_bytes(payload)
|
||||||
|
|
||||||
|
enc = cc.encrypt_file(str(src), USER_PWD)
|
||||||
|
out = cc.decrypt_file(enc, USER_PWD, str(tmp_path / "out.bin"))
|
||||||
|
assert open(out, "rb").read() == payload
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Errors, common to every mode
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
class TestModeErrors:
|
||||||
|
@pytest.mark.parametrize("mode", MODES)
|
||||||
|
def test_empty_plaintext_rejected(self, cores, mode):
|
||||||
|
with pytest.raises(ChaosCryptError) as ei:
|
||||||
|
cores[mode].encrypt_text("", USER_PWD)
|
||||||
|
assert ei.value.code == "E008"
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("mode", MODES)
|
||||||
|
def test_empty_password_rejected(self, cores, mode):
|
||||||
|
with pytest.raises(ChaosCryptError) as ei:
|
||||||
|
cores[mode].encrypt_text("data", "")
|
||||||
|
assert ei.value.code == "E006"
|
||||||
|
|
||||||
|
def test_empty_ciphertext_rejected(self, cores):
|
||||||
|
with pytest.raises(ChaosCryptError) as ei:
|
||||||
|
cores[MODE_FAST].decrypt_text("", USER_PWD)
|
||||||
|
assert ei.value.code == "E009"
|
||||||
@@ -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(69CES[^\s]+)", 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(69CES[^\s]+)", 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(69CES[^\s]+)", 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"
|
||||||
@@ -0,0 +1,294 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""
|
||||||
|
Strict reference-vector tests.
|
||||||
|
|
||||||
|
ChaosCrypt is a self-designed construction, so unlike AES or SHA-3 there are no
|
||||||
|
FIPS or RFC vectors to check it against. What can be checked is that the format
|
||||||
|
and the algorithm do not drift: the vectors in
|
||||||
|
``vectors/chaoscrypt_reference.json`` are generated from the implementation and
|
||||||
|
then frozen. If anything changes -- a substitution table, a bit operation, a
|
||||||
|
loop bound, the header layout, an encoding -- these tests fail.
|
||||||
|
|
||||||
|
Every artefact now carries a self-describing header, so each case is checked
|
||||||
|
for three things: the header is present and consistent, the ciphertext matches
|
||||||
|
the frozen value exactly, and the payload round-trips.
|
||||||
|
"""
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from chaoscrypt._core import ChaosCryptCore
|
||||||
|
from chaoscrypt.errors import ChaosCryptError
|
||||||
|
from chaoscrypt._header import (
|
||||||
|
MAGIC, BEGIN_MARKER, END_MARKER, read_header, strip_header,
|
||||||
|
MIDS, OUTS, KIND_CIPHERTEXT,
|
||||||
|
)
|
||||||
|
|
||||||
|
from ._vectors import available, load
|
||||||
|
|
||||||
|
VECTOR_NAME = "chaoscrypt_reference"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module")
|
||||||
|
def vectors():
|
||||||
|
return load(VECTOR_NAME)
|
||||||
|
|
||||||
|
|
||||||
|
def _core_from(km, mode="fast", enc="hex", mid="bt"):
|
||||||
|
"""Build a ChaosCryptCore preloaded with fixed key material."""
|
||||||
|
c = ChaosCryptCore(mode, "hash", enc, mid)
|
||||||
|
c.upper_mapping = km["upper_mapping"]
|
||||||
|
c.lower_mapping = km["lower_mapping"]
|
||||||
|
c.digit_mapping = km["digit_mapping"]
|
||||||
|
c.equal_mapping = km["equal_mapping"]
|
||||||
|
c.flip_pattern = km["flip_pattern"]
|
||||||
|
c.long_key = km["long_key"]
|
||||||
|
c.short_key = km["short_key"]
|
||||||
|
c.digit_reverse = {v: k for k, v in c.digit_mapping.items()}
|
||||||
|
c.equal_reverse = {v: k for k, v in c.equal_mapping.items()}
|
||||||
|
c._build_maps()
|
||||||
|
c.keys_loaded = True
|
||||||
|
return c
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module")
|
||||||
|
def core(vectors):
|
||||||
|
return _core_from(vectors["key_material"])
|
||||||
|
|
||||||
|
|
||||||
|
def _per_case_core(case, km):
|
||||||
|
"""A core configured the way the case was produced."""
|
||||||
|
return _core_from(km,
|
||||||
|
mode=case.get("mode", "fast"),
|
||||||
|
enc=case.get("out", "hex"),
|
||||||
|
mid=case.get("mid", "bt"))
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Vector file integrity
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
class TestVectorFile:
|
||||||
|
def test_vector_file_is_present(self):
|
||||||
|
assert VECTOR_NAME in available()
|
||||||
|
|
||||||
|
def test_required_sections_exist(self, vectors):
|
||||||
|
for key in ("key_material", "passwords", "cases",
|
||||||
|
"error_cases", "key_material_properties"):
|
||||||
|
assert key in vectors, f"missing section: {key}"
|
||||||
|
|
||||||
|
def test_long_key_is_4096_nibbles(self, vectors):
|
||||||
|
assert len(vectors["key_material"]["long_key"]) == 4096
|
||||||
|
|
||||||
|
def test_short_key_is_512_nibbles(self, vectors):
|
||||||
|
assert len(vectors["key_material"]["short_key"]) == 512
|
||||||
|
|
||||||
|
def test_keys_are_valid_hex(self, vectors):
|
||||||
|
int(vectors["key_material"]["long_key"], 16)
|
||||||
|
int(vectors["key_material"]["short_key"], 16)
|
||||||
|
|
||||||
|
def test_case_ids_are_unique(self, vectors):
|
||||||
|
ids = [c["id"] for c in vectors["cases"]]
|
||||||
|
assert len(ids) == len(set(ids))
|
||||||
|
|
||||||
|
def test_case_modes_are_known(self, vectors):
|
||||||
|
from chaoscrypt import MODES
|
||||||
|
for case in vectors["cases"]:
|
||||||
|
assert case.get("mode", "fast") in MODES, case["id"]
|
||||||
|
|
||||||
|
def test_case_mids_and_outs_are_known(self, vectors):
|
||||||
|
for case in vectors["cases"]:
|
||||||
|
assert case.get("mid", "bt") in MIDS, case["id"]
|
||||||
|
assert case.get("out", "hex") in OUTS, case["id"]
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Key material invariants
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
class TestKeyMaterialInvariants:
|
||||||
|
def test_upper_mapping_is_a_bijection(self, vectors):
|
||||||
|
m = vectors["key_material"]["upper_mapping"]
|
||||||
|
assert len(m) == 26
|
||||||
|
assert sorted(m) == sorted("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
|
||||||
|
|
||||||
|
def test_lower_mapping_is_a_bijection(self, vectors):
|
||||||
|
m = vectors["key_material"]["lower_mapping"]
|
||||||
|
assert len(m) == 26
|
||||||
|
assert sorted(m) == sorted("abcdefghijklmnopqrstuvwxyz")
|
||||||
|
|
||||||
|
def test_digit_mapping_covers_all_digits(self, vectors):
|
||||||
|
m = vectors["key_material"]["digit_mapping"]
|
||||||
|
assert sorted(m.keys()) == sorted("0123456789")
|
||||||
|
assert len(set(m.values())) == 10
|
||||||
|
|
||||||
|
def test_equal_mapping_covers_padding_counts(self, vectors):
|
||||||
|
m = vectors["key_material"]["equal_mapping"]
|
||||||
|
assert sorted(m.keys()) == ["0", "1", "2", "3"]
|
||||||
|
assert len(set(m.values())) == 4
|
||||||
|
|
||||||
|
def test_flip_pattern_is_ten_bits(self, vectors):
|
||||||
|
p = vectors["key_material"]["flip_pattern"]
|
||||||
|
assert len(p) == 10
|
||||||
|
assert all(b in (0, 1) for b in p)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Header conformance of every frozen case
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
class TestFrozenHeaders:
|
||||||
|
def test_every_case_starts_with_the_magic(self, vectors):
|
||||||
|
magic = MAGIC.decode()
|
||||||
|
for case in vectors["cases"]:
|
||||||
|
assert case["ciphertext"].startswith(magic), case["id"]
|
||||||
|
|
||||||
|
def test_every_case_carries_both_markers(self, vectors):
|
||||||
|
for case in vectors["cases"]:
|
||||||
|
ct = case["ciphertext"]
|
||||||
|
assert BEGIN_MARKER in ct, case["id"]
|
||||||
|
assert END_MARKER in ct, case["id"]
|
||||||
|
|
||||||
|
def test_every_case_header_parses(self, vectors):
|
||||||
|
for case in vectors["cases"]:
|
||||||
|
cfg = read_header(case["ciphertext"])
|
||||||
|
assert cfg["kind"] == KIND_CIPHERTEXT, case["id"]
|
||||||
|
|
||||||
|
def test_header_mode_matches_the_case(self, vectors):
|
||||||
|
for case in vectors["cases"]:
|
||||||
|
cfg = read_header(case["ciphertext"])
|
||||||
|
assert cfg["mode"] == case.get("mode", "fast"), case["id"]
|
||||||
|
|
||||||
|
def test_header_mid_matches_the_case(self, vectors):
|
||||||
|
"""The header's mid must match what the case says, or hex for the
|
||||||
|
character pipelines, which have no mid of their own."""
|
||||||
|
for case in vectors["cases"]:
|
||||||
|
cfg = read_header(case["ciphertext"])
|
||||||
|
mode = case.get("mode", "fast")
|
||||||
|
if mode in ("reference", "fast"):
|
||||||
|
assert cfg["mid"] == "hex", case["id"]
|
||||||
|
else:
|
||||||
|
assert cfg["mid"] == case.get("mid", "bt"), case["id"]
|
||||||
|
|
||||||
|
def test_header_out_matches_the_case(self, vectors):
|
||||||
|
for case in vectors["cases"]:
|
||||||
|
cfg = read_header(case["ciphertext"])
|
||||||
|
mode = case.get("mode", "fast")
|
||||||
|
if mode in ("reference", "fast"):
|
||||||
|
assert cfg["out"] == "hex", case["id"]
|
||||||
|
else:
|
||||||
|
assert cfg["out"] == case.get("out", "hex"), case["id"]
|
||||||
|
|
||||||
|
def test_reference_and_fast_always_report_hex(self, vectors):
|
||||||
|
"""The character pipelines ignore mid and always use hex."""
|
||||||
|
for case in vectors["cases"]:
|
||||||
|
if case.get("mode") in ("reference", "fast"):
|
||||||
|
cfg = read_header(case["ciphertext"])
|
||||||
|
assert cfg["mid"] == "hex", case["id"]
|
||||||
|
assert cfg["out"] == "hex", case["id"]
|
||||||
|
|
||||||
|
def test_payload_is_not_empty(self, vectors):
|
||||||
|
for case in vectors["cases"]:
|
||||||
|
assert strip_header(case["ciphertext"]), case["id"]
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# The frozen ciphertexts themselves
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
class TestFrozenVectors:
|
||||||
|
def test_encryption_reproduces_frozen_ciphertext(self, vectors):
|
||||||
|
"""Encrypting the recorded plaintext must yield the recorded artefact."""
|
||||||
|
km = vectors["key_material"]
|
||||||
|
pwd = vectors["passwords"]["user_password"]
|
||||||
|
failures = []
|
||||||
|
for case in vectors["cases"]:
|
||||||
|
c = _per_case_core(case, km)
|
||||||
|
got = c.encrypt_text(case["plaintext"], pwd)
|
||||||
|
if got != case["ciphertext"]:
|
||||||
|
failures.append(
|
||||||
|
f"{case['id']}:\n expected {case['ciphertext'][:80]}\n"
|
||||||
|
f" got {got[:80]}"
|
||||||
|
)
|
||||||
|
assert not failures, (
|
||||||
|
"frozen vectors no longer match -- format or algorithm changed:\n"
|
||||||
|
+ "\n".join(failures)
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_decryption_round_trips(self, vectors):
|
||||||
|
km = vectors["key_material"]
|
||||||
|
pwd = vectors["passwords"]["user_password"]
|
||||||
|
for case in vectors["cases"]:
|
||||||
|
c = _per_case_core(case, km)
|
||||||
|
got = c.decrypt_text(case["ciphertext"], pwd)
|
||||||
|
assert got == case["plaintext"], case["id"]
|
||||||
|
|
||||||
|
def test_encryption_is_deterministic(self, vectors):
|
||||||
|
km = vectors["key_material"]
|
||||||
|
pwd = vectors["passwords"]["user_password"]
|
||||||
|
for case in vectors["cases"]:
|
||||||
|
c = _per_case_core(case, km)
|
||||||
|
a = c.encrypt_text(case["plaintext"], pwd)
|
||||||
|
b = c.encrypt_text(case["plaintext"], pwd)
|
||||||
|
assert a == b, f"{case['id']} is not deterministic"
|
||||||
|
|
||||||
|
def test_wrong_password_does_not_reproduce_plaintext(self, core, vectors):
|
||||||
|
case = vectors["cases"][0]
|
||||||
|
try:
|
||||||
|
got = core.decrypt_text(case["ciphertext"], "not-the-password")
|
||||||
|
except ChaosCryptError:
|
||||||
|
return
|
||||||
|
assert got != case["plaintext"]
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Error behaviour
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
class TestFrozenErrorCases:
|
||||||
|
def test_error_cases_raise_expected_codes(self, core, vectors):
|
||||||
|
failures = []
|
||||||
|
for case in vectors["error_cases"]:
|
||||||
|
try:
|
||||||
|
if case["kind"] == "encrypt":
|
||||||
|
core.encrypt_text(case["plaintext"], case["password"])
|
||||||
|
else:
|
||||||
|
core.decrypt_text(case["ciphertext"], case["password"])
|
||||||
|
except ChaosCryptError as e:
|
||||||
|
if e.code != case["expect_code"]:
|
||||||
|
failures.append(
|
||||||
|
f"{case['id']}: expected {case['expect_code']}, got {e.code}"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
failures.append(
|
||||||
|
f"{case['id']}: expected {case['expect_code']}, no error raised"
|
||||||
|
)
|
||||||
|
assert not failures, "\n".join(failures)
|
||||||
|
|
||||||
|
def test_headerless_input_is_rejected(self, core, vectors):
|
||||||
|
"""The deliberate break from pre-4.2.6 material."""
|
||||||
|
with pytest.raises(ChaosCryptError) as ei:
|
||||||
|
core.decrypt_text("72370655031311011c111f261365172716020b69", "pw")
|
||||||
|
assert ei.value.code == "E017"
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Known-answer tests for the building blocks
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
class TestKnownAnswers:
|
||||||
|
def test_digit_mapping_encode(self, core, vectors):
|
||||||
|
kat = next(k for k in vectors["known_answer_tests"]
|
||||||
|
if k["id"] == "digit_mapping_encode")
|
||||||
|
assert core._encode_digit(kat["input"]) == kat["expected"]
|
||||||
|
|
||||||
|
def test_digit_mapping_round_trip(self, core, vectors):
|
||||||
|
kat = next(k for k in vectors["known_answer_tests"]
|
||||||
|
if k["id"] == "digit_mapping_encode")
|
||||||
|
assert core._decode_digit(kat["expected"]) == kat["input"]
|
||||||
|
|
||||||
|
def test_equal_mapping_values(self, vectors):
|
||||||
|
kat = next(k for k in vectors["known_answer_tests"]
|
||||||
|
if k["id"] == "equal_mapping_values")
|
||||||
|
assert vectors["key_material"]["equal_mapping"] == kat["expected"]
|
||||||
|
|
||||||
|
def test_substitution_round_trip(self, core):
|
||||||
|
sample = "ABCXYZabcxyz"
|
||||||
|
subbed = core._substitute_letters(sample, core.encrypt_map)
|
||||||
|
assert core._substitute_letters(subbed, core.decrypt_map) == sample
|
||||||
|
|
||||||
|
def test_case_flip_is_its_own_inverse(self, core):
|
||||||
|
sample = "AbCdEfGhIjKlMnOp"
|
||||||
|
assert core._apply_flip(core._apply_flip(sample)) == sample
|
||||||
@@ -0,0 +1,215 @@
|
|||||||
|
{
|
||||||
|
"_comment": "ChaosCrypt frozen reference vectors for the headed format (4.2.6 onward). Every artefact carries a self-describing header: magic b'69CES', a begin marker, a JSON configuration record, an end marker, then the payload. ChaosCrypt is a self-designed construction, so no FIPS or RFC vectors exist for it; these are generated from the implementation and then frozen, which turns them into a regression guard. They are NOT a proof of strength. Regenerating them means the format or the algorithm changed, which is a compatibility break.",
|
||||||
|
"name": "chaoscrypt_reference",
|
||||||
|
"source": "Self-generated from the implementation, then frozen",
|
||||||
|
"version": "4.2.6",
|
||||||
|
"notes": [
|
||||||
|
"Key material below is fixed so the vectors are reproducible; never use it for real data.",
|
||||||
|
"Every ciphertext starts with the magic bytes b'69CES'.",
|
||||||
|
"The configuration block names the mode, the intermediate representation (mid) and the output encoding (out).",
|
||||||
|
"reference and fast share one ciphertext form and always use hex; only mode is recorded differently.",
|
||||||
|
"turbo and raw support out=hex|base and mid=bt|hex, producing distinct formats.",
|
||||||
|
"Headerless input is rejected with E017, by design."
|
||||||
|
],
|
||||||
|
"key_material": {
|
||||||
|
"upper_mapping": "BCDEFGHIJKLMNOPQRSTUVWXYZA",
|
||||||
|
"lower_mapping": "bcdefghijklmnopqrstuvwxyza",
|
||||||
|
"digit_mapping": {
|
||||||
|
"0": "A",
|
||||||
|
"1": "B",
|
||||||
|
"2": "C",
|
||||||
|
"3": "D",
|
||||||
|
"4": "E",
|
||||||
|
"5": "F",
|
||||||
|
"6": "G",
|
||||||
|
"7": "H",
|
||||||
|
"8": "I",
|
||||||
|
"9": "J"
|
||||||
|
},
|
||||||
|
"equal_mapping": {
|
||||||
|
"0": "W",
|
||||||
|
"1": "X",
|
||||||
|
"2": "Z",
|
||||||
|
"3": "Y"
|
||||||
|
},
|
||||||
|
"flip_pattern": [
|
||||||
|
1,
|
||||||
|
0,
|
||||||
|
1,
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
1,
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
1,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"long_key": "39d65637ec0f62b69ca5d3c5ab08385d533d000dc2d8984d23406b2cb30e3ce304ab21201994888a838d10100ff5688702850c3cb7c828123be21f3f0fca661065db7b80d40b05717d7c18d8374e925044a9ce53e9445c1d12bed49340b1bc8e44fd81c3a63e933da598f9384fc25cded0d8c5e9d5a1462beeca11d631f5e65e578e95bcf67600c993436722dd4cd582487efff016f034c54be236ad3562ddcff16fc53e34597734c8326c54326343c6f4bda1cf82b884080a521dae535b7a6b45ba3350b56ea5b61fe1757b8f51328001975fd898057a6d7bcae3225d9b8742539b29023476500cccee48835dac749908dbf1003bcd754093a6a8ca4bf8f0159716e7c28877c5c7f66fd3885604c94a100372b691aff5811fc75fa91573e8677e56663fecf2314f1fada7239737396398228417a72c7335fb3af6949b3925d6127f2461d711dbf0a45fef7f4fe71ea981cfff4ccc51e52ab46af1fe98c24365c18fa8e368b891c9fb38307f627b877c73487c9fce2250eea6c6be1bdeea24500548b902e9795f8290907bbef77dcf05251d3e412cbac121a1703abc2329f091e27f48736b52db793a8cf03016aec910386ea811dbded8af82cbb1ed331a4e67e24441d95c69607b4f0278b398fc7bb44b12da5bca48bdfba3506e4604615c6ec426ebd4db7996d889bdd53088105d916d84f37b7f781fd49455d533356af6b85d15a3eec3047f933d0212cf53483c752cfc0eea4bca27fe2bd7fded49851324d80c02d8145e4bf5f90d479436850e37875fac00257db3e53b3a0fb3b782338113a1cd7b554e0fe606195a8a51e2898f8469d20b4896f928d113b7bc82ef0dd3b7d8237f98cc7044cb94c2ef513f32de92d59f0aa65f201528f2c1a5b2c18d8db7e2b87755cb273317133bdaf398e229b8bc519cc753b381f5555309763ceeaaf8134e7e9d14707de6382af9664ec9d6d3d0244d241c23070362b8f0b1497f5b6182b2bd3a60f7f03463ffa2e79c68efe169453489f153cc65251e140e72c7c3752c515b604238f65e5ba06dcffce9f9b1566934ca052eb30026b8d4236623c157f20ca480a53b22f95e979471d0c05b0b8f3755833b9396241679eb78c63ccd2170b3213660c0d2275f7ac3f4618f8a688e35d1a59cdd0177bcb23c4a283f487bcafc63ce5c1cba9baec57093cf12c8dd0c8d7f352333cd660814c94b27385445390056d75077d33c6cd977fa5f6aa19ebea84890bdc55400e02d8337b4097b1532e77fe5b7e1b3d9426ceb3417b0a2a481c1aa8c84692d34f2fa29c3c90cfd0bcb0fe227fc63fa8877e38ad2d8ac8a198c331c24c73de46c4b7f9fc157953b8c8964caedbd89305b443dc178aee57874b06ecc0b208eeeab632167047a105aa67471df64d17f6deddfc77781c6c1c9945a7125bee0eb19c50cd560311ebc0e62ae18eb197964e471dc09ca2fc4c135cd924b69b5006eb6ff0904cf064f64a54b94db3c72ba607554b74bbca4efb4fe42238eb4ffdf5fda2a1ab2675c3de0dd8da5f759c8648ed4e2ee68a1571290b7962b53f7710f3dbacd826971c1bc019f34b654e51aeb24f936dcf38ca7e87203a9ea57b21dc865b79d238092e49c156c5bc2e0abc2c47822546963ef3a77bbcf7ab70da0c27e209a1054160897af67042c326c055ec7a55dfe74a8d367a57a32ee3569e58c0674d58a95d8116d9082f463727987e5279d5fb27a54849feb1021f1649f55c56a7edd5017f6255ee7e2c309556992c127bd7ae270233b24f0c648cb499624e79184a7936da6108af26b47fa137cec35b5130b62039e3946ec427d9b34d9ebeabe0a95c518f06934a32c38ce2162e276757a2362cc5eb27a8c31be14c3b1d3d5611c752ff894944d3ea637a87eb2a286d8c7400b3c1a691a224e965ce2ad13ea95305c68e60691793c696887a74b8952e8434f510fdbb0ba7e0f3322a4da801db599a8210cf0a0a9ca1e296c25402f606fcbf45f06a22f2bfeb44c62a2680bce5c6e63ecd57bc4e3170111b00bd5fcf1d8feb5e21dbfd671d5826c9dfc7188689f99b05012629dd0d29fb291e25560729f017a2207949fa873d74d1a17251382a11feae73755614c53291674945312378fdc2b79d1078244f5ae4ee44f7a8e7f27d8b4ce1b1c19415cfa3d8a2c8b92041416da7556f27181d7583de84fd21129afeab0707dcce01e03cb3d69258edaf8c88535b828eb0651eba05dec330d3c2a68629c7498d47188238f3f216b4f848ed5e2c6c9cdef330ec2e58fdf89a4e2bcc3c114ab06d15541d9cac8947c9562ac5cfb2bd7ac56f4947b43f5f614aa409d84addcd325f696976caea9ff4b951e4c920c184cf4963c8cbb92e580fb78e41ec762e3f7f7bea9bb9488b93d524c55c4ca017c632ce12c381e73aaf9359346ee53c3cfd9922b41e5034031781f7b698c411e23d56e13327f316ac807c1d56c815915a56c3ad044c15070ff2c28ee2381fea84f36e70b039988ba7dc6cb55f698afc4859da08475197620a56c113f702e90f41f20708e853f0be81d5080ce7dd3683d3f1386e37c26e06161cf4500e5cc8bbd6f7e243e5733abdfb2e9554c22c5e16b4ecd6241e326e460765d874f578e7e720b00fb7f0ad725551bba2912e85d895bc705032c18bf3e8c6ad3587d39d2f00ae869a8da03afdb581d588af5eee8b69e1de6e1a5fda79946a05dc3bf9fcaae92b4b03b9d75bf6f61a6f35f1d3f4f293b2f0477d2e8dd90f1c51bba82beccd388d3f6a3cb6613ac1e4e8fb59a6d8844d1c15496d70e33a820ed5d9a027b2f3581d5e2b32ef3cd8eb229c728b138096811ad9b66868ec780fb03d4e6c9585329cf5635eca3fc5b7e4f6759b9b4278330280b6e940756153481fe",
|
||||||
|
"short_key": "cafb66ae19518dd63547f87adbf4d26a4f035480433cf7f9a2a19f846f152b8eabfc7673995f75ff3a2e90107432921ae92c06af87e549d1983684f89ec7964ca4d001671c483a93ced8b665e94310e375ec4933e04bce3c67bc895cdaa7c593d50a0c3b19f6efc5e3a88a0371904615899e71b481b6cf077f77f681d74fe2eadb666d3fdfda87e88d50ae94f2fc174958bf4e33954a685eba7a7c5d81816ebd47e56d6d8a8a246b0f0abc219bc3da5b790c12461475855d3fef3d3247b8c08d1d7326419c3e4df22f1138cbc39cb01da917cc8dacd97be1c2dd6bef4b626c9d8fafa25479735c02789006d1905f29d2c666114fc802abd19a095170e9e2c6eb"
|
||||||
|
},
|
||||||
|
"passwords": {
|
||||||
|
"user_password": "reference-user-password",
|
||||||
|
"key_password": "reference-key-password"
|
||||||
|
},
|
||||||
|
"key_material_properties": {
|
||||||
|
"long_key_length": 4096,
|
||||||
|
"short_key_length": 512,
|
||||||
|
"digit_mapping_size": 10,
|
||||||
|
"equal_mapping_size": 4,
|
||||||
|
"flip_pattern_length": 10,
|
||||||
|
"upper_mapping_is_bijection": true,
|
||||||
|
"lower_mapping_is_bijection": true
|
||||||
|
},
|
||||||
|
"cases": [
|
||||||
|
{
|
||||||
|
"id": "text_ascii_short",
|
||||||
|
"kind": "text",
|
||||||
|
"plaintext": "hello",
|
||||||
|
"ciphertext": "69CES385aeff1f4179a744c8fb0c5ae4702d325f6230d059f4251135c2536409dee93{\"alg\":\"chaoscrypt\",\"b64\":true,\"cache\":\"hash\",\"compact\":false,\"flip\":\"conditional\",\"flipbits\":10,\"kdf\":\"expand\",\"keybits\":16384,\"keyshort\":2048,\"kind\":\"ciphertext\",\"ksum\":\"8007e271aea2b261\",\"lib\":\"4.2.6\",\"mid\":\"hex\",\"mode\":\"fast\",\"order\":\"base64>subst>flip>reverse>xor>xor\",\"out\":\"hex\",\"subst\":\"bijective\",\"utf8\":true,\"v\":1,\"xor_layers\":2}2025ea4e4b4b93803f2ccadeaf318d1957ce42ff5409410f660348be96a4c0f272370655031311011c111f261365172716020b69"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "text_ascii_long",
|
||||||
|
"kind": "text",
|
||||||
|
"plaintext": "The quick brown fox jumps over the lazy dog.",
|
||||||
|
"ciphertext": "69CES385aeff1f4179a744c8fb0c5ae4702d325f6230d059f4251135c2536409dee93{\"alg\":\"chaoscrypt\",\"b64\":true,\"cache\":\"hash\",\"compact\":false,\"flip\":\"conditional\",\"flipbits\":10,\"kdf\":\"expand\",\"keybits\":16384,\"keyshort\":2048,\"kind\":\"ciphertext\",\"ksum\":\"8007e271aea2b261\",\"lib\":\"4.2.6\",\"mid\":\"hex\",\"mode\":\"fast\",\"order\":\"base64>subst>flip>reverse>xor>xor\",\"out\":\"hex\",\"subst\":\"bijective\",\"utf8\":true,\"v\":1,\"xor_layers\":2}2025ea4e4b4b93803f2ccadeaf318d1957ce42ff5409410f660348be96a4c0f272620757011113021e151f26116d1377165244424335566654761112461771556c355415785650231457101775157e77517a025a53761c646866101570571471047562634110750b1246147e412617017552161472621350437112030331791f7d41524563721555011276167f5f7443172460066114177e1036286067"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "text_unicode",
|
||||||
|
"kind": "text",
|
||||||
|
"plaintext": "ChaosCrypt 混沌加密世界",
|
||||||
|
"ciphertext": "69CES385aeff1f4179a744c8fb0c5ae4702d325f6230d059f4251135c2536409dee93{\"alg\":\"chaoscrypt\",\"b64\":true,\"cache\":\"hash\",\"compact\":false,\"flip\":\"conditional\",\"flipbits\":10,\"kdf\":\"expand\",\"keybits\":16384,\"keyshort\":2048,\"kind\":\"ciphertext\",\"ksum\":\"8007e271aea2b261\",\"lib\":\"4.2.6\",\"mid\":\"hex\",\"mode\":\"fast\",\"order\":\"base64>subst>flip>reverse>xor>xor\",\"out\":\"hex\",\"subst\":\"bijective\",\"utf8\":true,\"v\":1,\"xor_layers\":2}2025ea4e4b4b93803f2ccadeaf318d1957ce42ff5409410f660348be96a4c0f274370557031d120a1d151f2712611627175042144167573654701314441c70016f6c57477b0151271757154774157f27517c015453771c646f31131270561776042267644115745c104e13744075170b74065a6000"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "text_single_char",
|
||||||
|
"kind": "text",
|
||||||
|
"plaintext": "a",
|
||||||
|
"ciphertext": "69CES385aeff1f4179a744c8fb0c5ae4702d325f6230d059f4251135c2536409dee93{\"alg\":\"chaoscrypt\",\"b64\":true,\"cache\":\"hash\",\"compact\":false,\"flip\":\"conditional\",\"flipbits\":10,\"kdf\":\"expand\",\"keybits\":16384,\"keyshort\":2048,\"kind\":\"ciphertext\",\"ksum\":\"8007e271aea2b261\",\"lib\":\"4.2.6\",\"mid\":\"hex\",\"mode\":\"fast\",\"order\":\"base64>subst>flip>reverse>xor>xor\",\"out\":\"hex\",\"subst\":\"bijective\",\"utf8\":true,\"v\":1,\"xor_layers\":2}2025ea4e4b4b93803f2ccadeaf318d1957ce42ff5409410f660348be96a4c0f274640757021c13505466"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "text_repeated",
|
||||||
|
"kind": "text",
|
||||||
|
"plaintext": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
|
||||||
|
"ciphertext": "69CES385aeff1f4179a744c8fb0c5ae4702d325f6230d059f4251135c2536409dee93{\"alg\":\"chaoscrypt\",\"b64\":true,\"cache\":\"hash\",\"compact\":false,\"flip\":\"conditional\",\"flipbits\":10,\"kdf\":\"expand\",\"keybits\":16384,\"keyshort\":2048,\"kind\":\"ciphertext\",\"ksum\":\"8007e271aea2b261\",\"lib\":\"4.2.6\",\"mid\":\"hex\",\"mode\":\"fast\",\"order\":\"base64>subst>flip>reverse>xor>xor\",\"out\":\"hex\",\"subst\":\"bijective\",\"utf8\":true,\"v\":1,\"xor_layers\":2}2025ea4e4b4b93803f2ccadeaf318d1957ce42ff5409410f660348be96a4c0f21274143211731f451f501214035306307221650654071643044e141c761263457215564216426104660774101143132651606652447c0155704451404374112c72007f065253704c636161101573574175527463614412750f17404676447742062551131572621c55127111030066291a2a1051176074465357117341795025111c716551601344724461631713734d437053420843404710141d321555157c7f160f061440712c435f735578130d4d136d177806666344430411461440504d434e6173062b6240115d7160546266070421735513437666164406070856630610527a40167463456f1e447457735231046c467403136a0b73431044640d611f4121521613155515435d111302137e525a716c03"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "turbo_hex_default",
|
||||||
|
"kind": "text",
|
||||||
|
"mode": "turbo",
|
||||||
|
"out": "hex",
|
||||||
|
"mid": "bt",
|
||||||
|
"note": "turbo in its default form",
|
||||||
|
"plaintext": "mode coverage sample",
|
||||||
|
"ciphertext": "69CES385aeff1f4179a744c8fb0c5ae4702d325f6230d059f4251135c2536409dee93{\"alg\":\"chaoscrypt\",\"b64\":true,\"cache\":\"hash\",\"compact\":true,\"flip\":\"conditional\",\"flipbits\":10,\"kdf\":\"shake256\",\"keybits\":16384,\"keyshort\":2048,\"kind\":\"ciphertext\",\"ksum\":\"8007e271aea2b261\",\"lib\":\"4.2.6\",\"mid\":\"bt\",\"mode\":\"turbo\",\"order\":\"base64>subst>flip>reverse>xor>xor\",\"out\":\"hex\",\"subst\":\"bijective\",\"utf8\":true,\"v\":1,\"xor_layers\":2}2025ea4e4b4b93803f2ccadeaf318d1957ce42ff5409410f660348be96a4c0f2568d8a131c130eef3c78ac317ed0f40bb7da2bb3"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "turbo_hex_mid",
|
||||||
|
"kind": "text",
|
||||||
|
"mode": "turbo",
|
||||||
|
"out": "hex",
|
||||||
|
"mid": "hex",
|
||||||
|
"note": "turbo with a hex intermediate",
|
||||||
|
"plaintext": "mode coverage sample",
|
||||||
|
"ciphertext": "69CES385aeff1f4179a744c8fb0c5ae4702d325f6230d059f4251135c2536409dee93{\"alg\":\"chaoscrypt\",\"b64\":true,\"cache\":\"hash\",\"compact\":true,\"flip\":\"conditional\",\"flipbits\":10,\"kdf\":\"shake256\",\"keybits\":16384,\"keyshort\":2048,\"kind\":\"ciphertext\",\"ksum\":\"8007e271aea2b261\",\"lib\":\"4.2.6\",\"mid\":\"hex\",\"mode\":\"turbo\",\"order\":\"base64>subst>flip>reverse>xor>xor\",\"out\":\"hex\",\"subst\":\"bijective\",\"utf8\":true,\"v\":1,\"xor_layers\":2}2025ea4e4b4b93803f2ccadeaf318d1957ce42ff5409410f660348be96a4c0f2d6d808fc5bca259bec4b164a17418bb8b3ca098e9207e8a3aaf218b05faa270bd512f58b92372a07415e5c035d86277a0d971666c504ff9aa31519dce9f3a38f3bfae3f4f4934fb1ae92a1c57c55a216"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "turbo_base64_default",
|
||||||
|
"kind": "text",
|
||||||
|
"mode": "turbo",
|
||||||
|
"out": "base",
|
||||||
|
"mid": "bt",
|
||||||
|
"note": "turbo with base64 output",
|
||||||
|
"plaintext": "mode coverage sample",
|
||||||
|
"ciphertext": "69CES385aeff1f4179a744c8fb0c5ae4702d325f6230d059f4251135c2536409dee93{\"alg\":\"chaoscrypt\",\"b64\":true,\"cache\":\"hash\",\"compact\":true,\"flip\":\"conditional\",\"flipbits\":10,\"kdf\":\"shake256\",\"keybits\":16384,\"keyshort\":2048,\"kind\":\"ciphertext\",\"ksum\":\"8007e271aea2b261\",\"lib\":\"4.2.6\",\"mid\":\"bt\",\"mode\":\"turbo\",\"order\":\"base64>subst>flip>reverse>xor>xor\",\"out\":\"base\",\"subst\":\"bijective\",\"utf8\":true,\"v\":1,\"xor_layers\":2}2025ea4e4b4b93803f2ccadeaf318d1957ce42ff5409410f660348be96a4c0f2Vo2KExwTDu88eKwxftD0C7faK7M="
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "raw_hex_default",
|
||||||
|
"kind": "text",
|
||||||
|
"mode": "raw",
|
||||||
|
"out": "hex",
|
||||||
|
"mid": "bt",
|
||||||
|
"note": "raw in its default form",
|
||||||
|
"plaintext": "mode coverage sample",
|
||||||
|
"ciphertext": "69CES385aeff1f4179a744c8fb0c5ae4702d325f6230d059f4251135c2536409dee93{\"alg\":\"chaoscrypt\",\"b64\":true,\"cache\":\"hash\",\"compact\":true,\"flip\":\"conditional\",\"flipbits\":10,\"kdf\":\"shake256\",\"keybits\":16384,\"keyshort\":2048,\"kind\":\"ciphertext\",\"ksum\":\"8007e271aea2b261\",\"lib\":\"4.2.6\",\"mid\":\"bt\",\"mode\":\"raw\",\"order\":\"base64>subst>flip>reverse>xor>xor\",\"out\":\"hex\",\"subst\":\"bijective\",\"utf8\":true,\"v\":1,\"xor_layers\":2}2025ea4e4b4b93803f2ccadeaf318d1957ce42ff5409410f660348be96a4c0f2f694f4e8672f3fc16483d837efbb6d298fa015a3"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "raw_hex_mid",
|
||||||
|
"kind": "text",
|
||||||
|
"mode": "raw",
|
||||||
|
"out": "hex",
|
||||||
|
"mid": "hex",
|
||||||
|
"note": "raw with a hex intermediate",
|
||||||
|
"plaintext": "mode coverage sample",
|
||||||
|
"ciphertext": "69CES385aeff1f4179a744c8fb0c5ae4702d325f6230d059f4251135c2536409dee93{\"alg\":\"chaoscrypt\",\"b64\":true,\"cache\":\"hash\",\"compact\":true,\"flip\":\"conditional\",\"flipbits\":10,\"kdf\":\"shake256\",\"keybits\":16384,\"keyshort\":2048,\"kind\":\"ciphertext\",\"ksum\":\"8007e271aea2b261\",\"lib\":\"4.2.6\",\"mid\":\"hex\",\"mode\":\"raw\",\"order\":\"base64>subst>flip>reverse>xor>xor\",\"out\":\"hex\",\"subst\":\"bijective\",\"utf8\":true,\"v\":1,\"xor_layers\":2}2025ea4e4b4b93803f2ccadeaf318d1957ce42ff5409410f660348be96a4c0f267847ae69097a7286bc9d3e865d9f336ab78f3810b03b12184d10e44474079beb9a471f1d1d3b13a91808e0f5c111cad9b738545f48d51545a3f25edce7570b95060bcb456fda92bddbf60242457696c"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "raw_base64_default",
|
||||||
|
"kind": "text",
|
||||||
|
"mode": "raw",
|
||||||
|
"out": "base",
|
||||||
|
"mid": "bt",
|
||||||
|
"note": "raw with base64 output",
|
||||||
|
"plaintext": "mode coverage sample",
|
||||||
|
"ciphertext": "69CES385aeff1f4179a744c8fb0c5ae4702d325f6230d059f4251135c2536409dee93{\"alg\":\"chaoscrypt\",\"b64\":true,\"cache\":\"hash\",\"compact\":true,\"flip\":\"conditional\",\"flipbits\":10,\"kdf\":\"shake256\",\"keybits\":16384,\"keyshort\":2048,\"kind\":\"ciphertext\",\"ksum\":\"8007e271aea2b261\",\"lib\":\"4.2.6\",\"mid\":\"bt\",\"mode\":\"raw\",\"order\":\"base64>subst>flip>reverse>xor>xor\",\"out\":\"base\",\"subst\":\"bijective\",\"utf8\":true,\"v\":1,\"xor_layers\":2}2025ea4e4b4b93803f2ccadeaf318d1957ce42ff5409410f660348be96a4c0f29pT06GcvP8Fkg9g377ttKY+gFaM="
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"error_cases": [
|
||||||
|
{
|
||||||
|
"id": "empty_plaintext_rejected",
|
||||||
|
"kind": "encrypt",
|
||||||
|
"plaintext": "",
|
||||||
|
"password": "reference-user-password",
|
||||||
|
"expect_code": "E008",
|
||||||
|
"note": "Empty plaintext raises ChaosCrypt_ERR_EmptyPlaintext_E008."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "empty_password_rejected",
|
||||||
|
"kind": "encrypt",
|
||||||
|
"plaintext": "hello",
|
||||||
|
"password": "",
|
||||||
|
"expect_code": "E006",
|
||||||
|
"note": "Empty encryption password raises ChaosCrypt_ERR_EmptyPassword_E006."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "headerless_input_rejected",
|
||||||
|
"kind": "decrypt",
|
||||||
|
"ciphertext": "72370655031311011c111f261365172716020b69",
|
||||||
|
"password": "reference-user-password",
|
||||||
|
"expect_code": "E017",
|
||||||
|
"note": "Input without the magic header is not a CES artefact. This is the deliberate break from pre-4.2.6 material."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "malformed_header_rejected",
|
||||||
|
"kind": "decrypt",
|
||||||
|
"ciphertext": "69CES0000000000000000000000000000000000000000000000000000000000000000{}000000000000000000000000000000000000000000000000000000000000000000",
|
||||||
|
"password": "reference-user-password",
|
||||||
|
"expect_code": "E018",
|
||||||
|
"note": "A bad marker or unusable JSON raises ChaosCrypt_ERR_MalformedHeader_E018."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "empty_ciphertext_rejected",
|
||||||
|
"kind": "decrypt",
|
||||||
|
"ciphertext": "",
|
||||||
|
"password": "reference-user-password",
|
||||||
|
"expect_code": "E009",
|
||||||
|
"note": "Empty ciphertext raises ChaosCrypt_ERR_EmptyCiphertext_E009."
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"known_answer_tests": [
|
||||||
|
{
|
||||||
|
"id": "digit_mapping_encode",
|
||||||
|
"input": "0123456789",
|
||||||
|
"expected": "ABCDEFGHIJ",
|
||||||
|
"note": "_encode_digit maps each decimal digit through digit_mapping."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "equal_mapping_values",
|
||||||
|
"expected": {
|
||||||
|
"0": "W",
|
||||||
|
"1": "X",
|
||||||
|
"2": "Z",
|
||||||
|
"3": "Y"
|
||||||
|
},
|
||||||
|
"note": "equal_mapping maps padding counts to these distinct characters."
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,549 @@
|
|||||||
|
"""
|
||||||
|
ChaosCrypt interactive terminal UI.
|
||||||
|
|
||||||
|
A dependency-free menu-driven interface, intended for people who would
|
||||||
|
rather not memorise command line flags. English is the default language;
|
||||||
|
the menu can switch to Chinese at runtime.
|
||||||
|
|
||||||
|
Running ``chaoscrypt`` with no arguments launches this UI. The module is
|
||||||
|
imported lazily so that library users never pay for it.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from . import (DEFAULT_KEY_FILE, __version__, ChaosCrypt, MODES,
|
||||||
|
DEFAULT_MODE, ENCODINGS, DEFAULT_ENCODING)
|
||||||
|
from .errors import ChaosCryptError
|
||||||
|
from .i18n import DEFAULT_LANG, LANG_NAMES, t
|
||||||
|
|
||||||
|
__all__ = ["run_tui", "TUI"]
|
||||||
|
|
||||||
|
WIDTH = 66
|
||||||
|
|
||||||
|
# ANSI styling; degrades to plain text when the terminal cannot handle it.
|
||||||
|
_C = {
|
||||||
|
"reset": "\033[0m",
|
||||||
|
"bold": "\033[1m",
|
||||||
|
"dim": "\033[2m",
|
||||||
|
"cyan": "\033[36m",
|
||||||
|
"green": "\033[32m",
|
||||||
|
"yellow": "\033[33m",
|
||||||
|
"red": "\033[31m",
|
||||||
|
"magenta": "\033[35m",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _supports_color() -> bool:
|
||||||
|
"""Whether the attached stdout can render ANSI colour."""
|
||||||
|
if os.environ.get("NO_COLOR"):
|
||||||
|
return False
|
||||||
|
if not sys.stdout.isatty():
|
||||||
|
return False
|
||||||
|
if os.name == "nt":
|
||||||
|
try:
|
||||||
|
import ctypes
|
||||||
|
kernel32 = ctypes.windll.kernel32
|
||||||
|
kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)
|
||||||
|
return True
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
_COLOR = _supports_color()
|
||||||
|
|
||||||
|
|
||||||
|
def c(text: str, *styles: str) -> str:
|
||||||
|
"""Wrap ``text`` in ANSI styles, or return it unchanged."""
|
||||||
|
if not _COLOR or not styles:
|
||||||
|
return text
|
||||||
|
return "".join(_C.get(s, "") for s in styles) + text + _C["reset"]
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Input helpers
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
class _Abort(Exception):
|
||||||
|
"""Raised when the user asks to return to the main menu."""
|
||||||
|
|
||||||
|
|
||||||
|
def _ask(prompt: str, default: Optional[str] = None) -> str:
|
||||||
|
suffix = f" [{default}]" if default else ""
|
||||||
|
try:
|
||||||
|
val = input(f"{c('>', 'cyan')} {prompt}{suffix}: ").strip()
|
||||||
|
except (EOFError, KeyboardInterrupt):
|
||||||
|
print()
|
||||||
|
raise _Abort()
|
||||||
|
if not val and default is not None:
|
||||||
|
return default
|
||||||
|
return val
|
||||||
|
|
||||||
|
|
||||||
|
def _ask_secret(prompt: str) -> str:
|
||||||
|
"""Read a password without echoing it when possible.
|
||||||
|
|
||||||
|
Interactive terminals use ``getpass`` so the input is not shown. Piped or
|
||||||
|
redirected input cannot use ``getpass``, so it falls back to ``input``,
|
||||||
|
which keeps the UI scriptable.
|
||||||
|
"""
|
||||||
|
label = f"{c('>', 'cyan')} {prompt}: "
|
||||||
|
|
||||||
|
if sys.stdin is not None and sys.stdin.isatty():
|
||||||
|
try:
|
||||||
|
import getpass
|
||||||
|
return getpass.getpass(label)
|
||||||
|
except (EOFError, KeyboardInterrupt):
|
||||||
|
print()
|
||||||
|
raise _Abort()
|
||||||
|
except Exception:
|
||||||
|
pass # Fall through to the non-echoing fallback below.
|
||||||
|
|
||||||
|
try:
|
||||||
|
return input(label).strip()
|
||||||
|
except (EOFError, KeyboardInterrupt):
|
||||||
|
print()
|
||||||
|
raise _Abort()
|
||||||
|
|
||||||
|
|
||||||
|
def _ask_yes_no(prompt: str, lang: str) -> bool:
|
||||||
|
try:
|
||||||
|
val = input(f"{c('>', 'cyan')} {prompt} [y/n]: ").strip().lower()
|
||||||
|
except (EOFError, KeyboardInterrupt):
|
||||||
|
print()
|
||||||
|
raise _Abort()
|
||||||
|
return val in ("y", "yes")
|
||||||
|
|
||||||
|
|
||||||
|
def _pause(lang: str) -> None:
|
||||||
|
try:
|
||||||
|
input(c(f" {t('press_enter', lang)}", "dim"))
|
||||||
|
except (EOFError, KeyboardInterrupt):
|
||||||
|
print()
|
||||||
|
|
||||||
|
|
||||||
|
def _rule() -> str:
|
||||||
|
return "-" * WIDTH
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# TUI
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
class TUI:
|
||||||
|
"""Menu-driven bilingual interface over :class:`~chaoscrypt.ChaosCrypt`."""
|
||||||
|
|
||||||
|
def __init__(self, lang: str = DEFAULT_LANG,
|
||||||
|
key_file: str = DEFAULT_KEY_FILE,
|
||||||
|
mode: str = DEFAULT_MODE,
|
||||||
|
encoding: str = DEFAULT_ENCODING) -> None:
|
||||||
|
self.lang = lang if lang in LANG_NAMES else DEFAULT_LANG
|
||||||
|
self.key_file = key_file
|
||||||
|
self.mode = mode if mode in MODES else DEFAULT_MODE
|
||||||
|
self.encoding = encoding if encoding in ENCODINGS else DEFAULT_ENCODING
|
||||||
|
self.cc = ChaosCrypt(mode=self.mode, encoding=self.encoding)
|
||||||
|
self.key_password: Optional[str] = None
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------ view
|
||||||
|
def _tr(self, key: str) -> str:
|
||||||
|
return t(key, self.lang)
|
||||||
|
|
||||||
|
def banner(self) -> None:
|
||||||
|
print()
|
||||||
|
print(c("+" + "=" * (WIDTH - 2) + "+", "magenta"))
|
||||||
|
title = f" {self._tr('app_title')} v{__version__}"
|
||||||
|
print(c("|", "magenta")
|
||||||
|
+ c(title.ljust(WIDTH - 2), "bold", "cyan")
|
||||||
|
+ c("|", "magenta"))
|
||||||
|
print(c("+" + "=" * (WIDTH - 2) + "+", "magenta"))
|
||||||
|
for line in self._tr("warn_banner").split("\n"):
|
||||||
|
print(c(line, "yellow"))
|
||||||
|
|
||||||
|
shown = self.cc.key_file or self.key_file or DEFAULT_KEY_FILE
|
||||||
|
state = (
|
||||||
|
c("[*] " + self._tr("key_loaded"), "green")
|
||||||
|
if self.cc.loaded
|
||||||
|
else c("[ ] " + self._tr("no_key_loaded"), "red")
|
||||||
|
)
|
||||||
|
print(f"\n{state} {c(shown, 'dim')} {c('[' + self.mode + ']', 'yellow')}")
|
||||||
|
|
||||||
|
def _print_error(self, exc: Exception) -> None:
|
||||||
|
"""Render a unified error, with a hint where one applies."""
|
||||||
|
print()
|
||||||
|
print(c("+" + "-" * (WIDTH - 2) + "+", "red"))
|
||||||
|
print(c("| ", "red")
|
||||||
|
+ c(f"{self._tr('err_prefix')}: {exc}", "red", "bold"))
|
||||||
|
print(c("+" + "-" * (WIDTH - 2) + "+", "red"))
|
||||||
|
|
||||||
|
msg = str(exc)
|
||||||
|
if "_E011" in msg or "_E003" in msg:
|
||||||
|
print(c(" " + self._tr("err_hint_password"), "dim"))
|
||||||
|
elif "_E004" in msg or "_E001" in msg:
|
||||||
|
print(c(" " + self._tr("err_hint_key_required"), "dim"))
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------ menu
|
||||||
|
def menu(self) -> str:
|
||||||
|
items = [
|
||||||
|
("1", "menu_encrypt"),
|
||||||
|
("2", "menu_decrypt"),
|
||||||
|
("3", "menu_encrypt_file"),
|
||||||
|
("4", "menu_decrypt_file"),
|
||||||
|
("5", "menu_keygen"),
|
||||||
|
("6", "menu_loadkey"),
|
||||||
|
("7", "menu_keyinfo"),
|
||||||
|
("8", "menu_chpwd"),
|
||||||
|
("9", "menu_lang"),
|
||||||
|
("m", "menu_mode"),
|
||||||
|
("e", "menu_encoding"),
|
||||||
|
("a", "menu_about"),
|
||||||
|
("q", "menu_quit"),
|
||||||
|
]
|
||||||
|
print()
|
||||||
|
print(c(_rule(), "dim"))
|
||||||
|
print(c(" " + self._tr("menu_choose"), "bold"))
|
||||||
|
print(c(_rule(), "dim"))
|
||||||
|
for key, label in items:
|
||||||
|
print(f" {c('[' + key + ']', 'cyan')} {self._tr(label)}")
|
||||||
|
print(c(_rule(), "dim"))
|
||||||
|
return _ask(self._tr("menu_prompt")).lower()
|
||||||
|
|
||||||
|
# ------------------------------------------------------------ key state
|
||||||
|
def _ensure_key(self) -> bool:
|
||||||
|
"""Make sure a key is loaded, offering to create one if none exists.
|
||||||
|
|
||||||
|
Searches the instance's loaded key, then the remembered file, then
|
||||||
|
the default name.
|
||||||
|
"""
|
||||||
|
if self.cc.loaded:
|
||||||
|
return True
|
||||||
|
|
||||||
|
path = (
|
||||||
|
self.cc.key_file
|
||||||
|
or self.key_file
|
||||||
|
or DEFAULT_KEY_FILE
|
||||||
|
)
|
||||||
|
self.key_file = path
|
||||||
|
|
||||||
|
if not os.path.exists(path):
|
||||||
|
if _ask_yes_no(self._tr("prompt_create_if_missing"), self.lang):
|
||||||
|
return self.action_keygen()
|
||||||
|
return False
|
||||||
|
|
||||||
|
try:
|
||||||
|
pwd = self.key_password or _ask_secret(self._tr("prompt_key_password"))
|
||||||
|
self.cc.load(path, pwd)
|
||||||
|
self.key_password = pwd
|
||||||
|
print(c(f"{self._tr('key_loaded')}: {path}", "green"))
|
||||||
|
return True
|
||||||
|
except ChaosCryptError as exc:
|
||||||
|
self._print_error(exc)
|
||||||
|
return False
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- actions
|
||||||
|
def action_encrypt(self) -> None:
|
||||||
|
if not self._ensure_key():
|
||||||
|
return
|
||||||
|
text = _ask(self._tr("prompt_plaintext"))
|
||||||
|
if not text:
|
||||||
|
print(c(" " + self._tr("cancelled"), "dim"))
|
||||||
|
return
|
||||||
|
pwd = _ask_secret(self._tr("prompt_user_password"))
|
||||||
|
try:
|
||||||
|
ct = self.cc.encrypt(text, pwd)
|
||||||
|
print()
|
||||||
|
print(c(f"{self._tr('result_ciphertext')}:", "green", "bold"))
|
||||||
|
print(c(ct, "cyan"))
|
||||||
|
except ChaosCryptError as exc:
|
||||||
|
self._print_error(exc)
|
||||||
|
|
||||||
|
def action_decrypt(self) -> None:
|
||||||
|
if not self._ensure_key():
|
||||||
|
return
|
||||||
|
text = _ask(self._tr("prompt_ciphertext"))
|
||||||
|
if not text:
|
||||||
|
print(c(" " + self._tr("cancelled"), "dim"))
|
||||||
|
return
|
||||||
|
pwd = _ask_secret(self._tr("prompt_user_password"))
|
||||||
|
try:
|
||||||
|
pt = self.cc.decrypt(text, pwd)
|
||||||
|
print()
|
||||||
|
print(c(f"{self._tr('result_plaintext')}:", "green", "bold"))
|
||||||
|
print(c(pt, "cyan"))
|
||||||
|
except ChaosCryptError as exc:
|
||||||
|
self._print_error(exc)
|
||||||
|
|
||||||
|
def action_encrypt_file(self) -> None:
|
||||||
|
if not self._ensure_key():
|
||||||
|
return
|
||||||
|
src = _ask(self._tr("prompt_src_file"))
|
||||||
|
if not src or not os.path.exists(src):
|
||||||
|
print(c(f" {self._tr('failed')}: {src}", "red"))
|
||||||
|
return
|
||||||
|
dst = _ask(self._tr("prompt_dst_file")) or None
|
||||||
|
pwd = _ask_secret(self._tr("prompt_user_password"))
|
||||||
|
try:
|
||||||
|
out = self.cc.encrypt_file(src, pwd, dst)
|
||||||
|
print(c(f"{self._tr('file_written')}: {out}", "green"))
|
||||||
|
except ChaosCryptError as exc:
|
||||||
|
self._print_error(exc)
|
||||||
|
|
||||||
|
def action_decrypt_file(self) -> None:
|
||||||
|
if not self._ensure_key():
|
||||||
|
return
|
||||||
|
src = _ask(self._tr("prompt_src_file"))
|
||||||
|
if not src or not os.path.exists(src):
|
||||||
|
print(c(f" {self._tr('failed')}: {src}", "red"))
|
||||||
|
return
|
||||||
|
dst = _ask(self._tr("prompt_dst_file")) or None
|
||||||
|
pwd = _ask_secret(self._tr("prompt_user_password"))
|
||||||
|
try:
|
||||||
|
out = self.cc.decrypt_file(src, pwd, dst)
|
||||||
|
print(c(f"{self._tr('file_written')}: {out}", "green"))
|
||||||
|
except ChaosCryptError as exc:
|
||||||
|
self._print_error(exc)
|
||||||
|
|
||||||
|
def action_keygen(self) -> bool:
|
||||||
|
default = self.cc.key_file or self.key_file or DEFAULT_KEY_FILE
|
||||||
|
path = _ask(self._tr("prompt_key_file"), default)
|
||||||
|
|
||||||
|
overwrite = False
|
||||||
|
if os.path.exists(path):
|
||||||
|
if not _ask_yes_no(self._tr("prompt_overwrite"), self.lang):
|
||||||
|
print(c(" " + self._tr("cancelled"), "dim"))
|
||||||
|
return False
|
||||||
|
overwrite = True
|
||||||
|
|
||||||
|
pwd = _ask_secret(self._tr("prompt_key_password_new"))
|
||||||
|
if not pwd:
|
||||||
|
print(c(" " + self._tr("failed"), "red"))
|
||||||
|
return False
|
||||||
|
confirm = _ask_secret(self._tr("prompt_key_password_confirm"))
|
||||||
|
if pwd != confirm:
|
||||||
|
print(c(" ChaosCrypt_ERR_PasswordMismatch_E007", "red"))
|
||||||
|
return False
|
||||||
|
|
||||||
|
try:
|
||||||
|
out = self.cc.create_key(pwd, path, overwrite=overwrite)
|
||||||
|
self.key_file = out
|
||||||
|
self.key_password = pwd
|
||||||
|
print(c(f"{self._tr('key_saved')}: {out}", "green"))
|
||||||
|
return True
|
||||||
|
except ChaosCryptError as exc:
|
||||||
|
self._print_error(exc)
|
||||||
|
return False
|
||||||
|
|
||||||
|
def action_loadkey(self) -> None:
|
||||||
|
default = self.cc.key_file or self.key_file or DEFAULT_KEY_FILE
|
||||||
|
path = _ask(self._tr("prompt_key_file"), default)
|
||||||
|
pwd = _ask_secret(self._tr("prompt_key_password"))
|
||||||
|
try:
|
||||||
|
self.cc.load(path, pwd)
|
||||||
|
self.key_file = path
|
||||||
|
self.key_password = pwd
|
||||||
|
print(c(f"{self._tr('key_loaded')}: {path}", "green"))
|
||||||
|
except ChaosCryptError as exc:
|
||||||
|
self._print_error(exc)
|
||||||
|
|
||||||
|
def action_keyinfo(self) -> None:
|
||||||
|
if not self._ensure_key():
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
info = self.cc.info()
|
||||||
|
except ChaosCryptError as exc:
|
||||||
|
self._print_error(exc)
|
||||||
|
return
|
||||||
|
|
||||||
|
rows = [
|
||||||
|
("info_key_file", info["key_file"]),
|
||||||
|
("info_version", info["version"]),
|
||||||
|
("info_upper", info["upper_mapping"]),
|
||||||
|
("info_lower", info["lower_mapping"]),
|
||||||
|
("info_digit", "".join(info["digit_mapping"].values())),
|
||||||
|
("info_equal", "".join(info["equal_mapping"].values())),
|
||||||
|
("info_flip", info["flip_pattern"]),
|
||||||
|
("info_long_key",
|
||||||
|
f"{info['long_key_length']} {self._tr('characters')}"),
|
||||||
|
("info_short_key",
|
||||||
|
f"{info['short_key_length']} {self._tr('characters')}"),
|
||||||
|
("info_loaded", self._tr("yes")),
|
||||||
|
("info_mode", self.mode),
|
||||||
|
("info_encoding", self.encoding),
|
||||||
|
]
|
||||||
|
print()
|
||||||
|
print(c(_rule(), "dim"))
|
||||||
|
for key, val in rows:
|
||||||
|
print(f" {c(self._tr(key), 'bold'):<38} {val}")
|
||||||
|
print(c(_rule(), "dim"))
|
||||||
|
|
||||||
|
def action_chpwd(self) -> None:
|
||||||
|
default = self.cc.key_file or self.key_file or DEFAULT_KEY_FILE
|
||||||
|
path = _ask(self._tr("prompt_key_file"), default)
|
||||||
|
if not os.path.exists(path):
|
||||||
|
print(c(" ChaosCrypt_ERR_KeyFileNotFound_E001", "red"))
|
||||||
|
return
|
||||||
|
old = _ask_secret(self._tr("prompt_key_password_old"))
|
||||||
|
new = _ask_secret(self._tr("prompt_key_password_new"))
|
||||||
|
confirm = _ask_secret(self._tr("prompt_key_password_confirm"))
|
||||||
|
if new != confirm:
|
||||||
|
print(c(" ChaosCrypt_ERR_PasswordMismatch_E007", "red"))
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
out = self.cc.change_key_password(old, new, path)
|
||||||
|
self.key_password = new
|
||||||
|
print(c(f"{self._tr('key_password_changed')}: {out}", "green"))
|
||||||
|
except ChaosCryptError as exc:
|
||||||
|
self._print_error(exc)
|
||||||
|
|
||||||
|
def action_lang(self) -> None:
|
||||||
|
codes = list(LANG_NAMES.keys())
|
||||||
|
print()
|
||||||
|
for i, (code, name) in enumerate(LANG_NAMES.items(), 1):
|
||||||
|
mark = "*" if code == self.lang else " "
|
||||||
|
print(f" {c('[' + str(i) + ']', 'cyan')} {mark} {name} ({code})")
|
||||||
|
|
||||||
|
default_index = str(codes.index(self.lang) + 1) if self.lang in codes else "1"
|
||||||
|
choice = _ask("Language", default_index)
|
||||||
|
try:
|
||||||
|
idx = int(choice) - 1
|
||||||
|
if 0 <= idx < len(codes):
|
||||||
|
self.lang = codes[idx]
|
||||||
|
except ValueError:
|
||||||
|
if choice in codes:
|
||||||
|
self.lang = choice
|
||||||
|
print(c(f" -> {LANG_NAMES[self.lang]}", "green"))
|
||||||
|
|
||||||
|
def action_mode(self) -> None:
|
||||||
|
"""Switch the performance mode of the active core."""
|
||||||
|
print()
|
||||||
|
for i, name in enumerate(MODES, 1):
|
||||||
|
mark = "*" if name == self.mode else " "
|
||||||
|
desc = self._tr(f"mode_{name}_desc")
|
||||||
|
print(f" {c('[' + str(i) + ']', 'cyan')} {mark} {desc}")
|
||||||
|
|
||||||
|
default_index = str(MODES.index(self.mode) + 1)
|
||||||
|
choice = _ask(self._tr("mode_prompt"), default_index)
|
||||||
|
try:
|
||||||
|
idx = int(choice) - 1
|
||||||
|
if 0 <= idx < len(MODES):
|
||||||
|
self.mode = MODES[idx]
|
||||||
|
except ValueError:
|
||||||
|
if choice in MODES:
|
||||||
|
self.mode = choice
|
||||||
|
|
||||||
|
# Rebuild the core so the new mode takes effect, then reload the key
|
||||||
|
# if one was already loaded so the user does not have to re-enter the
|
||||||
|
# password.
|
||||||
|
was_loaded = self.cc.loaded
|
||||||
|
path = self.cc.key_file or self.key_file
|
||||||
|
pwd = self.key_password
|
||||||
|
self.cc = ChaosCrypt(mode=self.mode, encoding=self.encoding)
|
||||||
|
if was_loaded and path and pwd:
|
||||||
|
try:
|
||||||
|
self.cc.load(path, pwd)
|
||||||
|
except ChaosCryptError:
|
||||||
|
pass
|
||||||
|
print(c(f" -> {self._tr('mode_changed')} {self.mode}", "green"))
|
||||||
|
|
||||||
|
def action_encoding(self) -> None:
|
||||||
|
"""Switch the output encoding (turbo and raw only)."""
|
||||||
|
print()
|
||||||
|
for i, name in enumerate(ENCODINGS, 1):
|
||||||
|
mark = "*" if name == self.encoding else " "
|
||||||
|
desc = self._tr(f"encoding_{name}_desc")
|
||||||
|
print(f" {c('[' + str(i) + ']', 'cyan')} {mark} {desc}")
|
||||||
|
print(c(" " + self._tr("encoding_note"), "dim"))
|
||||||
|
|
||||||
|
default_index = str(ENCODINGS.index(self.encoding) + 1)
|
||||||
|
choice = _ask(self._tr("encoding_prompt"), default_index)
|
||||||
|
try:
|
||||||
|
idx = int(choice) - 1
|
||||||
|
if 0 <= idx < len(ENCODINGS):
|
||||||
|
self.encoding = ENCODINGS[idx]
|
||||||
|
except ValueError:
|
||||||
|
if choice in ENCODINGS:
|
||||||
|
self.encoding = choice
|
||||||
|
|
||||||
|
# Rebuild so the new encoding applies, then restore the loaded key.
|
||||||
|
was_loaded = self.cc.loaded
|
||||||
|
path = self.cc.key_file or self.key_file
|
||||||
|
pwd = self.key_password
|
||||||
|
self.cc = ChaosCrypt(mode=self.mode, encoding=self.encoding)
|
||||||
|
if was_loaded and path and pwd:
|
||||||
|
try:
|
||||||
|
self.cc.load(path, pwd)
|
||||||
|
except ChaosCryptError:
|
||||||
|
pass
|
||||||
|
print(c(f" -> {self._tr('encoding_changed')} {self.encoding}", "green"))
|
||||||
|
|
||||||
|
def action_about(self) -> None:
|
||||||
|
print()
|
||||||
|
print(c(self._tr("about_body"), "cyan"))
|
||||||
|
|
||||||
|
# ------------------------------------------------------------- main loop
|
||||||
|
def run(self) -> int:
|
||||||
|
while True:
|
||||||
|
self.banner()
|
||||||
|
try:
|
||||||
|
choice = self.menu()
|
||||||
|
except _Abort:
|
||||||
|
print()
|
||||||
|
print(c(self._tr("bye"), "green"))
|
||||||
|
return 0
|
||||||
|
|
||||||
|
try:
|
||||||
|
if choice == "1":
|
||||||
|
self.action_encrypt()
|
||||||
|
elif choice == "2":
|
||||||
|
self.action_decrypt()
|
||||||
|
elif choice == "3":
|
||||||
|
self.action_encrypt_file()
|
||||||
|
elif choice == "4":
|
||||||
|
self.action_decrypt_file()
|
||||||
|
elif choice == "5":
|
||||||
|
self.action_keygen()
|
||||||
|
elif choice == "6":
|
||||||
|
self.action_loadkey()
|
||||||
|
elif choice == "7":
|
||||||
|
self.action_keyinfo()
|
||||||
|
elif choice == "8":
|
||||||
|
self.action_chpwd()
|
||||||
|
elif choice == "9":
|
||||||
|
self.action_lang()
|
||||||
|
elif choice in ("m", "mode"):
|
||||||
|
self.action_mode()
|
||||||
|
elif choice in ("e", "encoding"):
|
||||||
|
self.action_encoding()
|
||||||
|
elif choice in ("a", "about"):
|
||||||
|
self.action_about()
|
||||||
|
elif choice in ("q", "quit", "exit"):
|
||||||
|
print()
|
||||||
|
print(c(self._tr("bye"), "green"))
|
||||||
|
return 0
|
||||||
|
else:
|
||||||
|
print(c(" " + self._tr("menu_invalid"), "yellow"))
|
||||||
|
continue
|
||||||
|
except _Abort:
|
||||||
|
print(c(" " + self._tr("cancelled"), "dim"))
|
||||||
|
continue
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
print()
|
||||||
|
print(c(self._tr("bye"), "green"))
|
||||||
|
return 0
|
||||||
|
|
||||||
|
_pause(self.lang)
|
||||||
|
|
||||||
|
|
||||||
|
def run_tui(lang: str = DEFAULT_LANG,
|
||||||
|
key_file: str = DEFAULT_KEY_FILE) -> int:
|
||||||
|
"""Launch the interactive UI and return the process exit code."""
|
||||||
|
try:
|
||||||
|
return TUI(lang=lang, key_file=key_file).run()
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
print()
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__": # pragma: no cover
|
||||||
|
sys.exit(run_tui())
|
||||||
+585
@@ -0,0 +1,585 @@
|
|||||||
|
# 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"` |
|
||||||
|
| `MODES` | constant | Tuple of the four mode names |
|
||||||
|
| `DEFAULT_MODE` | constant | `"fast"` |
|
||||||
|
| `MODE_REFERENCE` | constant | `"reference"` |
|
||||||
|
| `MODE_FAST` | constant | `"fast"` |
|
||||||
|
| `MODE_TURBO` | constant | `"turbo"` |
|
||||||
|
| `MODE_RAW` | constant | `"raw"` |
|
||||||
|
| `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 |
|
||||||
|
| `mode` | `str` | `"fast"` | Performance mode: `reference`, `fast`, `turbo` or `raw` |
|
||||||
|
| `encoding` | `str` | `"hex"` | Output encoding for `turbo`/`raw`: `hex` or `base64` (also accepted as `base`) |
|
||||||
|
| `mid` | `str` | `"bt"` | Intermediate representation for `turbo`/`raw`: `bt` or `hex` (also accepted as `bytes`) |
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Performance modes
|
||||||
|
|
||||||
|
Four modes, plus two settings that apply to the two byte-pipeline modes.
|
||||||
|
|
||||||
|
| Constant | Value | Pipeline | Ciphertext |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `MODE_REFERENCE` | `"reference"` | original algorithm, character pipeline | hex, 5.33x |
|
||||||
|
| `MODE_FAST` | `"fast"` | same algorithm, bulk operations | hex, 5.33x |
|
||||||
|
| `MODE_TURBO` | `"turbo"` | SHAKE256 keystream, byte pipeline | 2.00x / 1.33x |
|
||||||
|
| `MODE_RAW` | `"raw"` | SHAKE256 plus the long-key layer | 2.00x / 1.33x |
|
||||||
|
|
||||||
|
```python
|
||||||
|
from chaoscrypt import ChaosCrypt, MODES, DEFAULT_MODE
|
||||||
|
|
||||||
|
print(MODES) # ('reference', 'fast', 'turbo', 'raw')
|
||||||
|
print(DEFAULT_MODE) # 'fast'
|
||||||
|
```
|
||||||
|
|
||||||
|
### Settings for the byte-pipeline modes
|
||||||
|
|
||||||
|
| Constant | Value | Applies to | Meaning |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `ENC_HEX` | `"hex"` | `turbo`, `raw` | Two characters per octet (2.00x) |
|
||||||
|
| `ENC_BASE64` | `"base64"` | `turbo`, `raw` | Four characters per three octets (1.33x) |
|
||||||
|
| `MID_BYTES` | `"bt"` | `turbo`, `raw` | XOR layers exchange raw bytes |
|
||||||
|
| `MID_HEX` | `"hex"` | `turbo`, `raw` | XOR layers exchange hexadecimal text |
|
||||||
|
|
||||||
|
```python
|
||||||
|
from chaoscrypt import ChaosCrypt
|
||||||
|
|
||||||
|
cc = ChaosCrypt(mode="raw", encoding="base64", mid="bt")
|
||||||
|
cc.load("my.key", "key-password")
|
||||||
|
|
||||||
|
token = cc.encrypt("hello", "user-password")
|
||||||
|
```
|
||||||
|
|
||||||
|
```python
|
||||||
|
from chaoscrypt import ChaosCryptCore, MODE_TURBO, ENC_BASE64, MID_HEX
|
||||||
|
|
||||||
|
core = ChaosCryptCore(MODE_TURBO, "hash", ENC_BASE64, MID_HEX)
|
||||||
|
core.generate_keymaterial()
|
||||||
|
token = core.encrypt_text("hello", "password")
|
||||||
|
assert core.decrypt_text(token, "password") == "hello"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Which mode to choose
|
||||||
|
|
||||||
|
| If you… | Use |
|
||||||
|
|---|---|
|
||||||
|
| Are not sure | `fast` — the default |
|
||||||
|
| Need maximum speed from a standardised keystream primitive | `raw` with `mid="bt"` |
|
||||||
|
| Need the smallest ciphertext | `turbo` or `raw` with `encoding="base64"` |
|
||||||
|
| Need to interoperate with the character pipeline's shape | `mid="hex"` |
|
||||||
|
| Need a payload byte-compatible with pre-4.2.6 material | `reference` or `fast` |
|
||||||
|
|
||||||
|
`fast` performs the same arithmetic as `reference` and produces the same bytes;
|
||||||
|
only the implementation differs. `turbo` and `raw` change the algorithm and
|
||||||
|
define their own formats.
|
||||||
|
|
||||||
|
> **Artefacts are not interchangeable between mode families**, and `turbo`/`raw`
|
||||||
|
> artefacts are also specific to their `encoding` and `mid`. The header records
|
||||||
|
> all three, so a reader configured differently still reads the artefact
|
||||||
|
> correctly — the ordinary decrypt takes its parameters from the header.
|
||||||
|
|
||||||
|
An unrecognised `mode`, `encoding` or `mid` raises `ValueError` at construction.
|
||||||
|
|
||||||
|
## Reading pre-4.2.6 artefacts
|
||||||
|
|
||||||
|
Artefacts written before the header existed have none, and are rejected by the
|
||||||
|
ordinary path with `E017`. They are read through the compatibility API, which
|
||||||
|
synthesises a minimal header and then uses the ordinary path.
|
||||||
|
|
||||||
|
```python
|
||||||
|
from chaoscrypt import ChaosCrypt
|
||||||
|
|
||||||
|
cc = ChaosCrypt(key_file="my.key", key_password="kf-pwd", auto_load=True)
|
||||||
|
|
||||||
|
# a ciphertext with no header
|
||||||
|
plain = cc.decrypt_legacy(old_ciphertext, "user-password")
|
||||||
|
|
||||||
|
# if you know it is a legacy key file
|
||||||
|
cc.load_legacy_keys(old_key_text, "key-password")
|
||||||
|
|
||||||
|
# let the library work out which it is
|
||||||
|
plain = cc.decrypt_legacy_auto(old_ciphertext, "user-password")
|
||||||
|
|
||||||
|
# migrate once, then use the modern path
|
||||||
|
open("new.key", "w", encoding="utf-8").write(
|
||||||
|
cc.wrap_legacy(old_key_text, is_key=True)
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
| Method | Purpose |
|
||||||
|
|---|---|
|
||||||
|
| `wrap_legacy(text, is_key=False)` | Prefix a minimal header; the payload is untouched. Idempotent. |
|
||||||
|
| `decrypt_legacy(text, password, is_key=False)` | Read an artefact that may predate the header |
|
||||||
|
| `decrypt_legacy_auto(text, password)` | As above, probing whether the input is a key file or a ciphertext |
|
||||||
|
| `load_legacy_keys(text, key_password)` | Load a pre-header key file |
|
||||||
|
|
||||||
|
`is_old` in the synthesised header means every other field is ignored; the
|
||||||
|
legacy path tries `fast` and falls back to `reference`. Both implement the
|
||||||
|
original algorithm.
|
||||||
|
|
||||||
|
> The compatibility API is a **wrapper** around the ordinary path, never a
|
||||||
|
> lenient branch inside it. Passing headerless input to `decrypt` still raises
|
||||||
|
> `E017`.
|
||||||
|
|
||||||
|
See [FORMAT.md §12](FORMAT.md) for the legacy standard.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 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 |
|
||||||
|
| `E017` | `ChaosCrypt_ERR_MissingMagicHeader_E017` | Input is not a CES artefact |
|
||||||
|
| `E018` | `ChaosCrypt_ERR_MalformedHeader_E018` | Header unusable, or `kind` mismatch |
|
||||||
|
|
||||||
|
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.
|
||||||
@@ -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_<Detail>_<Code>`.
|
||||||
|
|
||||||
|
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.
|
||||||
@@ -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.
|
||||||
+408
@@ -0,0 +1,408 @@
|
|||||||
|
# Command Line Reference
|
||||||
|
|
||||||
|
Complete reference for the `chaoscrypt` command.
|
||||||
|
|
||||||
|
```
|
||||||
|
chaoscrypt # no arguments -> interactive TUI
|
||||||
|
chaoscrypt <command> [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 : <hidden, 26 chars>
|
||||||
|
lower_mapping : <hidden, 26 chars>
|
||||||
|
digit_mapping : <hidden, 10 chars>
|
||||||
|
equal_mapping : <hidden, 4 chars>
|
||||||
|
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 <command> --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
|
||||||
|
```
|
||||||
+618
@@ -0,0 +1,618 @@
|
|||||||
|
# CES Artifact Format Specification
|
||||||
|
|
||||||
|
**Normative reference for the ChaosCrypt (CES) container format**
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| Format version | 1 |
|
||||||
|
| Status | Normative |
|
||||||
|
| Applies to | Key files and ciphertexts produced from 4.2.6 onward |
|
||||||
|
| Library | `chaoscrypt` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Scope
|
||||||
|
|
||||||
|
This document specifies the byte-level layout of every artefact the library
|
||||||
|
produces. It is the authority for implementers: where this document and the
|
||||||
|
code disagree, this document is wrong and the code is to be fixed.
|
||||||
|
|
||||||
|
It defines:
|
||||||
|
|
||||||
|
- the fixed magic and delimiter values;
|
||||||
|
- the layout of the self-describing header;
|
||||||
|
- the complete field set of the configuration record;
|
||||||
|
- the payload that follows;
|
||||||
|
- the conformance requirements a reader must enforce.
|
||||||
|
|
||||||
|
It does **not** describe the cipher itself. For the algorithm see
|
||||||
|
[SECURITY.md](../SECURITY.md); for performance see [benchmark.md](benchmark.md).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Design rationale
|
||||||
|
|
||||||
|
Every artefact carries a header that states how it was produced. The reader
|
||||||
|
never infers a parameter from context and never guesses.
|
||||||
|
|
||||||
|
Earlier revisions left the mode and encoding to the caller's memory. That is a
|
||||||
|
silent-corruption hazard: a ciphertext decrypted under the wrong mode yields
|
||||||
|
garbage that is indistinguishable from a wrong password. Recording the
|
||||||
|
parameters alongside the artefact removes the ambiguity, and rejecting
|
||||||
|
headerless input removes the guesswork entirely.
|
||||||
|
|
||||||
|
The consequence is deliberate and absolute: **input without a valid header is
|
||||||
|
rejected, not interpreted.**
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Fixed values
|
||||||
|
|
||||||
|
These byte sequences are constants of the format. They are reproduced in three
|
||||||
|
representations for convenience; all three denote the same octets.
|
||||||
|
|
||||||
|
### 3.1 Magic
|
||||||
|
|
||||||
|
| Representation | Value |
|
||||||
|
|---|---|
|
||||||
|
| Bytes | `b"69CES"` |
|
||||||
|
| Hex | `3639434553` |
|
||||||
|
| Decimal byte list | `[54, 57, 67, 69, 83]` |
|
||||||
|
|
||||||
|
Length: 5 octets. Position: the first octet of every artefact.
|
||||||
|
|
||||||
|
### 3.2 Begin marker
|
||||||
|
|
||||||
|
```
|
||||||
|
385aeff1f4179a744c8fb0c5ae4702d325f6230d059f4251135c2536409dee93
|
||||||
|
```
|
||||||
|
|
||||||
|
64 characters of lowercase hexadecimal. Written verbatim; it is **not** decoded
|
||||||
|
before comparison.
|
||||||
|
|
||||||
|
### 3.3 End marker
|
||||||
|
|
||||||
|
```
|
||||||
|
2025ea4e4b4b93803f2ccadeaf318d1957ce42ff5409410f660348be96a4c0f2
|
||||||
|
```
|
||||||
|
|
||||||
|
64 characters of lowercase hexadecimal. Written verbatim.
|
||||||
|
|
||||||
|
> **Note.** Both markers are fixed constants of format version 1. They are
|
||||||
|
> delimiters, not integrity checks: they carry no signature semantics and do
|
||||||
|
> not authenticate the payload. Message integrity, where required, is provided
|
||||||
|
> by the cipher and by an external MAC.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Container layout
|
||||||
|
|
||||||
|
An artefact is a single character string with five regions:
|
||||||
|
|
||||||
|
```
|
||||||
|
+-------------------------------------------------------------------+
|
||||||
|
| MAGIC "69CES" 5 octets |
|
||||||
|
+-------------------------------------------------------------------+
|
||||||
|
| BEGIN MARKER 64 hex chars |
|
||||||
|
+-------------------------------------------------------------------+
|
||||||
|
| CONFIGURATION UTF-8 JSON object variable |
|
||||||
|
+-------------------------------------------------------------------+
|
||||||
|
| END MARKER 64 hex chars |
|
||||||
|
+-------------------------------------------------------------------+
|
||||||
|
| PAYLOAD key material or ciphertext variable |
|
||||||
|
+-------------------------------------------------------------------+
|
||||||
|
```
|
||||||
|
|
||||||
|
The three fixed regions are literals. Only the configuration and the payload
|
||||||
|
vary between artefacts.
|
||||||
|
|
||||||
|
### 4.1 Formal grammar
|
||||||
|
|
||||||
|
```
|
||||||
|
artifact = MAGIC begin-marker config end-marker payload
|
||||||
|
MAGIC = "69CES"
|
||||||
|
begin-marker= %s"385aeff1f4179a744c8fb0c5ae4702d325f6230d059f4251135c2536409dee93"
|
||||||
|
end-marker = %s"2025ea4e4b4b93803f2ccadeaf318d1957ce42ff5409410f660348be96a4c0f2"
|
||||||
|
config = <UTF-8 encoded JSON object, see section 5>
|
||||||
|
payload = <encoding-dependent text, see section 6>
|
||||||
|
```
|
||||||
|
|
||||||
|
There is no whitespace, newline or padding between regions. A reader must not
|
||||||
|
skip optional characters.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Configuration record
|
||||||
|
|
||||||
|
The configuration is a JSON object encoded as UTF-8, with no line breaks.
|
||||||
|
Keys are sorted; separators are `,` and `:` with no surrounding spaces. The
|
||||||
|
canonical form is therefore deterministic: the same configuration always
|
||||||
|
renders as the same octets.
|
||||||
|
|
||||||
|
### 5.1 Required fields
|
||||||
|
|
||||||
|
A configuration missing any of these is invalid, and the artefact must be
|
||||||
|
rejected rather than partially interpreted.
|
||||||
|
|
||||||
|
| Field | Type | Meaning |
|
||||||
|
|---|---|---|
|
||||||
|
| `kind` | string | `"ciphertext"` or `"key"` |
|
||||||
|
| `v` | integer | Format version; `1` for this specification |
|
||||||
|
| `mode` | string | Performance mode, see §5.2 |
|
||||||
|
| `mid` | string | Intermediate representation, see §5.3 |
|
||||||
|
| `out` | string | Output encoding, see §5.4 |
|
||||||
|
| `alg` | string | Algorithm family; `"chaoscrypt"` |
|
||||||
|
| `kdf` | string | Keystream derivation, see §5.5 |
|
||||||
|
| `keybits` | integer | Length of the long key in bits |
|
||||||
|
| `ksum` | string | Non-secret key digest, see §5.6 |
|
||||||
|
|
||||||
|
### 5.2 `mode`
|
||||||
|
|
||||||
|
| Value | Pipeline |
|
||||||
|
|---|---|
|
||||||
|
| `reference` | Original algorithm, character pipeline |
|
||||||
|
| `fast` | Original algorithm, bulk-operation implementation |
|
||||||
|
| `turbo` | SHAKE256 keystream, byte pipeline |
|
||||||
|
| `raw` | SHAKE256 keystream, byte pipeline with the long-key layer retained |
|
||||||
|
|
||||||
|
`reference` and `fast` produce identical ciphertexts. The distinction is
|
||||||
|
recorded so a reader can report which implementation wrote the artefact; it
|
||||||
|
does not affect decryption.
|
||||||
|
|
||||||
|
### 5.3 `mid` — intermediate representation
|
||||||
|
|
||||||
|
The `mid` field names how the two XOR layers of the byte pipeline exchange
|
||||||
|
their data. It is only meaningful for `turbo` and `raw`; for the character
|
||||||
|
pipelines it is descriptive.
|
||||||
|
|
||||||
|
| Value | Meaning |
|
||||||
|
|---|---|
|
||||||
|
| `bt` | Intermediate values carried as raw bytes (default) |
|
||||||
|
| `hex` | Intermediate values carried as hexadecimal text |
|
||||||
|
|
||||||
|
`turbo` and `raw` accept either value, and `bt` is the default. The choice is
|
||||||
|
recorded in the header and honoured when the artefact is read: a `turbo` or
|
||||||
|
`raw` artefact is decrypted with the `mid` it carries, and no fallback to the
|
||||||
|
other representation is attempted.
|
||||||
|
|
||||||
|
`reference` and `fast` are character pipelines and always use `hex`. They
|
||||||
|
ignore `mid`: whatever value is supplied, the header records `hex` for them.
|
||||||
|
|
||||||
|
**Expansion.** `bt` passes the bytes between the XOR layers unchanged, so the
|
||||||
|
only growth is the output encoding: 2.00x with `hex` output, 1.33x with
|
||||||
|
`base` output. `hex` re-encodes each layer's output as hexadecimal text
|
||||||
|
before the next layer consumes it; with the two layers of this format that
|
||||||
|
doubles the payload at each layer, so the byte payload handed to the output
|
||||||
|
encoder is about **4x** the `bt` size (roughly 8 hexadecimal characters per
|
||||||
|
input octet with `hex` output).
|
||||||
|
|
||||||
|
**Speed.** `bt` is about **4x faster** than `hex`: it skips the per-layer hex
|
||||||
|
encode and decode and XORs the shorter byte buffers directly. It is therefore
|
||||||
|
the default.
|
||||||
|
|
||||||
|
### 5.4 `out` — output encoding
|
||||||
|
|
||||||
|
| Value | Meaning | Expansion |
|
||||||
|
|---|---|---|
|
||||||
|
| `hex` | Two characters per octet | 2.00x |
|
||||||
|
| `base` | Base64, four characters per three octets | 1.33x |
|
||||||
|
|
||||||
|
`reference` and `fast` always emit `hex` and ignore any attempt to set it.
|
||||||
|
`turbo` and `raw` accept either.
|
||||||
|
|
||||||
|
> **Reader requirement.** The payload must be decoded according to `out`.
|
||||||
|
> Attempting to decode with the wrong encoding must fail, never silently produce
|
||||||
|
> a different result.
|
||||||
|
|
||||||
|
### 5.5 `kdf` — keystream derivation
|
||||||
|
|
||||||
|
| Value | Meaning |
|
||||||
|
|---|---|
|
||||||
|
| `expand` | Hand-rolled mixing and rotation expansion |
|
||||||
|
| `shake256` | SHAKE256 extensible-output function |
|
||||||
|
|
||||||
|
### 5.6 `ksum` — key digest
|
||||||
|
|
||||||
|
A 16-character lowercase hexadecimal string: the first 16 characters of
|
||||||
|
`SHA256(upper_mapping ‖ lower_mapping ‖ long_key ‖ short_key)`, where `‖` is
|
||||||
|
concatenation of the ASCII encodings.
|
||||||
|
|
||||||
|
It exists so a reader can confirm that a key file and a ciphertext belong
|
||||||
|
together without exposing any usable secret. It is a **correlation aid, not a
|
||||||
|
security control**: it reveals nothing that helps an attacker, and its absence
|
||||||
|
of secrecy must not be relied upon as an integrity guarantee.
|
||||||
|
|
||||||
|
### 5.7 Legacy fields
|
||||||
|
|
||||||
|
Two optional fields exist for reading artefacts produced before the header was
|
||||||
|
introduced. They are never written by the current library except when wrapping a
|
||||||
|
legacy artefact, and they are **not** part of :data:`REQUIRED_FIELDS`.
|
||||||
|
|
||||||
|
| Field | Type | Meaning |
|
||||||
|
|---|---|---|
|
||||||
|
| `is_old` | boolean | The artefact predates this format |
|
||||||
|
| `old_is_key` | boolean | With `is_old`, whether it is a key file (`true`) or a ciphertext (`false`) |
|
||||||
|
|
||||||
|
> **Precedence rule.** When `is_old` is present and true, **every other field is
|
||||||
|
> ignored**, including `mode`, `mid`, `out` and `kind`. The artefact predates the
|
||||||
|
> field set, so there is nothing else meaningful to read. A reader must not
|
||||||
|
> reject such an artefact for missing `kind`, nor act on any field beside
|
||||||
|
> `is_old` and `old_is_key`.
|
||||||
|
|
||||||
|
An artefact that carries neither field is a normal artefact and is read
|
||||||
|
normally. Their absence is not an error.
|
||||||
|
|
||||||
|
### 5.8 Descriptive fields
|
||||||
|
|
||||||
|
The record also carries fields that describe the construction. They are
|
||||||
|
informational — a reader may use them for display or diagnostics — and they do
|
||||||
|
not modify the decryption path.
|
||||||
|
|
||||||
|
| Field | Meaning |
|
||||||
|
|---|---|
|
||||||
|
| `lib` | Library version that wrote the artefact |
|
||||||
|
| `cache` | Keystream cache strategy in effect; does not affect output |
|
||||||
|
| `subst` | Substitution kind, `"bijective"` |
|
||||||
|
| `flip` | Case-flip kind, `"conditional"` |
|
||||||
|
| `order` | The pipeline, as an ordered list of stage names |
|
||||||
|
| `xor_layers` | Number of XOR layers applied |
|
||||||
|
| `compact` | Whether the byte pipeline was used |
|
||||||
|
| `keyshort` | Length of the short key in bits |
|
||||||
|
| `flipbits` | Number of bits in the flip pattern |
|
||||||
|
| `b64` | Whether Base64 is used as a byte-safety layer |
|
||||||
|
| `utf8` | Whether text is transported as UTF-8 |
|
||||||
|
|
||||||
|
### 5.9 Example
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"alg": "chaoscrypt",
|
||||||
|
"b64": true,
|
||||||
|
"cache": "hash",
|
||||||
|
"compact": true,
|
||||||
|
"flip": "conditional",
|
||||||
|
"flipbits": 10,
|
||||||
|
"kdf": "shake256",
|
||||||
|
"keybits": 16384,
|
||||||
|
"keyshort": 2048,
|
||||||
|
"kind": "ciphertext",
|
||||||
|
"ksum": "3f9a1c7e5b2d4086",
|
||||||
|
"lib": "4.2.6",
|
||||||
|
"mid": "bt",
|
||||||
|
"mode": "turbo",
|
||||||
|
"order": "base64>subst>flip>reverse>xor>xor",
|
||||||
|
"out": "hex",
|
||||||
|
"subst": "bijective",
|
||||||
|
"utf8": true,
|
||||||
|
"v": 1,
|
||||||
|
"xor_layers": 2
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Rendered between the markers, this is a single unbroken line.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Payload
|
||||||
|
|
||||||
|
### 6.1 Ciphertext payload
|
||||||
|
|
||||||
|
When `kind` is `"ciphertext"`, the payload is the ciphertext encoded per `out`:
|
||||||
|
|
||||||
|
- `out = "hex"`: lowercase hexadecimal, even length, alphabet `[0-9a-f]`.
|
||||||
|
- `out = "base"`: standard Base64 with `=` padding, alphabet
|
||||||
|
`[A-Za-z0-9+/]`.
|
||||||
|
|
||||||
|
The payload is the final output of the pipeline named in `mode`. Nothing is
|
||||||
|
appended after it.
|
||||||
|
|
||||||
|
### 6.2 Key payload
|
||||||
|
|
||||||
|
When `kind` is `"key"`, the payload is the password-wrapped key material, in the
|
||||||
|
same two encodings.
|
||||||
|
|
||||||
|
A caller reading a key file must check that `kind` is `"key"`. A key file is not
|
||||||
|
a ciphertext and must not be accepted where a ciphertext is expected, nor the
|
||||||
|
reverse. This is enforced, not advisory.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Reader conformance
|
||||||
|
|
||||||
|
A conforming reader performs these steps, in order, and fails at the first
|
||||||
|
that does not hold. It must not attempt recovery, interpretation or fallback.
|
||||||
|
|
||||||
|
| # | Check | Failure |
|
||||||
|
|---|---|---|
|
||||||
|
| 1 | Input is non-empty | `E017` |
|
||||||
|
| 2 | Input starts with `69CES` | `E017` |
|
||||||
|
| 3 | The 64 characters after the magic equal the begin marker | `E018` |
|
||||||
|
| 4 | The end marker occurs after the begin marker | `E018` |
|
||||||
|
| 5 | Text between the markers is valid UTF-8 JSON | `E018` |
|
||||||
|
| 6 | That JSON is an object | `E018` |
|
||||||
|
| 7 | Every required field of §5.1 is present | `E018` |
|
||||||
|
| 8 | `kind`, `mid` and `out` hold permitted values | `E018` |
|
||||||
|
| 9 | `kind` matches what the caller asked for | `E018` |
|
||||||
|
| 10 | The payload decodes under `out` | `E010` |
|
||||||
|
| 11 | Decryption succeeds under `mode` and the key | `E011` |
|
||||||
|
|
||||||
|
### 7.1 No fallback
|
||||||
|
|
||||||
|
There is no lenient path. An artefact without a header is not a ChaosCrypt
|
||||||
|
artefact and is rejected with `E017`. Artefacts written by revisions before the
|
||||||
|
header existed are not read by this path either: they are recovered only
|
||||||
|
through the explicit compatibility API, which wraps them in a header first
|
||||||
|
(see section 12). The ordinary reader never gains a lenient branch.
|
||||||
|
|
||||||
|
### 7.2 No partial trust
|
||||||
|
|
||||||
|
A header is either wholly valid or wholly rejected. A reader must not act on
|
||||||
|
fields it did manage to parse, because a partially parsed header may describe a
|
||||||
|
different construction than the one that produced the payload.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Error codes
|
||||||
|
|
||||||
|
| Code | Name | Raised when |
|
||||||
|
|---|---|---|
|
||||||
|
| `E010` | `MalformedCiphertext` | Payload does not decode under `out` |
|
||||||
|
| `E011` | `DecryptionFailed` | Decryption produced invalid data |
|
||||||
|
| `E017` | `MissingMagicHeader` | No magic present; input is not a CES artefact |
|
||||||
|
| `E018` | `MalformedHeader` | Marker missing, JSON invalid, field absent or out of range, or `kind` mismatch |
|
||||||
|
|
||||||
|
Codes `E001`–`E016` cover key handling, argument and I/O failures and are
|
||||||
|
unchanged.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Versioning
|
||||||
|
|
||||||
|
`v` is the format version and is independent of the library version in `lib`.
|
||||||
|
|
||||||
|
A reader must reject an artefact whose `v` it does not implement, with `E018`.
|
||||||
|
Adding optional descriptive fields does not change `v`. Changing the magic, the
|
||||||
|
markers, the region order, or the meaning of a required field does, and requires
|
||||||
|
a new major library release.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. Conformance checklist
|
||||||
|
|
||||||
|
An implementation claims conformance when it:
|
||||||
|
|
||||||
|
- [ ] writes the magic, both markers and the configuration in the order of §4;
|
||||||
|
- [ ] sorts configuration keys and uses `,` and `:` as separators with no spaces;
|
||||||
|
- [ ] includes every required field of §5.1;
|
||||||
|
- [ ] rejects input without the magic with `E017`;
|
||||||
|
- [ ] rejects malformed headers with `E018`, never partially trusting them;
|
||||||
|
- [ ] enforces the `kind` match on both read and write paths;
|
||||||
|
- [ ] decodes the payload strictly under `out`, failing rather than guessing;
|
||||||
|
- [ ] implements no lenient or legacy fallback path.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 11. Worked examples
|
||||||
|
|
||||||
|
### 11.1 A normal ciphertext
|
||||||
|
|
||||||
|
Text that is encrypted in `turbo` with `base64` output, then the layout read
|
||||||
|
back region by region.
|
||||||
|
|
||||||
|
```python
|
||||||
|
from chaoscrypt import ChaosCrypt
|
||||||
|
|
||||||
|
cc = ChaosCrypt(mode="turbo", encoding="base64")
|
||||||
|
cc.load("my.key", "key-file-password")
|
||||||
|
|
||||||
|
token = cc.encrypt("meet me at the usual place", "encryption-password")
|
||||||
|
```
|
||||||
|
|
||||||
|
The token begins with the five magic octets, then the begin marker:
|
||||||
|
|
||||||
|
```
|
||||||
|
69CES
|
||||||
|
385aeff1f4179a744c8fb0c5ae4702d325f6230d059f4251135c2536409dee93
|
||||||
|
```
|
||||||
|
|
||||||
|
then the configuration, which states the parameters actually used:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"alg":"chaoscrypt","b64":true,"cache":"hash","compact":true,
|
||||||
|
"flip":"conditional","flipbits":10,"kdf":"shake256","keybits":16384,
|
||||||
|
"keyshort":2048,"kind":"ciphertext","ksum":"8007e271aea2b261",
|
||||||
|
"lib":"4.2.6","mid":"bt","mode":"turbo",
|
||||||
|
"order":"base64>subst>flip>reverse>xor>xor","out":"base","subst":"bijective",
|
||||||
|
"utf8":true,"v":1,"xor_layers":2}
|
||||||
|
```
|
||||||
|
|
||||||
|
then the end marker, then the base64 payload:
|
||||||
|
|
||||||
|
```
|
||||||
|
2025ea4e4b4b93803f2ccadeaf318d1957ce42ff5409410f660348be96a4c0f2
|
||||||
|
IUhCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFla...
|
||||||
|
```
|
||||||
|
|
||||||
|
Decrypting needs no configuration at all — the record supplies it:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from chaoscrypt import ChaosCrypt
|
||||||
|
from chaoscrypt._header import read_header, strip_header
|
||||||
|
|
||||||
|
cfg = read_header(token)
|
||||||
|
print(cfg["mode"], cfg["out"]) # turbo base
|
||||||
|
|
||||||
|
# a fresh instance with no settings reads it correctly
|
||||||
|
plain = ChaosCrypt(key_file="my.key", key_password="key-file-password",
|
||||||
|
auto_load=True).decrypt(token, "encryption-password")
|
||||||
|
```
|
||||||
|
|
||||||
|
### 11.2 Reading an artefact without knowing anything about it
|
||||||
|
|
||||||
|
Because the header is complete, a reader needs only the key file and the
|
||||||
|
password. The mode, the intermediate representation and the output encoding are
|
||||||
|
all taken from the artefact.
|
||||||
|
|
||||||
|
```python
|
||||||
|
from chaoscrypt import ChaosCrypt
|
||||||
|
|
||||||
|
cc = ChaosCrypt(key_file="my.key", key_password="key-file-password",
|
||||||
|
auto_load=True)
|
||||||
|
cc.load("my.key", "key-file-password")
|
||||||
|
|
||||||
|
# whatever produced this, it will be read correctly
|
||||||
|
plain = cc.decrypt(open("message.ces").read(), "encryption-password")
|
||||||
|
```
|
||||||
|
|
||||||
|
### 11.3 Inspecting a key file
|
||||||
|
|
||||||
|
```python
|
||||||
|
from chaoscrypt._header import read_header, strip_header
|
||||||
|
|
||||||
|
text = open("my.key", encoding="utf-8").read()
|
||||||
|
cfg = read_header(text)
|
||||||
|
|
||||||
|
print(cfg["kind"]) # key
|
||||||
|
print(cfg["alg"]) # chaoscrypt
|
||||||
|
print(cfg["keybits"]) # 16384
|
||||||
|
print(cfg["ksum"]) # 16 hex characters
|
||||||
|
```
|
||||||
|
|
||||||
|
`ksum` lets a caller confirm that a key file and a ciphertext belong together
|
||||||
|
without exposing anything usable:
|
||||||
|
|
||||||
|
```python
|
||||||
|
cs = open("message.ces", encoding="utf-8").read()
|
||||||
|
assert read_header(cs)["ksum"] == read_header(text)["ksum"], "wrong key file"
|
||||||
|
```
|
||||||
|
|
||||||
|
### 11.4 A rejection
|
||||||
|
|
||||||
|
```python
|
||||||
|
from chaoscrypt import ChaosCrypt
|
||||||
|
from chaoscrypt.errors import ChaosCryptError
|
||||||
|
|
||||||
|
cc = ChaosCrypt(key_file="my.key", key_password="key-file-password",
|
||||||
|
auto_load=True)
|
||||||
|
|
||||||
|
try:
|
||||||
|
cc.decrypt("7a3f9c...", "encryption-password") # a bare payload
|
||||||
|
except ChaosCryptError as e:
|
||||||
|
print(e.code) # E017
|
||||||
|
print(e.detail) # MissingMagicHeader
|
||||||
|
```
|
||||||
|
|
||||||
|
There is no fallback path here. The input is not a CES artefact, and guessing
|
||||||
|
would risk returning garbage that looks like success.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 12. Legacy artefacts
|
||||||
|
|
||||||
|
Artefacts written before this format existed have no header. They are handled by
|
||||||
|
**wrapping**, never by loosening the reader.
|
||||||
|
|
||||||
|
### 12.1 What a legacy artefact looks like
|
||||||
|
|
||||||
|
| Kind | Content |
|
||||||
|
|---|---|
|
||||||
|
| Legacy ciphertext | Hexadecimal text, no prefix of any kind |
|
||||||
|
| Legacy key file | Password-wrapped key material, no prefix of any kind |
|
||||||
|
|
||||||
|
Neither carries a magic value, a marker or a configuration record.
|
||||||
|
|
||||||
|
### 12.2 Wrapping
|
||||||
|
|
||||||
|
To read one, a minimal header is synthesised and prefixed. The payload is not
|
||||||
|
touched.
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"is_old":true,"old_is_key":false}
|
||||||
|
```
|
||||||
|
|
||||||
|
That header is a normal, valid header. Wrapping therefore produces an artefact
|
||||||
|
that the ordinary path can read, and **the ordinary path never gains a lenient
|
||||||
|
branch**: it still rejects headerless input with `E017`.
|
||||||
|
|
||||||
|
```python
|
||||||
|
from chaoscrypt import ChaosCrypt
|
||||||
|
|
||||||
|
cc = ChaosCrypt(key_file="my.key", key_password="key-file-password",
|
||||||
|
auto_load=True)
|
||||||
|
|
||||||
|
# a legacy ciphertext: no header
|
||||||
|
plain = cc.decrypt_legacy("72370655031311011c111f261365172716020b69",
|
||||||
|
"encryption-password")
|
||||||
|
```
|
||||||
|
|
||||||
|
`decrypt_legacy` first tries the input as it stands. If that reports a missing
|
||||||
|
header, it wraps the input and tries again. `decrypt_legacy_auto` additionally
|
||||||
|
probes whether the artefact is a key file or a ciphertext, so the caller does
|
||||||
|
not have to say which.
|
||||||
|
|
||||||
|
A legacy key file is loaded the same way:
|
||||||
|
|
||||||
|
```python
|
||||||
|
legacy_text = open("old-encryption.key", encoding="utf-8").read()
|
||||||
|
cc = ChaosCrypt()
|
||||||
|
cc.load_legacy_keys(legacy_text, "key-file-password")
|
||||||
|
```
|
||||||
|
|
||||||
|
Or wrapped explicitly, when the artefact is to be stored in the new form:
|
||||||
|
|
||||||
|
```python
|
||||||
|
modernised = cc.wrap_legacy(legacy_text, is_key=True)
|
||||||
|
open("my.key", "w", encoding="utf-8").write(modernised)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 12.3 Which algorithm reads a legacy artefact
|
||||||
|
|
||||||
|
`is_old` is true, so every other field is ignored — there is no `mode` to
|
||||||
|
consult. The legacy path tries the bulk-operation implementation first and
|
||||||
|
falls back to the original character pipeline:
|
||||||
|
|
||||||
|
| Attempt | Why |
|
||||||
|
|---|---|
|
||||||
|
| 1. `fast` | Same algorithm, faster; correct for anything the bulk path can read |
|
||||||
|
| 2. `reference` | The original pipeline, in case the artefact needs it |
|
||||||
|
|
||||||
|
Both implement the original algorithm, so either can read pre-header material.
|
||||||
|
The fallback costs a second attempt only when the first fails.
|
||||||
|
|
||||||
|
### 12.4 What is not supported
|
||||||
|
|
||||||
|
- **Writing legacy artefacts.** The library only reads them. Output always
|
||||||
|
carries a header.
|
||||||
|
- **Partial trust of a legacy artefact.** It is wrapped whole; nothing is
|
||||||
|
inferred from its content.
|
||||||
|
- **Reading a legacy artefact without wrapping.** The ordinary path will reject
|
||||||
|
it with `E017`. Use the compatibility API.
|
||||||
|
|
||||||
|
### 12.5 Conformance for readers
|
||||||
|
|
||||||
|
An implementation that supports legacy artefacts must:
|
||||||
|
|
||||||
|
- [ ] detect a headerless input and treat it as legacy, not as an error at the
|
||||||
|
API boundary;
|
||||||
|
- [ ] synthesise a header rather than bypass the parser;
|
||||||
|
- [ ] ignore every field except `is_old` and `old_is_key` when `is_old` is true;
|
||||||
|
- [ ] keep the ordinary path strict — a headerless input passed to `decrypt`
|
||||||
|
still raises `E017`;
|
||||||
|
- [ ] never write a legacy artefact.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 13. Relation to the cipher
|
||||||
|
|
||||||
|
The header is metadata. It does not add secrecy, and it is not authenticated.
|
||||||
|
An attacker who modifies the header can cause a decryption to fail, which is a
|
||||||
|
denial of service and no more — the payload cannot be recovered without the key.
|
||||||
|
|
||||||
|
Where an application needs to detect tampering with the header as well as the
|
||||||
|
payload, it must compute a MAC over the **entire artefact**, header included,
|
||||||
|
and verify that MAC before parsing. The format does not do this for you.
|
||||||
|
|
||||||
|
See [SECURITY.md](../SECURITY.md) for what the cipher guarantees and what it
|
||||||
|
does not.
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
# 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 |
|
||||||
|
| [benchmark.md](benchmark.md) | Performance measurements and mode comparison |
|
||||||
|
| [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.
|
||||||
|
|
||||||
|
**Choosing a performance mode**
|
||||||
|
[benchmark.md](benchmark.md) for the numbers, [SECURITY.md §4](../SECURITY.md)
|
||||||
|
for what each mode costs in cryptographic margin.
|
||||||
|
|
||||||
|
**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).
|
||||||
@@ -0,0 +1,251 @@
|
|||||||
|
# Benchmark
|
||||||
|
|
||||||
|
Performance reference for `chaoscrypt` **4.2.6**.
|
||||||
|
|
||||||
|
> **Read this first.** These numbers are not a claim that ChaosCrypt competes
|
||||||
|
> with a C-backed cipher. It is pure Python. AES-GCM in `cryptography` runs at
|
||||||
|
> hundreds of megabytes per second; ChaosCrypt's fastest mode manages tens.
|
||||||
|
> What the tables below show is what the implementation costs, how the modes
|
||||||
|
> differ, and which parameters are realistic for the workloads this library is
|
||||||
|
> meant for.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Headline figures
|
||||||
|
|
||||||
|
`raw` mode, hex output, keystream cache warm, best of several runs.
|
||||||
|
|
||||||
|
| Payload | `bt` encrypt | `bt` decrypt | `hex` encrypt | `hex` decrypt |
|
||||||
|
|---|---:|---:|---:|---:|
|
||||||
|
| 64 KiB | 26.9 | 60.6 | 20.7 | 20.2 |
|
||||||
|
| 128 KiB | 54.9 | 85.5 | 15.8 | 14.3 |
|
||||||
|
| 1 MiB | 57.3 | 61.0 | 19.3 | 21.8 |
|
||||||
|
| 16 MiB | 63.4 | 69.0 | 18.9 | 22.7 |
|
||||||
|
| 128 MiB | 59.4 | 64.5 | 18.2 | 18.0 |
|
||||||
|
| 1024 MiB | 47.9 | 31.7 | — | — |
|
||||||
|
|
||||||
|
MB/s. Ciphertext expansion: `bt` **2.00x**, `hex` **8.00x**.
|
||||||
|
|
||||||
|
**The one-line summary:** `raw` with the default `bt` intermediate runs at
|
||||||
|
roughly **60 MB/s encryption and 70 MB/s decryption**, with ciphertext twice the
|
||||||
|
payload size. Throughput holds steady across four orders of magnitude, which is
|
||||||
|
what a linear algorithm looks like.
|
||||||
|
|
||||||
|
### Against the original implementation
|
||||||
|
|
||||||
|
| | Original | `raw` bt | Improvement |
|
||||||
|
|---|---:|---:|---:|
|
||||||
|
| 1 MiB encrypt | 12.050 s (0.08 MB/s) | 0.017 s (57 MB/s) | **≈700x** |
|
||||||
|
| Ciphertext | 5.33x | 2.00x | 62% smaller |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Test environment
|
||||||
|
|
||||||
|
| Item | Value |
|
||||||
|
|---|---|
|
||||||
|
| CPU | 16 logical cores |
|
||||||
|
| Python | CPython 3.13.4 |
|
||||||
|
| OS | Windows 10 (10.0.26200) |
|
||||||
|
| Library | `chaoscrypt` 4.2.6, pure Python, zero dependencies |
|
||||||
|
| Payload | ASCII, `"A" * n` |
|
||||||
|
| Measurement | Best of several runs; each size warmed once so the keystream cache is populated |
|
||||||
|
|
||||||
|
Best-of-N is used because the machine is not otherwise idle. That makes the
|
||||||
|
figures optimistic; a loaded system will be slower, and the ordering between
|
||||||
|
modes is unaffected.
|
||||||
|
|
||||||
|
> **1024 MiB with `hex`** needs an 8 GB ciphertext as a single Python string,
|
||||||
|
> which is not addressable. That cell is left blank rather than measured in a
|
||||||
|
> way that would only report the allocator's behaviour.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Throughput across four orders of magnitude
|
||||||
|
|
||||||
|
`raw`, `bt` intermediate, encryption:
|
||||||
|
|
||||||
|
| Size | MB/s | Ratio to previous |
|
||||||
|
|---|---:|---:|
|
||||||
|
| 64 KiB | 26.9 | — |
|
||||||
|
| 128 KiB | 54.9 | 2.04x |
|
||||||
|
| 1 MiB | 57.3 | 1.04x |
|
||||||
|
| 16 MiB | 63.4 | 1.11x |
|
||||||
|
| 128 MiB | 59.4 | 0.94x |
|
||||||
|
| 1024 MiB | 47.9 | 0.81x |
|
||||||
|
|
||||||
|
From 128 KiB upward the figure is flat within ±15%, which is measurement noise
|
||||||
|
plus cache effects rather than algorithmic behaviour. **64 KiB reads low
|
||||||
|
because fixed setup costs are a larger share of a short operation**, not because
|
||||||
|
something is quadratic.
|
||||||
|
|
||||||
|
The 1024 MiB figure is lower because a 2 GB ciphertext string puts the process
|
||||||
|
under memory pressure. It is an observation about the machine, not the
|
||||||
|
algorithm.
|
||||||
|
|
||||||
|
### The quadratic bug that used to be here
|
||||||
|
|
||||||
|
An earlier revision was genuinely super-linear, and it showed up exactly this
|
||||||
|
way: throughput fell as payload grew. The cause was `_get_dynamic_key`:
|
||||||
|
|
||||||
|
```python
|
||||||
|
key = self.long_key
|
||||||
|
while len(key) < text_length:
|
||||||
|
key += self.long_key # reallocates the whole accumulator every round
|
||||||
|
```
|
||||||
|
|
||||||
|
Covering a 5.6 MB intermediate took **866 ms**. Multiplication instead:
|
||||||
|
|
||||||
|
```python
|
||||||
|
return (lk * (text_length // ll + 1))[:text_length]
|
||||||
|
```
|
||||||
|
|
||||||
|
The same work takes **3 ms**, with byte-identical output. `_expand_keystream_slow`
|
||||||
|
shared the pattern and was fixed the same way.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Intermediate representation
|
||||||
|
|
||||||
|
The setting with the largest effect on both speed and size.
|
||||||
|
|
||||||
|
| Payload | `bt` enc | `bt` dec | `hex` enc | `hex` dec | Ciphertext `bt` / `hex` |
|
||||||
|
|---|---:|---:|---:|---:|---:|
|
||||||
|
| 64 KiB | 26.9 | 60.6 | 20.7 | 20.2 | 0.1 / 0.5 MB |
|
||||||
|
| 1 MiB | 57.3 | 61.0 | 19.3 | 21.8 | 2 / 8 MB |
|
||||||
|
| 16 MiB | 63.4 | 69.0 | 18.9 | 22.7 | 32 / 128 MB |
|
||||||
|
| 128 MiB | 59.4 | 64.5 | 18.2 | 18.0 | 256 / 1024 MB |
|
||||||
|
|
||||||
|
`hex` is about **3x slower** and produces **4x more** ciphertext. It re-encodes
|
||||||
|
the payload between the XOR layers, which doubles it twice. It exists for
|
||||||
|
interoperability with the character pipeline's shape, not for performance.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Output encoding
|
||||||
|
|
||||||
|
| Encoding | Expansion | Notes |
|
||||||
|
|---|---:|---|
|
||||||
|
| `hex` | 2.00x | Two characters per octet |
|
||||||
|
| `base64` | 1.33x | Four characters per three octets |
|
||||||
|
|
||||||
|
Base64 produces a third less output at broadly the same speed. The choice
|
||||||
|
affects only the final encode.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. How the modes compare
|
||||||
|
|
||||||
|
| | `reference` | `fast` | `turbo` | `raw` |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| 1 MiB encrypt | 12.05 s | 0.35 s | 0.05 s | 0.017 s |
|
||||||
|
| Ciphertext | 5.33x | 5.33x | 2.00x | 2.00x |
|
||||||
|
| Payload compatible with pre-4.2.6 | yes | yes | no | no |
|
||||||
|
| Keystream primitive | hand-rolled expansion | hand-rolled expansion | SHAKE256 | SHAKE256 |
|
||||||
|
|
||||||
|
`fast` is `reference` with the same arithmetic performed by C-level bulk
|
||||||
|
operations; its payload is byte-identical. The frozen vectors assert this, so
|
||||||
|
the equivalence cannot silently stop holding.
|
||||||
|
|
||||||
|
`turbo` and `raw` replace the keystream derivation with SHAKE256 and stop
|
||||||
|
re-encoding between layers. `raw` keeps the long-key XOR layer, `turbo` does not.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Where the time goes
|
||||||
|
|
||||||
|
Profiling `raw` with the `bt` intermediate, 10 MiB payload, encryption:
|
||||||
|
|
||||||
|
| Stage | Time | Share |
|
||||||
|
|---|---:|---:|
|
||||||
|
| `_bytes_stages` (substitution, flip, reversal) | 29 ms | 24% |
|
||||||
|
| XOR with the long key | 38 ms | 32% |
|
||||||
|
| XOR with the SHAKE keystream | 38 ms | 32% |
|
||||||
|
| Keystream derivation (cached) | ~0 ms | 0% |
|
||||||
|
| Output encode (`.hex()`) | 9 ms | 8% |
|
||||||
|
| **Total** | **119 ms** | |
|
||||||
|
|
||||||
|
Decryption is the mirror image, at 122 ms, and is if anything slightly quicker
|
||||||
|
end to end because it does not encode its output.
|
||||||
|
|
||||||
|
### The changes that mattered
|
||||||
|
|
||||||
|
**1. Keeping the payload in bytes between XOR layers (4x).**
|
||||||
|
The original re-encoded to hexadecimal after each XOR, doubling the payload at
|
||||||
|
every layer. At 1 MiB that meant a 5.6 MB intermediate. Bytes between layers
|
||||||
|
means a 1.4 MB intermediate instead.
|
||||||
|
|
||||||
|
**2. Per-character loops to `bytes.translate` (61x on substitution alone).**
|
||||||
|
Substitution was a dictionary lookup per character; it is now one translation
|
||||||
|
over a 256-entry table. The case flip is periodic, so it became ten strided
|
||||||
|
slice translations instead of a per-character branch.
|
||||||
|
|
||||||
|
**3. Per-byte XOR to one big-integer XOR (43x).**
|
||||||
|
```python
|
||||||
|
# before
|
||||||
|
for i, char in enumerate(text):
|
||||||
|
result.append(f"{ord(char) ^ ord(key[i % key_len]):02x}")
|
||||||
|
|
||||||
|
# after
|
||||||
|
xored = int.from_bytes(data, 'big') ^ int.from_bytes(key, 'big')
|
||||||
|
return xored.to_bytes(n, 'big').hex()
|
||||||
|
```
|
||||||
|
|
||||||
|
**4. Not copying or scanning the whole artefact on decrypt (2x).**
|
||||||
|
The decrypt path used to call `strip()`, then `int(payload, 16)`, and
|
||||||
|
`strip_header` sliced the whole string three times. On a 20 MB artefact that was
|
||||||
|
about 65 ms of pure copying. Removing it took decryption at 512 KiB from
|
||||||
|
34 MB/s to 87 MB/s.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. What did not work
|
||||||
|
|
||||||
|
An attempt to build all expansion chunks with `numpy` as a two-dimensional
|
||||||
|
array reached only 2.9x and added a dependency. Cached translation tables were
|
||||||
|
faster and dependency-free.
|
||||||
|
|
||||||
|
A later attempt to fold the hex round trip in `_derive_final_key` by processing
|
||||||
|
only the prefix the output consumes gained 1.6x — worth keeping, but far less
|
||||||
|
than the byte-pipeline change that made the whole stage cheaper.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Reproducing these numbers
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python bench/benchmark.py
|
||||||
|
python bench/benchmark.py --sizes 64,1024,65536 --budget 0.05 --repeats 3
|
||||||
|
python bench/benchmark.py --groups Text,Binary
|
||||||
|
```
|
||||||
|
|
||||||
|
The harness dispatches every task to a process pool, one worker per core, and
|
||||||
|
reports the best of N rounds per task.
|
||||||
|
|
||||||
|
### A note on large payloads
|
||||||
|
|
||||||
|
Beyond roughly 128 MiB the ciphertext itself becomes the practical limit: at
|
||||||
|
1024 MiB inputs, `bt` needs a 2 GB string and `hex` needs 8 GB. For payloads
|
||||||
|
that large, encrypt in blocks. The per-block throughput is the same, as §3
|
||||||
|
shows.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. Summary
|
||||||
|
|
||||||
|
| Dimension | Result |
|
||||||
|
|---|---|
|
||||||
|
| Fastest throughput | **~63 MB/s encryption, ~85 MB/s decryption** (`raw`, `bt`, hex) |
|
||||||
|
| Ciphertext overhead | 2.00x (`bt`) or 1.33x (`base64`) |
|
||||||
|
| Speed with a payload compatible with pre-4.2.6 | `fast`, ~30x the original |
|
||||||
|
| Linear across | 64 KiB to 1 GiB |
|
||||||
|
| Dependencies | none, in every mode |
|
||||||
|
| Best suited for | Notes, credentials, documents, personal backups |
|
||||||
|
| Not suited for | Bulk media at gigabyte scale, high-throughput services, KDF stretching |
|
||||||
|
|
||||||
|
> **Bottom line.** The original implementation's cost was almost entirely
|
||||||
|
> Python-level per-byte work, not the cipher's arithmetic. Keeping the payload
|
||||||
|
> in bytes between the XOR layers removed the largest remaining factor, and the
|
||||||
|
> result is a library that runs at tens of megabytes per second rather than
|
||||||
|
> fractions of one — with the same construction, and with the modes and their
|
||||||
|
> trade-offs documented in [SECURITY.md](../SECURITY.md).
|
||||||
+127
@@ -0,0 +1,127 @@
|
|||||||
|
[build-system]
|
||||||
|
requires = ["setuptools>=77", "wheel"]
|
||||||
|
build-backend = "setuptools.build_meta"
|
||||||
|
|
||||||
|
[project]
|
||||||
|
name = "chaoscrypt"
|
||||||
|
version = "4.2.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 = []
|
||||||
|
|
||||||
|
# Listed module by module. Automatic discovery would pick up chaoscrypt.tests,
|
||||||
|
# which has an __init__.py and would otherwise be installed as part of the
|
||||||
|
# package; the development directories must stay in the source tree only.
|
||||||
|
packages = ["chaoscrypt"]
|
||||||
|
|
||||||
|
[tool.setuptools.exclude-package-data]
|
||||||
|
chaoscrypt = [
|
||||||
|
"tests/*",
|
||||||
|
"examples/*",
|
||||||
|
"legacy/*",
|
||||||
|
]
|
||||||
|
|
||||||
|
[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__.:",
|
||||||
|
]
|
||||||
@@ -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()
|
||||||
Reference in New Issue
Block a user