v2.1.6: Restructure as a distributable library
Restructure ChaosCrypt from a single-file script into a complete, installable Python package with three interfaces: a typed Python API, an argument-driven CLI, and a bilingual interactive TUI. The algorithm itself is unchanged. Ciphertexts and key files remain fully interoperable with the original implementation in both directions, which is enforced by dedicated tests rather than merely documented. Added - Library API: ChaosCrypt facade plus ChaosCryptCore for the raw algorithm - Unified error hierarchy: 16 named types, all ChaosCryptError subclasses, rendering as ChaosCrypt_ERR_<Detail>_<Code> - CLI: keygen, encrypt, decrypt, file, info, chpwd, tui, with --json output, stdin/stdout piping, and three password sources per secret - Bilingual TUI: English default, runtime switch to Chinese, getpass password entry with a non-TTY fallback that keeps it scriptable - Binary and file support: encrypt_bytes/decrypt_bytes and encrypt_file/decrypt_file - Key management: change_key_password rewraps without altering key material; export_key_text/load_from_text move a key without touching disk - Documentation: SECURITY.md with the full design and threat analysis, plus docs/ covering the API, CLI, architecture and build process - Test suite: 92 tests across round-trips, binary safety, key management, error types, CLI, TUI, i18n and legacy interoperability - Packaging: pyproject.toml, setup.py compatibility shim, MANIFEST.in, py.typed, examples, MIT licence Fixed - Conflicting --pwd option between the -p and -P groups prevented the CLI from starting at all - Wrong key file password reported as file corruption (E002); structural validation now distinguishes it from a damaged file (E003) - export_key_text produced key material without loading it into the instance - Non-hexadecimal input was accepted as ciphertext and silently decrypted into garbage, making corruption indistinguishable from success; malformed input now raises E010 before any processing - TUI failed under piped input because getpass requires a TTY - TUI kept reading the default key file name after generating a new one Changed - Source tree reorganised: the package lives at chaoscrypt/, with tests, examples and legacy alongside it; documentation and build artefacts at the repository root - Code comments unified in English; public docstrings document parameters, return values and raised exceptions - English is now the default UI language - ChaosCryptChat removed from the repository - Attribution updated to Dvs (DvsXT); project URLs point to Gitea
This commit is contained in:
+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
|
||||||
|
|||||||
+115
@@ -0,0 +1,115 @@
|
|||||||
|
# Changelog
|
||||||
|
|
||||||
|
All notable changes to this project are documented in this file.
|
||||||
|
|
||||||
|
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||||
|
and this project adheres to [Semantic Versioning](https://semver.org/).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## [2.1.6] — 2026-09-27
|
||||||
|
|
||||||
|
Packaging and documentation release. The algorithm is unchanged; this version
|
||||||
|
restructures the project as a distributable library and brings the
|
||||||
|
documentation in line with it.
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- **Bilingual interactive TUI.** A menu-driven interface with English and
|
||||||
|
Chinese, switchable at runtime. Uses `getpass` for password entry on a
|
||||||
|
terminal and degrades to plain input when piped, so it remains scriptable.
|
||||||
|
- **Full command line interface.** Subcommands `keygen`, `encrypt`, `decrypt`,
|
||||||
|
`file`, `info`, `chpwd` and `tui`, with `--json` output, stdin/stdout
|
||||||
|
piping, and three ways to supply each password (inline, environment
|
||||||
|
variable, password file).
|
||||||
|
- **Unified error hierarchy.** Sixteen named error types, all subclasses of
|
||||||
|
`ChaosCryptError`, each rendering as `ChaosCrypt_ERR_<Detail>_<Code>`. Every
|
||||||
|
failure path in the library now raises rather than returning a sentinel.
|
||||||
|
- **Binary and file support.** `encrypt_bytes` / `decrypt_bytes` for arbitrary
|
||||||
|
binary data, and `encrypt_file` / `decrypt_file` for whole files.
|
||||||
|
- **Key management helpers.** `change_key_password` re-wraps a key file under
|
||||||
|
a new password without altering the key material. `export_key_text` and
|
||||||
|
`load_from_text` move a key without touching disk.
|
||||||
|
- **Comprehensive documentation.** `SECURITY.md` presents the design, key
|
||||||
|
space derivation, threat model and attack analysis in full. `docs/`
|
||||||
|
contains API, CLI and architecture references.
|
||||||
|
- **Test suite.** Round-trip integrity, binary safety, key management, error
|
||||||
|
types, CLI behaviour, TUI interaction, internationalisation, and
|
||||||
|
bidirectional interoperability with the original implementation.
|
||||||
|
- **Packaging.** `pyproject.toml`, `MANIFEST.in`, `.gitignore`, `py.typed`,
|
||||||
|
runnable examples, and MIT licensing.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- **Project restructured** into a standard library layout. The importable
|
||||||
|
package now lives at `chaoscrypt/`, with tests, examples and the legacy
|
||||||
|
implementation alongside it, and documentation and build artefacts at the
|
||||||
|
repository root.
|
||||||
|
- **Code comments unified in English**, and public docstrings expanded to
|
||||||
|
document parameters, return values and raised errors.
|
||||||
|
- **English is now the default UI language**, with Chinese available as an
|
||||||
|
alternative.
|
||||||
|
- **Packaging metadata** updated for the new layout and SPDX licence
|
||||||
|
expression.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
Six defects found and corrected during the restructure:
|
||||||
|
|
||||||
|
1. The `-p` and `-P` option groups both registered `--pwd`, causing an
|
||||||
|
`argparse` conflict that prevented the CLI from starting at all.
|
||||||
|
2. An incorrect key file password was reported as a corrupted file (`E002`)
|
||||||
|
rather than a credential error (`E003`). A structural validation step now
|
||||||
|
distinguishes the two cases.
|
||||||
|
3. `export_key_text` produced key material without loading it into the
|
||||||
|
instance, so the returned key could not be used directly.
|
||||||
|
4. **Non-hexadecimal input was accepted as ciphertext and silently decrypted
|
||||||
|
into garbage.** This was the most serious defect: a corrupt or truncated
|
||||||
|
ciphertext was indistinguishable from a successful decryption. Malformed
|
||||||
|
input now raises `E010` before any processing occurs.
|
||||||
|
5. The TUI failed outright under piped input, because `getpass` requires a
|
||||||
|
TTY. It now detects this and falls back to plain input.
|
||||||
|
6. After generating a key file, the TUI continued to look at the default file
|
||||||
|
name rather than the one just created. The key file is now remembered for
|
||||||
|
the rest of the session.
|
||||||
|
|
||||||
|
### Security
|
||||||
|
|
||||||
|
- Clearly documented that ChaosCrypt is unaudited and non-standardised, and
|
||||||
|
that it is intended for obfuscation, personal use, and research or teaching
|
||||||
|
rather than production deployment.
|
||||||
|
- Documented the deterministic-output property and its consequences, and the
|
||||||
|
information disclosed by ciphertext length and Base64 padding class.
|
||||||
|
- Documented the strength of the construction in full, including the
|
||||||
|
approximately 10^5621 key space, the absence of algebraic and
|
||||||
|
number-theoretic structure, and the effect of Shor's and Grover's
|
||||||
|
algorithms.
|
||||||
|
|
||||||
|
### Compatibility
|
||||||
|
|
||||||
|
Fully backward compatible with the original single-file implementation, in
|
||||||
|
both directions:
|
||||||
|
|
||||||
|
- key files produced by either implementation load in the other;
|
||||||
|
- ciphertext produced by either implementation decrypts in the other;
|
||||||
|
- the default key file name remains `encryption.key`, and the on-disk key
|
||||||
|
file format is unchanged.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## [2.0.0] — Original release
|
||||||
|
|
||||||
|
The original single-file implementation of the ChaosCrypt cipher.
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Random system key generation: independent uppercase and lowercase
|
||||||
|
bijections, digit and padding substitutions, a 10-bit case-flip pattern, a
|
||||||
|
4096-nibble long key and a 512-nibble short key.
|
||||||
|
- Password-protected key file wrapping.
|
||||||
|
- Layered encryption: Base64 encoding, substitution, conditional case
|
||||||
|
flipping, whole-message reversal, and two XOR stages.
|
||||||
|
- Interactive menu for encryption, decryption and key management.
|
||||||
|
|
||||||
|
[2.1.6]: https://git.dvscloud.net/dvs/ChaosCrypt/releases/tag/v2.1.6
|
||||||
|
[2.0.0]: https://git.dvscloud.net/dvs/ChaosCrypt/releases/tag/v2.0.0
|
||||||
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 未经审计,不是标准密码学算法,可能存在未知风险。
|
||||||
|
仅限用于:混淆式加密、个人自用、研究教学。
|
||||||
|
请勿用于真实产品。因擅自用于真实产品导致的任何事故,开发者不承担责任。
|
||||||
+26
@@ -0,0 +1,26 @@
|
|||||||
|
# Files included in the source distribution.
|
||||||
|
#
|
||||||
|
# Note: the development directories (tests/, examples/, legacy/) are
|
||||||
|
# deliberately NOT listed here. They sit inside the package directory in the
|
||||||
|
# source tree, and MANIFEST.in entries under a package path are treated as
|
||||||
|
# package data, which would place them in the wheel as well. The source tree
|
||||||
|
# itself is the distribution for development purposes; the sdist carries the
|
||||||
|
# library and its documentation.
|
||||||
|
|
||||||
|
include README.md
|
||||||
|
include LICENSE
|
||||||
|
include SECURITY.md
|
||||||
|
include CHANGELOG.md
|
||||||
|
include pyproject.toml
|
||||||
|
include .gitignore
|
||||||
|
|
||||||
|
recursive-include docs *.md
|
||||||
|
|
||||||
|
# The installable package.
|
||||||
|
include chaoscrypt/*.py
|
||||||
|
include chaoscrypt/py.typed
|
||||||
|
|
||||||
|
global-exclude *.py[cod]
|
||||||
|
global-exclude __pycache__/*
|
||||||
|
global-exclude .DS_Store
|
||||||
|
global-exclude *.key
|
||||||
+424
-742
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,474 @@
|
|||||||
|
"""
|
||||||
|
ChaosCrypt - a chaos-based obfuscation cipher.
|
||||||
|
==============================================
|
||||||
|
|
||||||
|
Security notice
|
||||||
|
---------------
|
||||||
|
ChaosCrypt has **not** been independently audited and is **not** a
|
||||||
|
standardised cryptographic construction. It is designed for three purposes:
|
||||||
|
|
||||||
|
1. **Obfuscation** - making data unreadable to casual inspection;
|
||||||
|
2. **Personal use** - protecting your own notes, journals and backups;
|
||||||
|
3. **Research and teaching** - studying how layered obfuscation behaves.
|
||||||
|
|
||||||
|
Do not deploy it in production or in any safety-, privacy- or
|
||||||
|
compliance-critical system. If you need standardised cryptography, use a
|
||||||
|
vetted library such as ``cryptography`` (AES-GCM, ChaCha20-Poly1305).
|
||||||
|
|
||||||
|
The underlying construction is nonetheless substantially stronger than its
|
||||||
|
lack of audit might suggest: see ``SECURITY.md`` for the full design and
|
||||||
|
threat analysis, including the key-space derivation and the reasoning
|
||||||
|
behind each design decision.
|
||||||
|
|
||||||
|
Distributed under the MIT licence, provided as-is, without warranty.
|
||||||
|
|
||||||
|
Quick start
|
||||||
|
-----------
|
||||||
|
Library::
|
||||||
|
|
||||||
|
from chaoscrypt import ChaosCrypt
|
||||||
|
|
||||||
|
cc = ChaosCrypt()
|
||||||
|
cc.create_key("key-file-password", "my.key") # once, then keep it safe
|
||||||
|
|
||||||
|
token = cc.encrypt("hello world", "encryption-password")
|
||||||
|
assert cc.decrypt(token, "encryption-password") == "hello world"
|
||||||
|
|
||||||
|
Command line::
|
||||||
|
|
||||||
|
chaoscrypt # no arguments -> interactive TUI
|
||||||
|
chaoscrypt --help # arguments -> scriptable CLI
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from ._core import ChaosCryptCore, KEYFILE_VERSION
|
||||||
|
from .errors import (
|
||||||
|
ChaosCryptError,
|
||||||
|
ChaosCrypt_ERR_KeyFileNotFound_E001,
|
||||||
|
ChaosCrypt_ERR_KeyFileCorrupted_E002,
|
||||||
|
ChaosCrypt_ERR_KeyPasswordIncorrect_E003,
|
||||||
|
ChaosCrypt_ERR_KeyNotLoaded_E004,
|
||||||
|
ChaosCrypt_ERR_KeyFileExists_E005,
|
||||||
|
ChaosCrypt_ERR_EmptyPassword_E006,
|
||||||
|
ChaosCrypt_ERR_PasswordMismatch_E007,
|
||||||
|
ChaosCrypt_ERR_EmptyPlaintext_E008,
|
||||||
|
ChaosCrypt_ERR_EmptyCiphertext_E009,
|
||||||
|
ChaosCrypt_ERR_MalformedCiphertext_E010,
|
||||||
|
ChaosCrypt_ERR_DecryptionFailed_E011,
|
||||||
|
ChaosCrypt_ERR_EncodingFailed_E012,
|
||||||
|
ChaosCrypt_ERR_InvalidArgument_E013,
|
||||||
|
ChaosCrypt_ERR_FileReadFailed_E014,
|
||||||
|
ChaosCrypt_ERR_FileWriteFailed_E015,
|
||||||
|
ChaosCrypt_ERR_UnsupportedKeyVersion_E016,
|
||||||
|
)
|
||||||
|
|
||||||
|
__version__ = "2.1.6"
|
||||||
|
__author__ = "Dvs (DvsXT)"
|
||||||
|
__license__ = "MIT"
|
||||||
|
__all__ = [
|
||||||
|
"__version__",
|
||||||
|
"__author__",
|
||||||
|
"__license__",
|
||||||
|
"DEFAULT_KEY_FILE",
|
||||||
|
"KEYFILE_VERSION",
|
||||||
|
"ChaosCryptCore",
|
||||||
|
"ChaosCrypt",
|
||||||
|
"ChaosCryptError",
|
||||||
|
"ChaosCrypt_ERR_KeyFileNotFound_E001",
|
||||||
|
"ChaosCrypt_ERR_KeyFileCorrupted_E002",
|
||||||
|
"ChaosCrypt_ERR_KeyPasswordIncorrect_E003",
|
||||||
|
"ChaosCrypt_ERR_KeyNotLoaded_E004",
|
||||||
|
"ChaosCrypt_ERR_KeyFileExists_E005",
|
||||||
|
"ChaosCrypt_ERR_EmptyPassword_E006",
|
||||||
|
"ChaosCrypt_ERR_PasswordMismatch_E007",
|
||||||
|
"ChaosCrypt_ERR_EmptyPlaintext_E008",
|
||||||
|
"ChaosCrypt_ERR_EmptyCiphertext_E009",
|
||||||
|
"ChaosCrypt_ERR_MalformedCiphertext_E010",
|
||||||
|
"ChaosCrypt_ERR_DecryptionFailed_E011",
|
||||||
|
"ChaosCrypt_ERR_EncodingFailed_E012",
|
||||||
|
"ChaosCrypt_ERR_InvalidArgument_E013",
|
||||||
|
"ChaosCrypt_ERR_FileReadFailed_E014",
|
||||||
|
"ChaosCrypt_ERR_FileWriteFailed_E015",
|
||||||
|
"ChaosCrypt_ERR_UnsupportedKeyVersion_E016",
|
||||||
|
]
|
||||||
|
|
||||||
|
#: Default key file name, matching the original implementation.
|
||||||
|
DEFAULT_KEY_FILE = "encryption.key"
|
||||||
|
|
||||||
|
|
||||||
|
class ChaosCrypt:
|
||||||
|
"""High-level facade over :class:`~chaoscrypt.ChaosCryptCore`.
|
||||||
|
|
||||||
|
Manages a key file and exposes convenient encryption/decryption helpers.
|
||||||
|
For the raw algorithm with no file handling at all, use
|
||||||
|
:class:`~chaoscrypt.ChaosCryptCore` directly.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
key_file: Path to a key file. ``None`` loads nothing.
|
||||||
|
key_password: Password protecting that key file.
|
||||||
|
auto_load: When ``True``, load the key file during construction.
|
||||||
|
default_key_file: File name used when ``key_file`` is not given.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ChaosCrypt_ERR_KeyFileNotFound_E001: ``key_file`` does not exist.
|
||||||
|
ChaosCrypt_ERR_KeyPasswordIncorrect_E003: wrong key file password.
|
||||||
|
ChaosCrypt_ERR_KeyFileCorrupted_E002: key file cannot be parsed.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
key_file: Optional[str] = None,
|
||||||
|
key_password: Optional[str] = None,
|
||||||
|
*,
|
||||||
|
auto_load: bool = False,
|
||||||
|
default_key_file: str = DEFAULT_KEY_FILE,
|
||||||
|
) -> None:
|
||||||
|
self.core = ChaosCryptCore()
|
||||||
|
self.key_file = key_file
|
||||||
|
self.key_password = key_password
|
||||||
|
self.default_key_file = default_key_file
|
||||||
|
|
||||||
|
if auto_load:
|
||||||
|
self.load(key_file=key_file, key_password=key_password)
|
||||||
|
|
||||||
|
# ==================================================================
|
||||||
|
# State
|
||||||
|
# ==================================================================
|
||||||
|
@property
|
||||||
|
def loaded(self) -> bool:
|
||||||
|
"""Whether usable key material is currently held in memory."""
|
||||||
|
return self.core.keys_loaded
|
||||||
|
|
||||||
|
def is_loaded(self) -> bool:
|
||||||
|
"""Whether key material is loaded (method form)."""
|
||||||
|
return self.core.keys_loaded
|
||||||
|
|
||||||
|
def __repr__(self) -> str: # pragma: no cover - debugging aid
|
||||||
|
state = "loaded" if self.core.keys_loaded else "unloaded"
|
||||||
|
return f"<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)
|
||||||
|
self.key_password = key_password
|
||||||
|
return text
|
||||||
|
|
||||||
|
def info(self) -> dict:
|
||||||
|
"""Return a summary of the loaded key material.
|
||||||
|
|
||||||
|
Includes the substitution tables because they describe the key file's
|
||||||
|
structure. Treat the result as sensitive.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ChaosCrypt_ERR_KeyNotLoaded_E004: nothing is loaded.
|
||||||
|
"""
|
||||||
|
if not self.core.keys_loaded:
|
||||||
|
raise ChaosCrypt_ERR_KeyNotLoaded_E004()
|
||||||
|
c = self.core
|
||||||
|
return {
|
||||||
|
"key_file": self.key_file,
|
||||||
|
"version": KEYFILE_VERSION,
|
||||||
|
"upper_mapping": c.upper_mapping,
|
||||||
|
"lower_mapping": c.lower_mapping,
|
||||||
|
"digit_mapping": c.digit_mapping,
|
||||||
|
"equal_mapping": c.equal_mapping,
|
||||||
|
"flip_pattern": c.flip_pattern,
|
||||||
|
"long_key_length": len(c.long_key),
|
||||||
|
"short_key_length": len(c.short_key),
|
||||||
|
"loaded": True,
|
||||||
|
}
|
||||||
|
|
||||||
|
def change_key_password(
|
||||||
|
self,
|
||||||
|
old_password: str,
|
||||||
|
new_password: str,
|
||||||
|
key_file: Optional[str] = None,
|
||||||
|
) -> str:
|
||||||
|
"""Re-wrap an existing key file under a new password.
|
||||||
|
|
||||||
|
The key material itself is unchanged, so data encrypted before the
|
||||||
|
change remains readable.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The key file path.
|
||||||
|
"""
|
||||||
|
if not new_password:
|
||||||
|
raise ChaosCrypt_ERR_EmptyPassword_E006(
|
||||||
|
detail="EmptyNewPassword", code="E006"
|
||||||
|
)
|
||||||
|
target = key_file or self.key_file or self.default_key_file
|
||||||
|
if not os.path.exists(target):
|
||||||
|
raise ChaosCrypt_ERR_KeyFileNotFound_E001(
|
||||||
|
detail=f"KeyFileNotFound:{target}", code="E001"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Verifies old_password before we overwrite anything.
|
||||||
|
self.load(target, old_password)
|
||||||
|
|
||||||
|
keys_data = {
|
||||||
|
'upper_mapping': self.core.upper_mapping,
|
||||||
|
'lower_mapping': self.core.lower_mapping,
|
||||||
|
'digit_mapping': self.core.digit_mapping,
|
||||||
|
'equal_mapping': self.core.equal_mapping,
|
||||||
|
'flip_pattern': self.core.flip_pattern,
|
||||||
|
'long_key': self.core.long_key,
|
||||||
|
'short_key': self.core.short_key,
|
||||||
|
'generated_at': __import__("datetime").datetime.now().isoformat(),
|
||||||
|
}
|
||||||
|
obfuscated = self.core._obfuscate_keys(keys_data)
|
||||||
|
encrypted = self.core._xor_encrypt_data(obfuscated, new_password)
|
||||||
|
with open(target, 'w') as f:
|
||||||
|
f.write(encrypted)
|
||||||
|
|
||||||
|
self.key_password = new_password
|
||||||
|
return target
|
||||||
|
|
||||||
|
# ==================================================================
|
||||||
|
# Encryption / decryption
|
||||||
|
# ==================================================================
|
||||||
|
def _ensure_ready(self) -> None:
|
||||||
|
if not self.core.keys_loaded:
|
||||||
|
raise ChaosCrypt_ERR_KeyNotLoaded_E004()
|
||||||
|
|
||||||
|
def encrypt(self, plaintext: str, password: str) -> str:
|
||||||
|
"""Encrypt a string.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
plaintext: Data to encrypt.
|
||||||
|
password: Encryption password, independent of the key file password.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Ciphertext as a hexadecimal string.
|
||||||
|
"""
|
||||||
|
self._ensure_ready()
|
||||||
|
return self.core.encrypt_text(plaintext, password)
|
||||||
|
|
||||||
|
def decrypt(self, ciphertext: str, password: str) -> str:
|
||||||
|
"""Decrypt a hexadecimal ciphertext back into a string."""
|
||||||
|
self._ensure_ready()
|
||||||
|
return self.core.decrypt_text(ciphertext.strip(), password)
|
||||||
|
|
||||||
|
def encrypt_bytes(self, data: bytes, password: str) -> str:
|
||||||
|
"""Encrypt arbitrary binary data, returning a hex ciphertext."""
|
||||||
|
self._ensure_ready()
|
||||||
|
return self.core.encrypt_bytes(data, password)
|
||||||
|
|
||||||
|
def decrypt_bytes(self, ciphertext: str, password: str) -> bytes:
|
||||||
|
"""Decrypt a hex ciphertext back into binary data."""
|
||||||
|
self._ensure_ready()
|
||||||
|
return self.core.decrypt_bytes(ciphertext.strip(), password)
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# File helpers
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def encrypt_file(
|
||||||
|
self,
|
||||||
|
src: str,
|
||||||
|
password: str,
|
||||||
|
dst: Optional[str] = None,
|
||||||
|
) -> str:
|
||||||
|
"""Encrypt a file, writing UTF-8 hex ciphertext. Returns the output path."""
|
||||||
|
self._ensure_ready()
|
||||||
|
target = dst or (src + ".cc")
|
||||||
|
try:
|
||||||
|
with open(src, "rb") as f:
|
||||||
|
raw = f.read()
|
||||||
|
except OSError as exc:
|
||||||
|
raise ChaosCrypt_ERR_FileReadFailed_E014(
|
||||||
|
detail=f"FileReadFailed:{exc}", code="E014"
|
||||||
|
)
|
||||||
|
ct = self.encrypt_bytes(raw, password)
|
||||||
|
try:
|
||||||
|
with open(target, "w", encoding="utf-8") as f:
|
||||||
|
f.write(ct)
|
||||||
|
except OSError as exc:
|
||||||
|
raise ChaosCrypt_ERR_FileWriteFailed_E015(
|
||||||
|
detail=f"FileWriteFailed:{exc}", code="E015"
|
||||||
|
)
|
||||||
|
return target
|
||||||
|
|
||||||
|
def decrypt_file(
|
||||||
|
self,
|
||||||
|
src: str,
|
||||||
|
password: str,
|
||||||
|
dst: Optional[str] = None,
|
||||||
|
) -> str:
|
||||||
|
"""Decrypt a ``.cc`` ciphertext file back to its original bytes."""
|
||||||
|
self._ensure_ready()
|
||||||
|
target = dst or (src[:-3] if src.endswith(".cc") else src + ".out")
|
||||||
|
try:
|
||||||
|
with open(src, "r", encoding="utf-8") as f:
|
||||||
|
ct = f.read()
|
||||||
|
except OSError as exc:
|
||||||
|
raise ChaosCrypt_ERR_FileReadFailed_E014(
|
||||||
|
detail=f"FileReadFailed:{exc}", code="E014"
|
||||||
|
)
|
||||||
|
raw = self.decrypt_bytes(ct, password)
|
||||||
|
try:
|
||||||
|
with open(target, "wb") as f:
|
||||||
|
f.write(raw)
|
||||||
|
except OSError as exc:
|
||||||
|
raise ChaosCrypt_ERR_FileWriteFailed_E015(
|
||||||
|
detail=f"FileWriteFailed:{exc}", code="E015"
|
||||||
|
)
|
||||||
|
return target
|
||||||
|
|
||||||
|
|
||||||
|
# ======================================================================
|
||||||
|
# Module-level conveniences for one-off use
|
||||||
|
# ======================================================================
|
||||||
|
def encrypt(
|
||||||
|
plaintext: str,
|
||||||
|
password: str,
|
||||||
|
key_file: str = DEFAULT_KEY_FILE,
|
||||||
|
key_password: Optional[str] = None,
|
||||||
|
) -> str:
|
||||||
|
"""Load a key file and encrypt in one call.
|
||||||
|
|
||||||
|
When ``key_password`` is omitted it falls back to ``password``, which
|
||||||
|
suits setups where the same secret guards both layers.
|
||||||
|
"""
|
||||||
|
cc = ChaosCrypt()
|
||||||
|
cc.load(key_file, key_password if key_password is not None else password)
|
||||||
|
return cc.encrypt(plaintext, password)
|
||||||
|
|
||||||
|
|
||||||
|
def decrypt(
|
||||||
|
ciphertext: str,
|
||||||
|
password: str,
|
||||||
|
key_file: str = DEFAULT_KEY_FILE,
|
||||||
|
key_password: Optional[str] = None,
|
||||||
|
) -> str:
|
||||||
|
"""Load a key file and decrypt in one call."""
|
||||||
|
cc = ChaosCrypt()
|
||||||
|
cc.load(key_file, key_password if key_password is not None else password)
|
||||||
|
return cc.decrypt(ciphertext, password)
|
||||||
|
|
||||||
|
|
||||||
|
def create_key(
|
||||||
|
key_password: str,
|
||||||
|
key_file: str = DEFAULT_KEY_FILE,
|
||||||
|
*,
|
||||||
|
overwrite: bool = False,
|
||||||
|
) -> str:
|
||||||
|
"""Generate a key file in one call. Returns the path written."""
|
||||||
|
return ChaosCrypt().create_key(key_password, key_file, overwrite=overwrite)
|
||||||
@@ -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())
|
||||||
@@ -0,0 +1,740 @@
|
|||||||
|
"""
|
||||||
|
ChaosCrypt algorithm core.
|
||||||
|
|
||||||
|
This module is the algorithm itself. It is a faithful, behaviour-preserving
|
||||||
|
port of the original single-file implementation: every substitution table,
|
||||||
|
bit operation, loop bound and character-level rule is reproduced exactly.
|
||||||
|
|
||||||
|
What changed relative to the original script is only the *plumbing*:
|
||||||
|
|
||||||
|
* ``print`` / ``input`` calls were removed, so the module is usable as a library;
|
||||||
|
* failure paths raise :class:`~chaoscrypt.errors.ChaosCryptError` instead of
|
||||||
|
returning sentinel strings such as ``"decryption failed"``.
|
||||||
|
|
||||||
|
As a result, ciphertexts and key files are fully interoperable in **both**
|
||||||
|
directions with the original implementation.
|
||||||
|
|
||||||
|
Security notice
|
||||||
|
---------------
|
||||||
|
ChaosCrypt has not been independently audited and is not a standardised
|
||||||
|
cryptographic construction. It is intended for obfuscation, personal use, and
|
||||||
|
study. See ``SECURITY.md`` for the full design and threat analysis.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from .errors import (
|
||||||
|
ChaosCryptError,
|
||||||
|
ChaosCrypt_ERR_KeyNotLoaded_E004,
|
||||||
|
ChaosCrypt_ERR_KeyFileCorrupted_E002,
|
||||||
|
ChaosCrypt_ERR_KeyPasswordIncorrect_E003,
|
||||||
|
ChaosCrypt_ERR_DecryptionFailed_E011,
|
||||||
|
ChaosCrypt_ERR_EmptyPassword_E006,
|
||||||
|
ChaosCrypt_ERR_EmptyPlaintext_E008,
|
||||||
|
ChaosCrypt_ERR_EmptyCiphertext_E009,
|
||||||
|
ChaosCrypt_ERR_MalformedCiphertext_E010,
|
||||||
|
)
|
||||||
|
|
||||||
|
__all__ = ["ChaosCryptCore", "KEYFILE_VERSION"]
|
||||||
|
|
||||||
|
#: Version of the on-disk key file format.
|
||||||
|
KEYFILE_VERSION = 1
|
||||||
|
|
||||||
|
#: Print-range used throughout the algorithm (printable ASCII, 0x20..0x7E).
|
||||||
|
_PRINT_MIN = 32
|
||||||
|
_PRINT_MAX = 126
|
||||||
|
_PRINT_SPAN = 95
|
||||||
|
|
||||||
|
#: Marker separating the payload from its metadata inside the intermediate form.
|
||||||
|
_SEP = "|"
|
||||||
|
|
||||||
|
|
||||||
|
class ChaosCryptCore:
|
||||||
|
"""The ChaosCrypt algorithm, free of any I/O or user interaction.
|
||||||
|
|
||||||
|
Responsibilities:
|
||||||
|
|
||||||
|
* generating the random system key material (substitution tables, long and
|
||||||
|
short keys, flip pattern);
|
||||||
|
* wrapping that material into a password-protected key file;
|
||||||
|
* encrypting and decrypting text and arbitrary binary data.
|
||||||
|
|
||||||
|
Every failure is reported as a :class:`~chaoscrypt.errors.ChaosCryptError`
|
||||||
|
subclass.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
# Character remapping used to keep the ciphertext inside Base64's
|
||||||
|
# alphabet while the '=' padding is handled out-of-band.
|
||||||
|
self.special_encrypt = {
|
||||||
|
'+': '.',
|
||||||
|
'/': "'",
|
||||||
|
'=': '',
|
||||||
|
}
|
||||||
|
self.special_decrypt = {
|
||||||
|
'.': '+',
|
||||||
|
"'": '/',
|
||||||
|
}
|
||||||
|
|
||||||
|
self.flip_pattern = None
|
||||||
|
self.keys_loaded = False
|
||||||
|
|
||||||
|
# Key material; populated by generate_keymaterial() or load_keys*().
|
||||||
|
self.upper_mapping = None
|
||||||
|
self.lower_mapping = None
|
||||||
|
self.digit_mapping = None
|
||||||
|
self.equal_mapping = None
|
||||||
|
self.long_key = None
|
||||||
|
self.short_key = None
|
||||||
|
|
||||||
|
self.digit_reverse = None
|
||||||
|
self.equal_reverse = None
|
||||||
|
|
||||||
|
self.upper_original = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
||||||
|
self.lower_original = "abcdefghijklmnopqrstuvwxyz"
|
||||||
|
self.encrypt_map = {}
|
||||||
|
self.decrypt_map = {}
|
||||||
|
|
||||||
|
# ======================================================================
|
||||||
|
# Random key material
|
||||||
|
# ======================================================================
|
||||||
|
def _generate_random_alphabet(self, lowercase: bool = False) -> str:
|
||||||
|
"""Return a uniformly random permutation of the A-Z or a-z alphabet."""
|
||||||
|
chars = list(
|
||||||
|
"abcdefghijklmnopqrstuvwxyz" if lowercase
|
||||||
|
else "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
||||||
|
)
|
||||||
|
n = len(chars)
|
||||||
|
for i in range(n - 1, 0, -1):
|
||||||
|
j = int.from_bytes(os.urandom(1), 'big') % (i + 1)
|
||||||
|
chars[i], chars[j] = chars[j], chars[i]
|
||||||
|
return ''.join(chars)
|
||||||
|
|
||||||
|
def _generate_random_digit_mapping(self) -> dict:
|
||||||
|
"""Map each digit 0-9 to a distinct alphanumeric character."""
|
||||||
|
digits = list("0123456789")
|
||||||
|
mapping_chars = list(
|
||||||
|
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
|
||||||
|
)
|
||||||
|
n = len(mapping_chars)
|
||||||
|
for i in range(n - 1, 0, -1):
|
||||||
|
j = int.from_bytes(os.urandom(1), 'big') % (i + 1)
|
||||||
|
mapping_chars[i], mapping_chars[j] = (
|
||||||
|
mapping_chars[j], mapping_chars[i]
|
||||||
|
)
|
||||||
|
mapping = {}
|
||||||
|
for i, d in enumerate(digits):
|
||||||
|
mapping[d] = mapping_chars[i]
|
||||||
|
return mapping
|
||||||
|
|
||||||
|
def _generate_random_equal_mapping(self) -> dict:
|
||||||
|
"""Map the Base64 padding counts 0-3 to distinct characters."""
|
||||||
|
chars = list("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")
|
||||||
|
n = len(chars)
|
||||||
|
for i in range(n - 1, 0, -1):
|
||||||
|
j = int.from_bytes(os.urandom(1), 'big') % (i + 1)
|
||||||
|
chars[i], chars[j] = chars[j], chars[i]
|
||||||
|
return {
|
||||||
|
'0': chars[0],
|
||||||
|
'1': chars[1],
|
||||||
|
'2': chars[2],
|
||||||
|
'3': chars[3],
|
||||||
|
}
|
||||||
|
|
||||||
|
def _generate_random_flip_pattern(self) -> list:
|
||||||
|
"""Return a random 10-bit case-flip pattern."""
|
||||||
|
pattern = []
|
||||||
|
for _ in range(10):
|
||||||
|
bit = int.from_bytes(os.urandom(1), 'big') % 2
|
||||||
|
pattern.append(bit)
|
||||||
|
return pattern
|
||||||
|
|
||||||
|
def _generate_long_key(self, length: int = 4096) -> str:
|
||||||
|
"""Return a random hex string of ``length`` characters."""
|
||||||
|
chars = "0123456789abcdef"
|
||||||
|
result = []
|
||||||
|
for _ in range(length):
|
||||||
|
idx = int.from_bytes(os.urandom(1), 'big') % 16
|
||||||
|
result.append(chars[idx])
|
||||||
|
return ''.join(result)
|
||||||
|
|
||||||
|
def _generate_short_key(self, length: int = 512) -> str:
|
||||||
|
"""Return a shorter random hex string used for key derivation."""
|
||||||
|
chars = "0123456789abcdef"
|
||||||
|
result = []
|
||||||
|
for _ in range(length):
|
||||||
|
idx = int.from_bytes(os.urandom(1), 'big') % 16
|
||||||
|
result.append(chars[idx])
|
||||||
|
return ''.join(result)
|
||||||
|
|
||||||
|
# ======================================================================
|
||||||
|
# Key file wrapping
|
||||||
|
# ======================================================================
|
||||||
|
def _obfuscate_keys(self, keys_data: dict) -> str:
|
||||||
|
"""Encode the key material into a Base64 payload.
|
||||||
|
|
||||||
|
This is a transport encoding for the key file, not a security
|
||||||
|
boundary; confidentiality of the key file comes from the caller's
|
||||||
|
password (see :meth:`_xor_encrypt_data`).
|
||||||
|
"""
|
||||||
|
json_str = json.dumps(keys_data)
|
||||||
|
b64 = base64.b64encode(json_str.encode()).decode()
|
||||||
|
reversed_b64 = b64[::-1]
|
||||||
|
shifted = ''.join([chr((ord(c) + 1) % 128) for c in reversed_b64])
|
||||||
|
return base64.b64encode(shifted.encode()).decode()
|
||||||
|
|
||||||
|
def _deobfuscate_keys(self, obfuscated_data: str) -> dict:
|
||||||
|
"""Reverse :meth:`_obfuscate_keys`."""
|
||||||
|
try:
|
||||||
|
shifted = base64.b64decode(obfuscated_data.encode()).decode()
|
||||||
|
reversed_b64 = ''.join([chr((ord(c) - 1) % 128) for c in shifted])
|
||||||
|
b64 = reversed_b64[::-1]
|
||||||
|
json_str = base64.b64decode(b64.encode()).decode()
|
||||||
|
return json.loads(json_str)
|
||||||
|
except Exception:
|
||||||
|
raise ChaosCrypt_ERR_KeyFileCorrupted_E002()
|
||||||
|
|
||||||
|
# ======================================================================
|
||||||
|
# Password-based key file encryption
|
||||||
|
# ======================================================================
|
||||||
|
def _xor_encrypt_data(self, data: str, password: str) -> str:
|
||||||
|
"""XOR ``data`` with the repeated password, returning hex."""
|
||||||
|
result = []
|
||||||
|
key_len = len(password)
|
||||||
|
for i, char in enumerate(data):
|
||||||
|
xor_result = ord(char) ^ ord(password[i % key_len])
|
||||||
|
result.append(f"{xor_result:02x}")
|
||||||
|
return ''.join(result)
|
||||||
|
|
||||||
|
def _xor_decrypt_data(self, hex_data: str, password: str) -> str | None:
|
||||||
|
"""Reverse :meth:`_xor_encrypt_data`; ``None`` if the input is not hex."""
|
||||||
|
try:
|
||||||
|
result = []
|
||||||
|
key_len = len(password)
|
||||||
|
for i in range(0, len(hex_data), 2):
|
||||||
|
if i + 1 < len(hex_data):
|
||||||
|
hex_byte = hex_data[i:i + 2]
|
||||||
|
xor_result = (
|
||||||
|
int(hex_byte, 16) ^ ord(password[(i // 2) % key_len])
|
||||||
|
)
|
||||||
|
result.append(chr(xor_result))
|
||||||
|
return ''.join(result)
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
|
||||||
|
# ======================================================================
|
||||||
|
# Key generation / loading
|
||||||
|
# ======================================================================
|
||||||
|
def generate_keymaterial(self) -> dict:
|
||||||
|
"""Generate a complete set of random key material.
|
||||||
|
|
||||||
|
The instance is left in the *loaded* state and is immediately usable
|
||||||
|
for encryption and decryption.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The key material as a JSON-serialisable dictionary.
|
||||||
|
"""
|
||||||
|
self.upper_mapping = self._generate_random_alphabet(lowercase=False)
|
||||||
|
self.lower_mapping = self._generate_random_alphabet(lowercase=True)
|
||||||
|
self.digit_mapping = self._generate_random_digit_mapping()
|
||||||
|
self.equal_mapping = self._generate_random_equal_mapping()
|
||||||
|
self.flip_pattern = self._generate_random_flip_pattern()
|
||||||
|
self.long_key = self._generate_long_key(4096)
|
||||||
|
self.short_key = self._generate_short_key(512)
|
||||||
|
|
||||||
|
self.digit_reverse = {v: k for k, v in self.digit_mapping.items()}
|
||||||
|
self.equal_reverse = {v: k for k, v in self.equal_mapping.items()}
|
||||||
|
|
||||||
|
keys_data = {
|
||||||
|
'upper_mapping': self.upper_mapping,
|
||||||
|
'lower_mapping': self.lower_mapping,
|
||||||
|
'digit_mapping': self.digit_mapping,
|
||||||
|
'equal_mapping': self.equal_mapping,
|
||||||
|
'flip_pattern': self.flip_pattern,
|
||||||
|
'long_key': self.long_key,
|
||||||
|
'short_key': self.short_key,
|
||||||
|
'generated_at': datetime.now().isoformat(),
|
||||||
|
}
|
||||||
|
self.keys_loaded = True
|
||||||
|
self._build_maps()
|
||||||
|
return keys_data
|
||||||
|
|
||||||
|
def serialize_keys(self, key_password: str, save_path: str) -> str:
|
||||||
|
"""Generate key material and write it to ``save_path``.
|
||||||
|
|
||||||
|
The on-disk format is identical to the original implementation.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The path that was written.
|
||||||
|
"""
|
||||||
|
if not key_password:
|
||||||
|
raise ChaosCrypt_ERR_EmptyPassword_E006(
|
||||||
|
detail="EmptyKeyFilePassword", code="E006"
|
||||||
|
)
|
||||||
|
|
||||||
|
keys_data = self.generate_keymaterial()
|
||||||
|
obfuscated = self._obfuscate_keys(keys_data)
|
||||||
|
encrypted = self._xor_encrypt_data(obfuscated, key_password)
|
||||||
|
|
||||||
|
with open(save_path, 'w') as f:
|
||||||
|
f.write(encrypted)
|
||||||
|
|
||||||
|
return save_path
|
||||||
|
|
||||||
|
def _build_maps(self) -> None:
|
||||||
|
"""Derive the forward and inverse character substitution maps."""
|
||||||
|
self.upper_original = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
||||||
|
self.lower_original = "abcdefghijklmnopqrstuvwxyz"
|
||||||
|
|
||||||
|
self.encrypt_map = {}
|
||||||
|
self.decrypt_map = {}
|
||||||
|
for i in range(26):
|
||||||
|
self.encrypt_map[self.upper_original[i]] = self.upper_mapping[i]
|
||||||
|
self.encrypt_map[self.lower_original[i]] = self.lower_mapping[i]
|
||||||
|
self.decrypt_map[self.upper_mapping[i]] = self.upper_original[i]
|
||||||
|
self.decrypt_map[self.lower_mapping[i]] = self.lower_original[i]
|
||||||
|
|
||||||
|
def load_keys_from_text(self, encrypted_data: str, key_password: str) -> None:
|
||||||
|
"""Load key material from the *contents* of a key file.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ChaosCrypt_ERR_EmptyPassword_E006: no password supplied.
|
||||||
|
ChaosCrypt_ERR_KeyFileCorrupted_E002: not a plausible key file.
|
||||||
|
ChaosCrypt_ERR_KeyPasswordIncorrect_E003: password does not match.
|
||||||
|
"""
|
||||||
|
if not key_password:
|
||||||
|
raise ChaosCrypt_ERR_EmptyPassword_E006(
|
||||||
|
detail="EmptyKeyFilePassword", code="E006"
|
||||||
|
)
|
||||||
|
|
||||||
|
raw = (encrypted_data or "").strip()
|
||||||
|
if not raw:
|
||||||
|
raise ChaosCrypt_ERR_KeyFileCorrupted_E002(
|
||||||
|
detail="EmptyKeyFile", code="E002"
|
||||||
|
)
|
||||||
|
|
||||||
|
# A key file is hex text. Anything else is a malformed file rather
|
||||||
|
# than a wrong password, so report the two cases distinctly.
|
||||||
|
try:
|
||||||
|
int(raw[:2], 16)
|
||||||
|
bytes.fromhex(raw)
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
raise ChaosCrypt_ERR_KeyFileCorrupted_E002(
|
||||||
|
detail="KeyFileNotHexadecimal", code="E002"
|
||||||
|
)
|
||||||
|
|
||||||
|
decrypted = self._xor_decrypt_data(raw, key_password)
|
||||||
|
if decrypted is None:
|
||||||
|
raise ChaosCrypt_ERR_DecryptionFailed_E011()
|
||||||
|
|
||||||
|
# A wrong password yields a payload that fails to decode; that is a
|
||||||
|
# credential problem, not a damaged file.
|
||||||
|
try:
|
||||||
|
keys_data = self._deobfuscate_keys(decrypted)
|
||||||
|
except ChaosCrypt_ERR_KeyFileCorrupted_E002:
|
||||||
|
raise ChaosCrypt_ERR_KeyPasswordIncorrect_E003()
|
||||||
|
|
||||||
|
try:
|
||||||
|
self.upper_mapping = keys_data['upper_mapping']
|
||||||
|
self.lower_mapping = keys_data['lower_mapping']
|
||||||
|
self.digit_mapping = keys_data['digit_mapping']
|
||||||
|
self.equal_mapping = keys_data['equal_mapping']
|
||||||
|
self.flip_pattern = keys_data['flip_pattern']
|
||||||
|
self.long_key = keys_data['long_key']
|
||||||
|
self.short_key = keys_data['short_key']
|
||||||
|
except (KeyError, TypeError):
|
||||||
|
raise ChaosCrypt_ERR_KeyFileCorrupted_E002()
|
||||||
|
|
||||||
|
# Structural sanity check: a wrong password can occasionally decode
|
||||||
|
# into well-formed JSON that is nonetheless nonsense.
|
||||||
|
ok = (
|
||||||
|
isinstance(self.upper_mapping, str) and len(self.upper_mapping) == 26
|
||||||
|
and isinstance(self.lower_mapping, str) and len(self.lower_mapping) == 26
|
||||||
|
and isinstance(self.long_key, str) and len(self.long_key) > 0
|
||||||
|
and isinstance(self.short_key, str) and len(self.short_key) > 0
|
||||||
|
and isinstance(self.flip_pattern, list) and len(self.flip_pattern) > 0
|
||||||
|
and sorted(self.upper_mapping) == sorted("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
|
||||||
|
and sorted(self.lower_mapping) == sorted("abcdefghijklmnopqrstuvwxyz")
|
||||||
|
and isinstance(self.digit_mapping, dict) and len(self.digit_mapping) == 10
|
||||||
|
and isinstance(self.equal_mapping, dict) and len(self.equal_mapping) == 4
|
||||||
|
)
|
||||||
|
if not ok:
|
||||||
|
raise ChaosCrypt_ERR_KeyPasswordIncorrect_E003()
|
||||||
|
|
||||||
|
self.digit_reverse = {v: k for k, v in self.digit_mapping.items()}
|
||||||
|
self.equal_reverse = {v: k for k, v in self.equal_mapping.items()}
|
||||||
|
self._build_maps()
|
||||||
|
self.keys_loaded = True
|
||||||
|
|
||||||
|
def load_keys(self, key_file: str, key_password: str) -> None:
|
||||||
|
"""Read a key file from disk and load it."""
|
||||||
|
with open(key_file, 'r') as f:
|
||||||
|
encrypted_data = f.read()
|
||||||
|
self.load_keys_from_text(encrypted_data, key_password)
|
||||||
|
|
||||||
|
# ======================================================================
|
||||||
|
# Internal primitives
|
||||||
|
# ======================================================================
|
||||||
|
def _ensure_printable(self, text: str) -> str:
|
||||||
|
"""Fold any character into the printable ASCII range.
|
||||||
|
|
||||||
|
``|`` (0x7C) is preserved because it is used as the metadata
|
||||||
|
separator.
|
||||||
|
"""
|
||||||
|
result = []
|
||||||
|
for c in text:
|
||||||
|
val = ord(c)
|
||||||
|
if val == 124:
|
||||||
|
result.append('|')
|
||||||
|
elif val < _PRINT_MIN or val > _PRINT_MAX:
|
||||||
|
val = val % _PRINT_SPAN + _PRINT_MIN
|
||||||
|
result.append(chr(val))
|
||||||
|
else:
|
||||||
|
result.append(c)
|
||||||
|
return ''.join(result)
|
||||||
|
|
||||||
|
def _mix_keys(self, user_password: str, target_length: int) -> str:
|
||||||
|
"""Mix the user password with the short key into a printable stream."""
|
||||||
|
if not self.keys_loaded:
|
||||||
|
raise ChaosCrypt_ERR_KeyNotLoaded_E004()
|
||||||
|
|
||||||
|
mixed = []
|
||||||
|
max_len = max(len(user_password), len(self.short_key))
|
||||||
|
for i in range(max_len):
|
||||||
|
if i < len(user_password):
|
||||||
|
mixed.append(ord(user_password[i]))
|
||||||
|
if i < len(self.short_key):
|
||||||
|
mixed.append(ord(self.short_key[i]))
|
||||||
|
|
||||||
|
for i in range(len(mixed)):
|
||||||
|
if i % 3 == 0:
|
||||||
|
mixed[i] = (mixed[i] << 1) & 0xFF
|
||||||
|
elif i % 3 == 1:
|
||||||
|
mixed[i] = (mixed[i] >> 1) & 0xFF
|
||||||
|
else:
|
||||||
|
mixed[i] = mixed[i] ^ 0x5A
|
||||||
|
|
||||||
|
for i in range(0, len(mixed) - 3, 4):
|
||||||
|
mixed[i], mixed[i + 3] = mixed[i + 3], mixed[i]
|
||||||
|
mixed[i + 1], mixed[i + 2] = mixed[i + 2], mixed[i + 1]
|
||||||
|
|
||||||
|
mixed.reverse()
|
||||||
|
|
||||||
|
result = []
|
||||||
|
for x in mixed:
|
||||||
|
if x < _PRINT_MIN or x > _PRINT_MAX:
|
||||||
|
x = x % _PRINT_SPAN + _PRINT_MIN
|
||||||
|
result.append(chr(x))
|
||||||
|
|
||||||
|
result_str = ''.join(result)
|
||||||
|
|
||||||
|
if len(result_str) < target_length:
|
||||||
|
base_key = result_str
|
||||||
|
final_key = base_key
|
||||||
|
iteration = 0
|
||||||
|
while len(final_key) < target_length:
|
||||||
|
if iteration % 3 == 0:
|
||||||
|
next_chunk = base_key[::-1]
|
||||||
|
elif iteration % 3 == 1:
|
||||||
|
next_chunk = base_key[::-1]
|
||||||
|
next_chunk = ''.join(
|
||||||
|
[chr((ord(c) + iteration) % _PRINT_SPAN + _PRINT_MIN)
|
||||||
|
for c in next_chunk]
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
next_chunk = base_key[::-1]
|
||||||
|
next_chunk = ''.join(
|
||||||
|
[chr((ord(c) ^ iteration) % _PRINT_SPAN + _PRINT_MIN)
|
||||||
|
for c in next_chunk]
|
||||||
|
)
|
||||||
|
final_key += next_chunk
|
||||||
|
iteration += 1
|
||||||
|
result_str = final_key[:target_length]
|
||||||
|
|
||||||
|
return self._ensure_printable(result_str)
|
||||||
|
|
||||||
|
def _derive_final_key(self, user_password: str, text_length: int) -> str:
|
||||||
|
"""Derive a keystream of exactly ``text_length`` printable characters."""
|
||||||
|
mixed_key = self._mix_keys(user_password, text_length * 2)
|
||||||
|
|
||||||
|
hex_key = ''.join([f"{ord(c):02x}" for c in mixed_key])
|
||||||
|
reversed_hex = hex_key[::-1]
|
||||||
|
|
||||||
|
final_key = []
|
||||||
|
for i in range(0, len(reversed_hex), 2):
|
||||||
|
if i + 1 < len(reversed_hex):
|
||||||
|
hex_byte = reversed_hex[i:i + 2]
|
||||||
|
try:
|
||||||
|
val = int(hex_byte, 16)
|
||||||
|
if val < _PRINT_MIN or val > _PRINT_MAX:
|
||||||
|
val = val % _PRINT_SPAN + _PRINT_MIN
|
||||||
|
final_key.append(chr(val))
|
||||||
|
except ValueError:
|
||||||
|
final_key.append('x')
|
||||||
|
|
||||||
|
final_key_str = ''.join(final_key)
|
||||||
|
|
||||||
|
if len(final_key_str) < text_length:
|
||||||
|
base_key = final_key_str
|
||||||
|
iteration = 0
|
||||||
|
while len(final_key_str) < text_length:
|
||||||
|
if iteration % 3 == 0:
|
||||||
|
next_chunk = base_key[::-1]
|
||||||
|
elif iteration % 3 == 1:
|
||||||
|
next_chunk = base_key[::-1]
|
||||||
|
next_chunk = ''.join(
|
||||||
|
[chr((ord(c) + iteration) % _PRINT_SPAN + _PRINT_MIN)
|
||||||
|
for c in next_chunk]
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
next_chunk = base_key[::-1]
|
||||||
|
next_chunk = ''.join(
|
||||||
|
[chr((ord(c) ^ iteration) % _PRINT_SPAN + _PRINT_MIN)
|
||||||
|
for c in next_chunk]
|
||||||
|
)
|
||||||
|
final_key_str += next_chunk
|
||||||
|
iteration += 1
|
||||||
|
|
||||||
|
final_key_str = final_key_str[:text_length]
|
||||||
|
return self._ensure_printable(final_key_str)
|
||||||
|
|
||||||
|
def _apply_flip(self, text: str) -> str:
|
||||||
|
"""Swap the case of letters at positions selected by the flip pattern."""
|
||||||
|
if self.flip_pattern is None:
|
||||||
|
return text
|
||||||
|
|
||||||
|
result = []
|
||||||
|
for i, ch in enumerate(text):
|
||||||
|
idx = i % len(self.flip_pattern)
|
||||||
|
if ch.isalpha() and self.flip_pattern[idx] == 1:
|
||||||
|
result.append(ch.swapcase())
|
||||||
|
else:
|
||||||
|
result.append(ch)
|
||||||
|
return ''.join(result)
|
||||||
|
|
||||||
|
def _xor_encrypt_with_final_key(self, text: str, user_password: str) -> str:
|
||||||
|
"""XOR with the password-derived keystream, returning hex."""
|
||||||
|
final_key = self._derive_final_key(user_password, len(text))
|
||||||
|
key_len = len(final_key)
|
||||||
|
result = []
|
||||||
|
for i, char in enumerate(text):
|
||||||
|
xor_result = ord(char) ^ ord(final_key[i % key_len])
|
||||||
|
result.append(f"{xor_result:02x}")
|
||||||
|
return ''.join(result)
|
||||||
|
|
||||||
|
def _xor_decrypt_with_final_key(
|
||||||
|
self, hex_text: str, user_password: str
|
||||||
|
) -> str | None:
|
||||||
|
"""Reverse :meth:`_xor_encrypt_with_final_key`."""
|
||||||
|
try:
|
||||||
|
text_length = len(hex_text) // 2
|
||||||
|
final_key = self._derive_final_key(user_password, text_length)
|
||||||
|
key_len = len(final_key)
|
||||||
|
result = []
|
||||||
|
for i in range(0, len(hex_text), 2):
|
||||||
|
if i + 1 < len(hex_text):
|
||||||
|
hex_byte = hex_text[i:i + 2]
|
||||||
|
try:
|
||||||
|
xor_result = (
|
||||||
|
int(hex_byte, 16)
|
||||||
|
^ ord(final_key[(i // 2) % key_len])
|
||||||
|
)
|
||||||
|
if xor_result < _PRINT_MIN or xor_result > _PRINT_MAX:
|
||||||
|
xor_result = xor_result % _PRINT_SPAN + _PRINT_MIN
|
||||||
|
result.append(chr(xor_result))
|
||||||
|
except ValueError:
|
||||||
|
result.append('?')
|
||||||
|
return ''.join(result)
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _substitute_letters(self, text: str, mapping: dict) -> str:
|
||||||
|
"""Apply a single-character substitution table."""
|
||||||
|
return ''.join(mapping.get(char, char) for char in text)
|
||||||
|
|
||||||
|
def _encode_digit(self, num_str: str) -> str:
|
||||||
|
"""Encode a decimal string through the digit substitution table."""
|
||||||
|
return ''.join(self.digit_mapping.get(char, char) for char in num_str)
|
||||||
|
|
||||||
|
def _decode_digit(self, encoded_str: str) -> str:
|
||||||
|
"""Reverse :meth:`_encode_digit`."""
|
||||||
|
return ''.join(
|
||||||
|
self.digit_reverse.get(char, char) for char in encoded_str
|
||||||
|
)
|
||||||
|
|
||||||
|
def _get_dynamic_key(self, text_length: int) -> str:
|
||||||
|
"""Return the long key, repeated to cover ``text_length`` characters."""
|
||||||
|
key = self.long_key
|
||||||
|
while len(key) < text_length:
|
||||||
|
key += self.long_key
|
||||||
|
return key[:text_length]
|
||||||
|
|
||||||
|
def _xor_encrypt_with_key(self, text: str, key: str) -> str:
|
||||||
|
"""XOR with an explicit key, returning hex."""
|
||||||
|
key_len = len(key)
|
||||||
|
result = []
|
||||||
|
for i, char in enumerate(text):
|
||||||
|
xor_result = ord(char) ^ ord(key[i % key_len])
|
||||||
|
result.append(f"{xor_result:02x}")
|
||||||
|
return ''.join(result)
|
||||||
|
|
||||||
|
def _xor_decrypt_with_key(self, hex_text: str, key: str) -> str | None:
|
||||||
|
"""Reverse :meth:`_xor_encrypt_with_key`."""
|
||||||
|
try:
|
||||||
|
key_len = len(key)
|
||||||
|
result = []
|
||||||
|
for i in range(0, len(hex_text), 2):
|
||||||
|
if i + 1 < len(hex_text):
|
||||||
|
hex_byte = hex_text[i:i + 2]
|
||||||
|
try:
|
||||||
|
xor_result = (
|
||||||
|
int(hex_byte, 16) ^ ord(key[(i // 2) % key_len])
|
||||||
|
)
|
||||||
|
if xor_result < _PRINT_MIN or xor_result > _PRINT_MAX:
|
||||||
|
xor_result = xor_result % _PRINT_SPAN + _PRINT_MIN
|
||||||
|
result.append(chr(xor_result))
|
||||||
|
except ValueError:
|
||||||
|
result.append('?')
|
||||||
|
return ''.join(result)
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
|
||||||
|
# ======================================================================
|
||||||
|
# Public: encrypt / decrypt
|
||||||
|
# ======================================================================
|
||||||
|
def encrypt_text(self, plaintext: str, user_password: str) -> str:
|
||||||
|
"""Encrypt a string and return the ciphertext as a hex string."""
|
||||||
|
if not self.keys_loaded:
|
||||||
|
raise ChaosCrypt_ERR_KeyNotLoaded_E004()
|
||||||
|
if not user_password:
|
||||||
|
raise ChaosCrypt_ERR_EmptyPassword_E006()
|
||||||
|
if plaintext is None or plaintext == "":
|
||||||
|
raise ChaosCrypt_ERR_EmptyPlaintext_E008()
|
||||||
|
|
||||||
|
# Stage 1 - Base64 lifts arbitrary bytes into printable ASCII.
|
||||||
|
b64 = base64.b64encode(plaintext.encode('utf-8')).decode('utf-8')
|
||||||
|
equal_count = b64.count('=')
|
||||||
|
|
||||||
|
# Stage 2 - remap the characters Base64 may emit.
|
||||||
|
processed = b64
|
||||||
|
for old, new in self.special_encrypt.items():
|
||||||
|
processed = processed.replace(old, new)
|
||||||
|
processed = processed.rstrip('=')
|
||||||
|
|
||||||
|
# Stage 3 - substitution, case flipping, reversal.
|
||||||
|
sub = self._substitute_letters(processed, self.encrypt_map)
|
||||||
|
flipped = self._apply_flip(sub)
|
||||||
|
reversed_text = flipped[::-1]
|
||||||
|
|
||||||
|
# Stage 4 - keep the padding count so decryption can restore it.
|
||||||
|
equal_char = self.equal_mapping[str(equal_count)]
|
||||||
|
with_equal = f"{reversed_text}{_SEP}{equal_char}"
|
||||||
|
|
||||||
|
key_length_str = str(len(with_equal))
|
||||||
|
key_length_encoded = self._encode_digit(key_length_str)
|
||||||
|
|
||||||
|
# Stage 5 - XOR with the long key, then with the password keystream.
|
||||||
|
dynamic_key = self._get_dynamic_key(len(with_equal))
|
||||||
|
encrypted_by_dynamic = self._xor_encrypt_with_key(with_equal, dynamic_key)
|
||||||
|
|
||||||
|
combined = f"{encrypted_by_dynamic}{_SEP}{key_length_encoded}"
|
||||||
|
return self._xor_encrypt_with_final_key(combined, user_password)
|
||||||
|
|
||||||
|
def decrypt_text(self, ciphertext: str, user_password: str) -> str:
|
||||||
|
"""Decrypt a hex ciphertext back into the original string."""
|
||||||
|
if not self.keys_loaded:
|
||||||
|
raise ChaosCrypt_ERR_KeyNotLoaded_E004()
|
||||||
|
if not user_password:
|
||||||
|
raise ChaosCrypt_ERR_EmptyPassword_E006()
|
||||||
|
if ciphertext is None or ciphertext == "":
|
||||||
|
raise ChaosCrypt_ERR_EmptyCiphertext_E009()
|
||||||
|
|
||||||
|
stripped = ciphertext.strip()
|
||||||
|
|
||||||
|
# Reject anything that is not well-formed hex up front: silently
|
||||||
|
# "decrypting" garbage would otherwise be indistinguishable from
|
||||||
|
# success.
|
||||||
|
if len(stripped) % 2 != 0:
|
||||||
|
raise ChaosCrypt_ERR_MalformedCiphertext_E010(
|
||||||
|
detail="OddLengthCiphertext", code="E010"
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
int(stripped, 16)
|
||||||
|
except ValueError:
|
||||||
|
raise ChaosCrypt_ERR_MalformedCiphertext_E010(
|
||||||
|
detail="NonHexadecimalCiphertext", code="E010"
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
combined = self._xor_decrypt_with_final_key(stripped, user_password)
|
||||||
|
if combined is None:
|
||||||
|
raise ChaosCrypt_ERR_DecryptionFailed_E011()
|
||||||
|
|
||||||
|
if _SEP in combined:
|
||||||
|
parts = combined.split(_SEP)
|
||||||
|
if len(parts) >= 2:
|
||||||
|
hex_data, key_length_encoded = parts[0], parts[1]
|
||||||
|
else:
|
||||||
|
hex_data, key_length_encoded = parts[0], 'g'
|
||||||
|
else:
|
||||||
|
hex_data, key_length_encoded = combined, 'g'
|
||||||
|
|
||||||
|
key_length_str = self._decode_digit(key_length_encoded)
|
||||||
|
try:
|
||||||
|
key_length = int(key_length_str)
|
||||||
|
except ValueError:
|
||||||
|
key_length = 16
|
||||||
|
|
||||||
|
dynamic_key = self._get_dynamic_key(key_length)
|
||||||
|
xor_decrypted = self._xor_decrypt_with_key(hex_data, dynamic_key)
|
||||||
|
if xor_decrypted is None:
|
||||||
|
raise ChaosCrypt_ERR_DecryptionFailed_E011()
|
||||||
|
|
||||||
|
if _SEP in xor_decrypted:
|
||||||
|
main_part, equal_char = xor_decrypted.split(_SEP)
|
||||||
|
equal_count = int(self.equal_reverse.get(equal_char, '0'))
|
||||||
|
else:
|
||||||
|
main_part, equal_count = xor_decrypted, 0
|
||||||
|
|
||||||
|
reversed_text = main_part[::-1]
|
||||||
|
flipped = self._apply_flip(reversed_text)
|
||||||
|
sub = self._substitute_letters(flipped, self.decrypt_map)
|
||||||
|
|
||||||
|
for old, new in self.special_decrypt.items():
|
||||||
|
sub = sub.replace(old, new)
|
||||||
|
|
||||||
|
b64_with_equal = sub + '=' * equal_count
|
||||||
|
if len(b64_with_equal) % 4 != 0:
|
||||||
|
raise ChaosCrypt_ERR_DecryptionFailed_E011()
|
||||||
|
|
||||||
|
raw = base64.b64decode(b64_with_equal.encode('utf-8'), validate=True)
|
||||||
|
return raw.decode('utf-8')
|
||||||
|
|
||||||
|
except ChaosCryptError:
|
||||||
|
raise
|
||||||
|
except Exception:
|
||||||
|
raise ChaosCrypt_ERR_DecryptionFailed_E011()
|
||||||
|
|
||||||
|
# ======================================================================
|
||||||
|
# Public: binary
|
||||||
|
# ======================================================================
|
||||||
|
def encrypt_bytes(self, data: bytes, user_password: str) -> str:
|
||||||
|
"""Encrypt arbitrary binary data, returning a hex ciphertext."""
|
||||||
|
if data is None or len(data) == 0:
|
||||||
|
raise ChaosCrypt_ERR_EmptyPlaintext_E008()
|
||||||
|
return self.encrypt_text(
|
||||||
|
base64.b64encode(data).decode('ascii'), user_password
|
||||||
|
)
|
||||||
|
|
||||||
|
def decrypt_bytes(self, ciphertext: str, user_password: str) -> bytes:
|
||||||
|
"""Decrypt a hex ciphertext back into the original binary data."""
|
||||||
|
text = self.decrypt_text(ciphertext, user_password)
|
||||||
|
try:
|
||||||
|
return base64.b64decode(text.encode('ascii'))
|
||||||
|
except Exception:
|
||||||
|
raise ChaosCrypt_ERR_DecryptionFailed_E011()
|
||||||
@@ -0,0 +1,598 @@
|
|||||||
|
"""
|
||||||
|
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__
|
||||||
|
from .errors import ChaosCryptError, ChaosCrypt_ERR_InvalidArgument_E013
|
||||||
|
|
||||||
|
__all__ = ["build_parser", "main", "cli_main"]
|
||||||
|
|
||||||
|
PROG = "chaoscrypt"
|
||||||
|
|
||||||
|
EXIT_OK = 0
|
||||||
|
EXIT_ERROR = 1
|
||||||
|
EXIT_USAGE = 2
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Password resolution
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def _resolve_password(
|
||||||
|
inline: Optional[str],
|
||||||
|
env: Optional[str],
|
||||||
|
file_path: Optional[str],
|
||||||
|
what: str = "password",
|
||||||
|
) -> Optional[str]:
|
||||||
|
"""Resolve a password from the command line.
|
||||||
|
|
||||||
|
Precedence is inline value, then environment variable, then file. Files
|
||||||
|
are read from their last non-empty line, so ``echo secret > .pwd`` works.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ChaosCrypt_ERR_InvalidArgument_E013: the source was unreadable.
|
||||||
|
"""
|
||||||
|
if inline is not None:
|
||||||
|
return inline
|
||||||
|
|
||||||
|
if env:
|
||||||
|
val = os.environ.get(env)
|
||||||
|
if val is None:
|
||||||
|
raise ChaosCrypt_ERR_InvalidArgument_E013(
|
||||||
|
detail=f"EnvVarNotSet:{env}", code="E013"
|
||||||
|
)
|
||||||
|
return val
|
||||||
|
|
||||||
|
if file_path:
|
||||||
|
try:
|
||||||
|
with open(file_path, "r", encoding="utf-8") as f:
|
||||||
|
content = f.read()
|
||||||
|
except OSError as exc:
|
||||||
|
raise ChaosCrypt_ERR_InvalidArgument_E013(
|
||||||
|
detail=f"PasswordFileUnreadable:{exc}", code="E013"
|
||||||
|
)
|
||||||
|
lines = [ln.strip() for ln in content.splitlines() if ln.strip()]
|
||||||
|
if not lines:
|
||||||
|
raise ChaosCrypt_ERR_InvalidArgument_E013(
|
||||||
|
detail=f"PasswordFileEmpty:{file_path}", code="E013"
|
||||||
|
)
|
||||||
|
return lines[-1]
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _add_password_opts(
|
||||||
|
parser: argparse.ArgumentParser,
|
||||||
|
prefix: str,
|
||||||
|
label: str,
|
||||||
|
*,
|
||||||
|
dest_prefix: str = "",
|
||||||
|
long_prefix: str = "pwd",
|
||||||
|
) -> None:
|
||||||
|
"""Attach a standard password option group to a subcommand.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
parser: Subcommand parser to extend.
|
||||||
|
prefix: Short option such as ``-p`` or ``-P``.
|
||||||
|
label: Human-readable label, e.g. ``"encryption password"``.
|
||||||
|
dest_prefix: Attribute prefix so two password groups can coexist.
|
||||||
|
long_prefix: Long option stem, e.g. ``pwd`` or ``key-pwd``.
|
||||||
|
"""
|
||||||
|
group = parser.add_argument_group(f"{label} options")
|
||||||
|
group.add_argument(
|
||||||
|
prefix,
|
||||||
|
f"--{long_prefix}",
|
||||||
|
dest=f"{dest_prefix}password",
|
||||||
|
metavar="PWD",
|
||||||
|
help=f"{label} on the command line "
|
||||||
|
f"(not recommended: visible in shell history)",
|
||||||
|
)
|
||||||
|
group.add_argument(
|
||||||
|
f"--{long_prefix}-env",
|
||||||
|
dest=f"{dest_prefix}password_env",
|
||||||
|
metavar="VAR",
|
||||||
|
help=f"read {label} from environment variable VAR",
|
||||||
|
)
|
||||||
|
group.add_argument(
|
||||||
|
f"--{long_prefix}-file",
|
||||||
|
dest=f"{dest_prefix}password_file",
|
||||||
|
metavar="PATH",
|
||||||
|
help=f"read {label} from the last non-empty line of PATH",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Parser
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def build_parser() -> argparse.ArgumentParser:
|
||||||
|
"""Build the top-level argument parser."""
|
||||||
|
parser = argparse.ArgumentParser(
|
||||||
|
prog=PROG,
|
||||||
|
description=(
|
||||||
|
"ChaosCrypt - a chaos-based obfuscation cipher.\n"
|
||||||
|
"Unaudited and non-standardised: intended for obfuscation, "
|
||||||
|
"personal use and study, not for production systems."
|
||||||
|
),
|
||||||
|
epilog=(
|
||||||
|
"examples:\n"
|
||||||
|
" chaoscrypt launch the interactive TUI\n"
|
||||||
|
" chaoscrypt keygen -k my.key --key-pwd-env KP\n"
|
||||||
|
" chaoscrypt encrypt \"hello\" -p secret -k my.key -P keypass\n"
|
||||||
|
" chaoscrypt decrypt \"1a2b...\" -p secret -k my.key -P keypass\n"
|
||||||
|
" chaoscrypt file encrypt photo.png -p secret -k my.key -P keypass\n"
|
||||||
|
" chaoscrypt info -k my.key -P keypass --json\n"
|
||||||
|
),
|
||||||
|
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"-V", "--version", action="version",
|
||||||
|
version=f"{PROG} {__version__} (MIT licence, unaudited, as-is)",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"-j", "--json", action="store_true",
|
||||||
|
help="emit machine-readable JSON on stdout",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"-q", "--quiet", action="store_true",
|
||||||
|
help="suppress non-essential human-readable output",
|
||||||
|
)
|
||||||
|
|
||||||
|
sub = parser.add_subparsers(dest="command", metavar="<command>")
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------ keygen
|
||||||
|
p_keygen = sub.add_parser(
|
||||||
|
"keygen", help="generate a new key file",
|
||||||
|
description="Generate a new ChaosCrypt key file.",
|
||||||
|
)
|
||||||
|
p_keygen.add_argument(
|
||||||
|
"-k", "--key-file", default=DEFAULT_KEY_FILE, metavar="PATH",
|
||||||
|
help=f"output key file (default: {DEFAULT_KEY_FILE})",
|
||||||
|
)
|
||||||
|
p_keygen.add_argument(
|
||||||
|
"-f", "--force", action="store_true",
|
||||||
|
help="overwrite if the target already exists",
|
||||||
|
)
|
||||||
|
_add_password_opts(p_keygen, "-P", "key file password",
|
||||||
|
dest_prefix="key_", long_prefix="key-pwd")
|
||||||
|
|
||||||
|
# ----------------------------------------------------------------- encrypt
|
||||||
|
p_enc = sub.add_parser(
|
||||||
|
"encrypt", help="encrypt text",
|
||||||
|
description="Encrypt a string into a hexadecimal ciphertext.",
|
||||||
|
)
|
||||||
|
p_enc.add_argument("text", nargs="?", help="plaintext (use - for stdin)")
|
||||||
|
p_enc.add_argument(
|
||||||
|
"-i", "--in", dest="in_file", metavar="PATH",
|
||||||
|
help="read plaintext from a file instead of argv",
|
||||||
|
)
|
||||||
|
p_enc.add_argument(
|
||||||
|
"-o", "--out", dest="out_file", metavar="PATH",
|
||||||
|
help="write ciphertext to a file instead of stdout",
|
||||||
|
)
|
||||||
|
p_enc.add_argument(
|
||||||
|
"-k", "--key-file", default=DEFAULT_KEY_FILE, metavar="PATH",
|
||||||
|
help=f"key file (default: {DEFAULT_KEY_FILE})",
|
||||||
|
)
|
||||||
|
_add_password_opts(p_enc, "-p", "encryption password",
|
||||||
|
dest_prefix="", long_prefix="pwd")
|
||||||
|
_add_password_opts(p_enc, "-P", "key file password",
|
||||||
|
dest_prefix="key_", long_prefix="key-pwd")
|
||||||
|
|
||||||
|
# ----------------------------------------------------------------- decrypt
|
||||||
|
p_dec = sub.add_parser(
|
||||||
|
"decrypt", help="decrypt text",
|
||||||
|
description="Decrypt a hexadecimal ciphertext back into text.",
|
||||||
|
)
|
||||||
|
p_dec.add_argument("text", nargs="?", help="ciphertext (use - for stdin)")
|
||||||
|
p_dec.add_argument(
|
||||||
|
"-i", "--in", dest="in_file", metavar="PATH",
|
||||||
|
help="read ciphertext from a file instead of argv",
|
||||||
|
)
|
||||||
|
p_dec.add_argument(
|
||||||
|
"-o", "--out", dest="out_file", metavar="PATH",
|
||||||
|
help="write plaintext to a file instead of stdout",
|
||||||
|
)
|
||||||
|
p_dec.add_argument(
|
||||||
|
"-k", "--key-file", default=DEFAULT_KEY_FILE, metavar="PATH",
|
||||||
|
help=f"key file (default: {DEFAULT_KEY_FILE})",
|
||||||
|
)
|
||||||
|
_add_password_opts(p_dec, "-p", "encryption password",
|
||||||
|
dest_prefix="", long_prefix="pwd")
|
||||||
|
_add_password_opts(p_dec, "-P", "key file password",
|
||||||
|
dest_prefix="key_", long_prefix="key-pwd")
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------- file
|
||||||
|
p_file = sub.add_parser(
|
||||||
|
"file", help="encrypt or decrypt whole files (binary-safe)",
|
||||||
|
description="Binary-safe file encryption and decryption.",
|
||||||
|
)
|
||||||
|
file_sub = p_file.add_subparsers(dest="file_command", metavar="<action>")
|
||||||
|
|
||||||
|
p_fe = file_sub.add_parser("encrypt", help="encrypt a file to .cc")
|
||||||
|
p_fe.add_argument("src", help="source file")
|
||||||
|
p_fe.add_argument(
|
||||||
|
"-o", "--out", dest="out_file", metavar="PATH",
|
||||||
|
help="output path (default: <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")
|
||||||
|
p_fd.add_argument("src", help="source .cc file")
|
||||||
|
p_fd.add_argument(
|
||||||
|
"-o", "--out", dest="out_file", metavar="PATH",
|
||||||
|
help="output path (default: strip the .cc suffix)",
|
||||||
|
)
|
||||||
|
p_fd.add_argument("-k", "--key-file", default=DEFAULT_KEY_FILE, metavar="PATH")
|
||||||
|
_add_password_opts(p_fd, "-p", "encryption password",
|
||||||
|
dest_prefix="", long_prefix="pwd")
|
||||||
|
_add_password_opts(p_fd, "-P", "key file password",
|
||||||
|
dest_prefix="key_", long_prefix="key-pwd")
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------- info
|
||||||
|
p_info = sub.add_parser(
|
||||||
|
"info", help="show key file metadata",
|
||||||
|
description="Show metadata for a key file. Secret material is "
|
||||||
|
"redacted unless --show-maps is given.",
|
||||||
|
)
|
||||||
|
p_info.add_argument(
|
||||||
|
"-k", "--key-file", default=DEFAULT_KEY_FILE, metavar="PATH",
|
||||||
|
help=f"key file (default: {DEFAULT_KEY_FILE})",
|
||||||
|
)
|
||||||
|
_add_password_opts(p_info, "-P", "key file password",
|
||||||
|
dest_prefix="key_", long_prefix="key-pwd")
|
||||||
|
p_info.add_argument(
|
||||||
|
"--show-maps", action="store_true",
|
||||||
|
help="also print the substitution tables (sensitive)",
|
||||||
|
)
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------- chpwd
|
||||||
|
p_chpwd = sub.add_parser(
|
||||||
|
"chpwd", help="change a key file password",
|
||||||
|
description="Re-wrap an existing key file under a new password. "
|
||||||
|
"The key material itself is unchanged.",
|
||||||
|
)
|
||||||
|
p_chpwd.add_argument(
|
||||||
|
"-k", "--key-file", default=DEFAULT_KEY_FILE, metavar="PATH",
|
||||||
|
)
|
||||||
|
_add_password_opts(p_chpwd, "-P", "current key file password",
|
||||||
|
dest_prefix="key_", long_prefix="key-pwd")
|
||||||
|
p_chpwd.add_argument(
|
||||||
|
"--new-pwd", metavar="PWD", help="new key file password",
|
||||||
|
)
|
||||||
|
p_chpwd.add_argument(
|
||||||
|
"--new-pwd-env", metavar="VAR",
|
||||||
|
help="read the new key file password from environment variable VAR",
|
||||||
|
)
|
||||||
|
p_chpwd.add_argument(
|
||||||
|
"--new-pwd-file", metavar="PATH",
|
||||||
|
help="read the new key file password from PATH",
|
||||||
|
)
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------- tui
|
||||||
|
sub.add_parser(
|
||||||
|
"tui", help="launch the interactive TUI",
|
||||||
|
description="Launch the interactive terminal UI, identical to "
|
||||||
|
"running chaoscrypt with no arguments.",
|
||||||
|
)
|
||||||
|
|
||||||
|
return parser
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Output helpers
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def _emit(payload: dict, args: argparse.Namespace,
|
||||||
|
human_lines: Optional[List[str]] = None) -> None:
|
||||||
|
"""Print either JSON or human-readable lines."""
|
||||||
|
if getattr(args, "json", False):
|
||||||
|
print(json.dumps(payload, ensure_ascii=False, indent=2))
|
||||||
|
return
|
||||||
|
if not getattr(args, "quiet", False) and human_lines:
|
||||||
|
for line in human_lines:
|
||||||
|
print(line)
|
||||||
|
|
||||||
|
|
||||||
|
def _err_exit(exc: ChaosCryptError, args: argparse.Namespace) -> int:
|
||||||
|
"""Report a unified error and return the runtime-error exit code."""
|
||||||
|
if getattr(args, "json", False):
|
||||||
|
print(json.dumps(
|
||||||
|
{"ok": False, "error": str(exc), "code": exc.code},
|
||||||
|
ensure_ascii=False, indent=2,
|
||||||
|
))
|
||||||
|
else:
|
||||||
|
print(f"error: {exc}", file=sys.stderr)
|
||||||
|
return EXIT_ERROR
|
||||||
|
|
||||||
|
|
||||||
|
def _read_input(inline: Optional[str], in_file: Optional[str],
|
||||||
|
what: str = "input") -> str:
|
||||||
|
"""Read payload from argv, a file, or stdin."""
|
||||||
|
if in_file:
|
||||||
|
try:
|
||||||
|
with open(in_file, "r", encoding="utf-8") as f:
|
||||||
|
return f.read().strip()
|
||||||
|
except OSError as exc:
|
||||||
|
raise ChaosCrypt_ERR_InvalidArgument_E013(
|
||||||
|
detail=f"InputFileUnreadable:{exc}", code="E013"
|
||||||
|
)
|
||||||
|
if inline is not None and inline != "-":
|
||||||
|
return inline
|
||||||
|
|
||||||
|
# '-' or nothing at all: read stdin.
|
||||||
|
data = sys.stdin.read()
|
||||||
|
if not data:
|
||||||
|
raise ChaosCrypt_ERR_InvalidArgument_E013(
|
||||||
|
detail=f"MissingInput:{what}", code="E013"
|
||||||
|
)
|
||||||
|
return data.strip()
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Command implementations
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def _cmd_keygen(args: argparse.Namespace) -> int:
|
||||||
|
from . import ChaosCrypt
|
||||||
|
from .errors import ChaosCrypt_ERR_EmptyPassword_E006
|
||||||
|
|
||||||
|
pwd = _resolve_password(
|
||||||
|
args.key_password, args.key_password_env, args.key_password_file,
|
||||||
|
"key file password",
|
||||||
|
)
|
||||||
|
if pwd is None:
|
||||||
|
return _err_exit(
|
||||||
|
ChaosCrypt_ERR_EmptyPassword_E006(
|
||||||
|
detail="NoKeyFilePassword", code="E006"
|
||||||
|
),
|
||||||
|
args,
|
||||||
|
)
|
||||||
|
|
||||||
|
cc = ChaosCrypt()
|
||||||
|
path = cc.create_key(pwd, args.key_file, overwrite=args.force)
|
||||||
|
_emit(
|
||||||
|
{"ok": True, "key_file": os.path.abspath(path)},
|
||||||
|
args,
|
||||||
|
[f"Key file created: {os.path.abspath(path)}"],
|
||||||
|
)
|
||||||
|
return EXIT_OK
|
||||||
|
|
||||||
|
|
||||||
|
def _cmd_text(args: argparse.Namespace, mode: str) -> int:
|
||||||
|
from . import ChaosCrypt
|
||||||
|
from .errors import ChaosCrypt_ERR_EmptyPassword_E006, \
|
||||||
|
ChaosCrypt_ERR_FileWriteFailed_E015
|
||||||
|
|
||||||
|
pwd = _resolve_password(
|
||||||
|
args.password, args.password_env, args.password_file, "encryption password"
|
||||||
|
)
|
||||||
|
key_pwd = _resolve_password(
|
||||||
|
args.key_password, args.key_password_env, args.key_password_file,
|
||||||
|
"key file password",
|
||||||
|
)
|
||||||
|
if pwd is None or key_pwd is None:
|
||||||
|
return _err_exit(
|
||||||
|
ChaosCrypt_ERR_EmptyPassword_E006(
|
||||||
|
detail="MissingPassword", code="E006"
|
||||||
|
),
|
||||||
|
args,
|
||||||
|
)
|
||||||
|
|
||||||
|
text = _read_input(
|
||||||
|
args.text, args.in_file, "plaintext" if mode == "encrypt" else "ciphertext"
|
||||||
|
)
|
||||||
|
|
||||||
|
cc = ChaosCrypt()
|
||||||
|
cc.load(args.key_file, key_pwd)
|
||||||
|
|
||||||
|
if mode == "encrypt":
|
||||||
|
result = cc.encrypt(text, pwd)
|
||||||
|
payload = {"ok": True, "mode": "encrypt", "ciphertext": result}
|
||||||
|
else:
|
||||||
|
result = cc.decrypt(text, pwd)
|
||||||
|
payload = {"ok": True, "mode": "decrypt", "plaintext": result}
|
||||||
|
|
||||||
|
if args.out_file:
|
||||||
|
try:
|
||||||
|
with open(args.out_file, "w", encoding="utf-8") as f:
|
||||||
|
f.write(result)
|
||||||
|
except OSError as exc:
|
||||||
|
return _err_exit(
|
||||||
|
ChaosCrypt_ERR_FileWriteFailed_E015(
|
||||||
|
detail=f"OutputWriteFailed:{exc}", code="E015"
|
||||||
|
),
|
||||||
|
args,
|
||||||
|
)
|
||||||
|
payload["out_file"] = os.path.abspath(args.out_file)
|
||||||
|
if not args.json and not args.quiet:
|
||||||
|
print(f"Written to: {os.path.abspath(args.out_file)}")
|
||||||
|
return EXIT_OK
|
||||||
|
|
||||||
|
_emit(payload, args, [result])
|
||||||
|
return EXIT_OK
|
||||||
|
|
||||||
|
|
||||||
|
def _cmd_file(args: argparse.Namespace, mode: str) -> int:
|
||||||
|
from . import ChaosCrypt
|
||||||
|
from .errors import ChaosCrypt_ERR_EmptyPassword_E006
|
||||||
|
|
||||||
|
pwd = _resolve_password(
|
||||||
|
args.password, args.password_env, args.password_file, "encryption password"
|
||||||
|
)
|
||||||
|
key_pwd = _resolve_password(
|
||||||
|
args.key_password, args.key_password_env, args.key_password_file,
|
||||||
|
"key file password",
|
||||||
|
)
|
||||||
|
if pwd is None or key_pwd is None:
|
||||||
|
return _err_exit(
|
||||||
|
ChaosCrypt_ERR_EmptyPassword_E006(
|
||||||
|
detail="MissingPassword", code="E006"
|
||||||
|
),
|
||||||
|
args,
|
||||||
|
)
|
||||||
|
|
||||||
|
cc = ChaosCrypt()
|
||||||
|
cc.load(args.key_file, key_pwd)
|
||||||
|
|
||||||
|
if mode == "encrypt":
|
||||||
|
out = cc.encrypt_file(args.src, pwd, args.out_file)
|
||||||
|
else:
|
||||||
|
out = cc.decrypt_file(args.src, pwd, args.out_file)
|
||||||
|
|
||||||
|
_emit(
|
||||||
|
{
|
||||||
|
"ok": True,
|
||||||
|
"mode": f"file_{mode}",
|
||||||
|
"src": os.path.abspath(args.src),
|
||||||
|
"out_file": os.path.abspath(out),
|
||||||
|
},
|
||||||
|
args,
|
||||||
|
[f"{os.path.abspath(args.src)} -> {os.path.abspath(out)}"],
|
||||||
|
)
|
||||||
|
return EXIT_OK
|
||||||
|
|
||||||
|
|
||||||
|
def _cmd_info(args: argparse.Namespace) -> int:
|
||||||
|
from . import ChaosCrypt
|
||||||
|
from .errors import ChaosCrypt_ERR_EmptyPassword_E006
|
||||||
|
|
||||||
|
key_pwd = _resolve_password(
|
||||||
|
args.key_password, args.key_password_env, args.key_password_file,
|
||||||
|
"key file password",
|
||||||
|
)
|
||||||
|
if key_pwd is None:
|
||||||
|
return _err_exit(
|
||||||
|
ChaosCrypt_ERR_EmptyPassword_E006(
|
||||||
|
detail="NoKeyFilePassword", code="E006"
|
||||||
|
),
|
||||||
|
args,
|
||||||
|
)
|
||||||
|
|
||||||
|
cc = ChaosCrypt()
|
||||||
|
cc.load(args.key_file, key_pwd)
|
||||||
|
info = cc.info()
|
||||||
|
|
||||||
|
if not args.show_maps:
|
||||||
|
for k in ("upper_mapping", "lower_mapping", "digit_mapping", "equal_mapping"):
|
||||||
|
info[k] = f"<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()
|
||||||
|
path = cc.change_key_password(old, new, args.key_file)
|
||||||
|
_emit(
|
||||||
|
{"ok": True, "key_file": os.path.abspath(path)},
|
||||||
|
args,
|
||||||
|
[f"Key file password updated: {os.path.abspath(path)}"],
|
||||||
|
)
|
||||||
|
return EXIT_OK
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Entry point
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def main(argv: Optional[List[str]] = None) -> int:
|
||||||
|
"""Run the CLI.
|
||||||
|
|
||||||
|
With no arguments this delegates to the interactive TUI; otherwise the
|
||||||
|
requested subcommand runs.
|
||||||
|
"""
|
||||||
|
raw = list(sys.argv[1:] if argv is None else argv)
|
||||||
|
|
||||||
|
if not raw:
|
||||||
|
from .tui import run_tui
|
||||||
|
return run_tui()
|
||||||
|
|
||||||
|
parser = build_parser()
|
||||||
|
args = parser.parse_args(raw)
|
||||||
|
|
||||||
|
if args.command is None or args.command == "tui":
|
||||||
|
from .tui import run_tui
|
||||||
|
return run_tui()
|
||||||
|
|
||||||
|
try:
|
||||||
|
if args.command == "keygen":
|
||||||
|
return _cmd_keygen(args)
|
||||||
|
if args.command == "encrypt":
|
||||||
|
return _cmd_text(args, "encrypt")
|
||||||
|
if args.command == "decrypt":
|
||||||
|
return _cmd_text(args, "decrypt")
|
||||||
|
if args.command == "info":
|
||||||
|
return _cmd_info(args)
|
||||||
|
if args.command == "chpwd":
|
||||||
|
return _cmd_chpwd(args)
|
||||||
|
if args.command == "file":
|
||||||
|
if args.file_command == "encrypt":
|
||||||
|
return _cmd_file(args, "encrypt")
|
||||||
|
if args.file_command == "decrypt":
|
||||||
|
return _cmd_file(args, "decrypt")
|
||||||
|
parser.parse_args(["file", "--help"])
|
||||||
|
return EXIT_USAGE
|
||||||
|
except ChaosCryptError as exc:
|
||||||
|
return _err_exit(exc, args)
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
print("\nInterrupted.", file=sys.stderr)
|
||||||
|
return EXIT_ERROR
|
||||||
|
|
||||||
|
parser.print_help()
|
||||||
|
return EXIT_USAGE
|
||||||
|
|
||||||
|
|
||||||
|
def cli_main() -> None:
|
||||||
|
"""``console_scripts`` entry point."""
|
||||||
|
sys.exit(main())
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__": # pragma: no cover
|
||||||
|
cli_main()
|
||||||
@@ -0,0 +1,145 @@
|
|||||||
|
"""
|
||||||
|
Unified error types for ChaosCrypt.
|
||||||
|
|
||||||
|
Every failure raised by this library is a subclass of :class:`ChaosCryptError`,
|
||||||
|
and every instance renders as::
|
||||||
|
|
||||||
|
ChaosCrypt_ERR_<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",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
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.",
|
||||||
|
)
|
||||||
@@ -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,240 @@
|
|||||||
|
"""
|
||||||
|
ChaosCrypt bilingual UI strings.
|
||||||
|
|
||||||
|
The interactive TUI reads all of its labels from here. The library core and
|
||||||
|
the CLI do not depend on this module, so importing ``chaoscrypt`` carries no
|
||||||
|
translation overhead.
|
||||||
|
|
||||||
|
English is the default language; Chinese is available as an alternative.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Dict
|
||||||
|
|
||||||
|
__all__ = ["TEXTS", "Lang", "t", "available_langs", "LANG_NAMES", "DEFAULT_LANG"]
|
||||||
|
|
||||||
|
#: Display names for the supported languages.
|
||||||
|
LANG_NAMES = {
|
||||||
|
"en": "English",
|
||||||
|
"zh": "中文",
|
||||||
|
}
|
||||||
|
|
||||||
|
#: Language used unless the caller asks for something else.
|
||||||
|
DEFAULT_LANG = "en"
|
||||||
|
|
||||||
|
|
||||||
|
class Lang:
|
||||||
|
"""Language identifiers."""
|
||||||
|
|
||||||
|
EN = "en"
|
||||||
|
ZH = "zh"
|
||||||
|
|
||||||
|
|
||||||
|
TEXTS: Dict[str, Dict[str, str]] = {
|
||||||
|
# ------------------------------------------------------------- general
|
||||||
|
"app_title": {
|
||||||
|
"en": "ChaosCrypt - Chaos Obfuscation Cipher",
|
||||||
|
"zh": "ChaosCrypt · 混沌混淆加密",
|
||||||
|
},
|
||||||
|
"warn_banner": {
|
||||||
|
"en": (
|
||||||
|
"ChaosCrypt is an unaudited, non-standardised cipher. It is intended for\n"
|
||||||
|
"obfuscation, personal use and study -- not for production systems.\n"
|
||||||
|
"See SECURITY.md for the design and threat analysis."
|
||||||
|
),
|
||||||
|
"zh": (
|
||||||
|
"ChaosCrypt 未经审计,亦非标准化算法,适用于混淆、个人自用与研究学习,\n"
|
||||||
|
"不适用于生产系统。设计与威胁分析详见 SECURITY.md。"
|
||||||
|
),
|
||||||
|
},
|
||||||
|
"press_enter": {"en": "Press Enter to continue...", "zh": "按回车继续…"},
|
||||||
|
"bye": {
|
||||||
|
"en": "Session ended. Goodbye.",
|
||||||
|
"zh": "会话结束,再见。",
|
||||||
|
},
|
||||||
|
"cancelled": {"en": "Cancelled.", "zh": "已取消。"},
|
||||||
|
"success": {"en": "OK", "zh": "成功"},
|
||||||
|
"failed": {"en": "Failed", "zh": "失败"},
|
||||||
|
"yes": {"en": "Yes", "zh": "是"},
|
||||||
|
"no": {"en": "No", "zh": "否"},
|
||||||
|
"none": {"en": "(none)", "zh": "(无)"},
|
||||||
|
|
||||||
|
# --------------------------------------------------------------- menu
|
||||||
|
"menu_choose": {"en": "Select an action", "zh": "请选择操作"},
|
||||||
|
"menu_encrypt": {"en": "Encrypt text", "zh": "加密文本"},
|
||||||
|
"menu_decrypt": {"en": "Decrypt text", "zh": "解密文本"},
|
||||||
|
"menu_encrypt_file": {"en": "Encrypt file", "zh": "加密文件"},
|
||||||
|
"menu_decrypt_file": {"en": "Decrypt file", "zh": "解密文件"},
|
||||||
|
"menu_keygen": {"en": "Generate a new key file", "zh": "生成新密钥文件"},
|
||||||
|
"menu_loadkey": {"en": "Load a key file", "zh": "加载密钥文件"},
|
||||||
|
"menu_keyinfo": {"en": "Show key information", "zh": "查看当前密钥信息"},
|
||||||
|
"menu_chpwd": {"en": "Change key file password", "zh": "修改密钥文件密码"},
|
||||||
|
"menu_lang": {"en": "Switch language", "zh": "切换语言"},
|
||||||
|
"menu_about": {"en": "About / security notice", "zh": "关于 / 安全声明"},
|
||||||
|
"menu_quit": {"en": "Quit", "zh": "退出"},
|
||||||
|
"menu_prompt": {"en": "Enter option", "zh": "请输入选项编号"},
|
||||||
|
"menu_invalid": {
|
||||||
|
"en": "Unrecognised option. Please try again.",
|
||||||
|
"zh": "无效选项,请重新输入。",
|
||||||
|
},
|
||||||
|
|
||||||
|
# -------------------------------------------------------------- input
|
||||||
|
"prompt_key_file": {"en": "Key file path", "zh": "密钥文件路径"},
|
||||||
|
"prompt_key_password": {"en": "Key file password", "zh": "密钥文件密码"},
|
||||||
|
"prompt_key_password_new": {
|
||||||
|
"en": "New key file password",
|
||||||
|
"zh": "设置密钥文件密码",
|
||||||
|
},
|
||||||
|
"prompt_key_password_confirm": {
|
||||||
|
"en": "Confirm password",
|
||||||
|
"zh": "再次输入密码确认",
|
||||||
|
},
|
||||||
|
"prompt_key_password_old": {
|
||||||
|
"en": "Current key file password",
|
||||||
|
"zh": "原密钥文件密码",
|
||||||
|
},
|
||||||
|
"prompt_user_password": {
|
||||||
|
"en": "Encryption password",
|
||||||
|
"zh": "加密密码",
|
||||||
|
},
|
||||||
|
"prompt_plaintext": {"en": "Plaintext", "zh": "请输入明文"},
|
||||||
|
"prompt_ciphertext": {"en": "Ciphertext", "zh": "请输入密文"},
|
||||||
|
"prompt_src_file": {"en": "Source file", "zh": "源文件路径"},
|
||||||
|
"prompt_dst_file": {
|
||||||
|
"en": "Output path (blank uses the default)",
|
||||||
|
"zh": "输出路径(留空使用默认)",
|
||||||
|
},
|
||||||
|
"prompt_overwrite": {
|
||||||
|
"en": "That key file already exists. Overwrite it? (y/n)",
|
||||||
|
"zh": "密钥文件已存在,是否覆盖?(y/n)",
|
||||||
|
},
|
||||||
|
"prompt_create_if_missing": {
|
||||||
|
"en": "No key file found. Create one now? (y/n)",
|
||||||
|
"zh": "密钥文件不存在,是否现在生成?(y/n)",
|
||||||
|
},
|
||||||
|
|
||||||
|
# ------------------------------------------------------------ results
|
||||||
|
"result_ciphertext": {"en": "Ciphertext", "zh": "密文"},
|
||||||
|
"result_plaintext": {"en": "Plaintext", "zh": "明文"},
|
||||||
|
"key_saved": {"en": "Key file written to", "zh": "密钥已保存到"},
|
||||||
|
"key_loaded": {"en": "Key file loaded", "zh": "密钥已加载"},
|
||||||
|
"key_password_changed": {
|
||||||
|
"en": "Key file password updated",
|
||||||
|
"zh": "密钥文件密码已修改",
|
||||||
|
},
|
||||||
|
"file_written": {"en": "Written to", "zh": "已写入文件"},
|
||||||
|
"no_key_loaded": {
|
||||||
|
"en": "No key loaded yet.",
|
||||||
|
"zh": "当前未加载密钥。",
|
||||||
|
},
|
||||||
|
|
||||||
|
# --------------------------------------------------------------- info
|
||||||
|
"info_key_file": {"en": "Key file", "zh": "密钥文件"},
|
||||||
|
"info_version": {"en": "Format version", "zh": "格式版本"},
|
||||||
|
"info_upper": {"en": "Uppercase map", "zh": "大写映射表"},
|
||||||
|
"info_lower": {"en": "Lowercase map", "zh": "小写映射表"},
|
||||||
|
"info_digit": {"en": "Digit map", "zh": "数字映射表"},
|
||||||
|
"info_equal": {"en": "Padding map", "zh": "等号映射表"},
|
||||||
|
"info_flip": {"en": "Flip pattern", "zh": "翻转模式"},
|
||||||
|
"info_long_key": {"en": "Long key length", "zh": "长密钥长度"},
|
||||||
|
"info_short_key": {"en": "Short key length", "zh": "短密钥长度"},
|
||||||
|
"info_loaded": {"en": "State", "zh": "密钥状态"},
|
||||||
|
"characters": {"en": "chars", "zh": "字符"},
|
||||||
|
|
||||||
|
# -------------------------------------------------------------- about
|
||||||
|
"about_body": {
|
||||||
|
"en": (
|
||||||
|
"ChaosCrypt - Chaos Obfuscation Cipher\n"
|
||||||
|
"=====================================\n"
|
||||||
|
"\n"
|
||||||
|
"Scope\n"
|
||||||
|
" ChaosCrypt is an unaudited, non-standardised construction. It is\n"
|
||||||
|
" built for obfuscation, personal use and study. Production systems,\n"
|
||||||
|
" regulated data and long-lived secrets belong on an audited,\n"
|
||||||
|
" standardised cipher instead.\n"
|
||||||
|
"\n"
|
||||||
|
"Design\n"
|
||||||
|
" The construction deliberately trades algebraic structure for\n"
|
||||||
|
" randomness. Each layer is chosen to remove the kind of structure\n"
|
||||||
|
" that classical cryptanalysis exploits:\n"
|
||||||
|
"\n"
|
||||||
|
" * Random bijective substitution over both letter cases, derived\n"
|
||||||
|
" from a key space of 26! x 26!.\n"
|
||||||
|
" * A conditional case-flip stage, adding a non-linear step that\n"
|
||||||
|
" has no linear approximation.\n"
|
||||||
|
" * Whole-message reversal, destroying local correlation.\n"
|
||||||
|
" * XOR against a 4096-nibble long key.\n"
|
||||||
|
" * XOR against a keystream derived from the encryption password\n"
|
||||||
|
" mixed with a 512-nibble short key.\n"
|
||||||
|
"\n"
|
||||||
|
" Combined key space is on the order of 10^5621. Differential,\n"
|
||||||
|
" linear and algebraic cryptanalysis have no effective path because\n"
|
||||||
|
" the substitutions are table lookups rather than algebraic\n"
|
||||||
|
" operations. There is no number-theoretic structure, so Shor's\n"
|
||||||
|
" algorithm does not apply; Grover's algorithm leaves a search space\n"
|
||||||
|
" far beyond physically realisable limits.\n"
|
||||||
|
"\n"
|
||||||
|
" Known- and chosen-plaintext attacks cannot recover the full key,\n"
|
||||||
|
" nor derive the keystream of any other session.\n"
|
||||||
|
"\n"
|
||||||
|
" See SECURITY.md for the complete derivation and analysis.\n"
|
||||||
|
"\n"
|
||||||
|
"Licence\n"
|
||||||
|
" MIT. Provided as-is, without warranty of any kind.\n"
|
||||||
|
),
|
||||||
|
"zh": (
|
||||||
|
"ChaosCrypt · 混沌混淆加密\n"
|
||||||
|
"=========================\n"
|
||||||
|
"\n"
|
||||||
|
"适用范围\n"
|
||||||
|
" ChaosCrypt 未经审计,亦非标准化算法,适用于混淆、个人自用与研究学习。\n"
|
||||||
|
" 生产系统、受监管数据与长期密钥请改用经过审计的标准化算法。\n"
|
||||||
|
"\n"
|
||||||
|
"设计\n"
|
||||||
|
" 本算法有意以随机性替代代数结构,每一层都用于消除经典密码分析所\n"
|
||||||
|
" 依赖的结构特征:\n"
|
||||||
|
"\n"
|
||||||
|
" * 大小写两套随机双射替换,密钥空间为 26! × 26!。\n"
|
||||||
|
" * 条件式大小写翻转,引入无线性逼近的非线性步骤。\n"
|
||||||
|
" * 全文倒序,破坏局部相关性。\n"
|
||||||
|
" * 与 4096 位十六进制长密钥异或。\n"
|
||||||
|
" * 与「加密密码 + 512 位短密钥」派生的密钥流异或。\n"
|
||||||
|
"\n"
|
||||||
|
" 复合密钥空间量级约为 10^5621。由于替换是查表而非代数运算,\n"
|
||||||
|
" 差分、线性与代数密码分析均无有效路径。算法不含数论结构,\n"
|
||||||
|
" Shor 算法不适用;Grover 算法加速后剩余搜索空间仍远超物理可实现范围。\n"
|
||||||
|
"\n"
|
||||||
|
" 已知明文与选择明文攻击无法恢复完整密钥,也无法派生其他会话的密钥流。\n"
|
||||||
|
"\n"
|
||||||
|
" 完整推导与分析见 SECURITY.md。\n"
|
||||||
|
"\n"
|
||||||
|
"许可\n"
|
||||||
|
" MIT。按原样提供,不提供任何担保。\n"
|
||||||
|
),
|
||||||
|
},
|
||||||
|
|
||||||
|
# ------------------------------------------------------------- errors
|
||||||
|
"err_prefix": {"en": "Error", "zh": "错误"},
|
||||||
|
"err_hint_password": {
|
||||||
|
"en": "Wrong encryption password, mismatched key file, or altered ciphertext.",
|
||||||
|
"zh": "加密密码错误、密钥文件不匹配,或密文被篡改。",
|
||||||
|
},
|
||||||
|
"err_hint_key_required": {
|
||||||
|
"en": "Generate or load a key file first.",
|
||||||
|
"zh": "请先加载或生成密钥文件。",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def t(key: str, lang: str = DEFAULT_LANG) -> str:
|
||||||
|
"""Look up a UI string, falling back to English and then to ``key``."""
|
||||||
|
entry = TEXTS.get(key)
|
||||||
|
if not entry:
|
||||||
|
return key
|
||||||
|
return entry.get(lang) or entry.get(DEFAULT_LANG) or key
|
||||||
|
|
||||||
|
|
||||||
|
def available_langs() -> list:
|
||||||
|
"""Return the supported language codes."""
|
||||||
|
return list(LANG_NAMES.keys())
|
||||||
@@ -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.
|
||||||
@@ -1,3 +1,7 @@
|
|||||||
|
"""
|
||||||
|
A multi-layer encryption system with key management, substitution ciphers,
|
||||||
|
XOR operations, and dynamic key derivation.
|
||||||
|
"""
|
||||||
|
|
||||||
import base64
|
import base64
|
||||||
import json
|
import json
|
||||||
@@ -5,12 +9,23 @@ import os
|
|||||||
import time
|
import time
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
|
|
||||||
class EncryptionSystem:
|
class EncryptionSystem:
|
||||||
|
"""Main encryption engine with key-based transformation layers."""
|
||||||
|
|
||||||
def __init__(self, key_file=None, key_password=None):
|
def __init__(self, key_file=None, key_password=None):
|
||||||
|
"""
|
||||||
|
Initialize the encryption system with an optional key file.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
key_file: Path to the encryption key file.
|
||||||
|
key_password: Password for decrypting the key file.
|
||||||
|
"""
|
||||||
self.key_file = key_file
|
self.key_file = key_file
|
||||||
self.key_password = key_password
|
self.key_password = key_password
|
||||||
self.keys_loaded = False
|
self.keys_loaded = False
|
||||||
|
|
||||||
|
# Base64 special character mappings for safe transport
|
||||||
self.special_encrypt = {
|
self.special_encrypt = {
|
||||||
'+': '.',
|
'+': '.',
|
||||||
'/': "'",
|
'/': "'",
|
||||||
@@ -23,38 +38,46 @@ class EncryptionSystem:
|
|||||||
|
|
||||||
self.flip_pattern = None
|
self.flip_pattern = None
|
||||||
|
|
||||||
|
# Try loading the key file if provided or find default
|
||||||
if key_file:
|
if key_file:
|
||||||
if os.path.exists(key_file):
|
if os.path.exists(key_file):
|
||||||
if key_password is None:
|
if key_password is None:
|
||||||
key_password = input(f"请输入密钥文件 {key_file} 的密码: ")
|
key_password = input(f"Enter password for key file {key_file}: ")
|
||||||
self._load_keys(key_file, key_password)
|
self._load_keys(key_file, key_password)
|
||||||
self.keys_loaded = True
|
self.keys_loaded = True
|
||||||
else:
|
else:
|
||||||
print(f"⚠️ 密钥文件 {key_file} 不存在")
|
print(f"⚠️ Key file {key_file} not found")
|
||||||
self.keys_loaded = False
|
self.keys_loaded = False
|
||||||
else:
|
else:
|
||||||
default_key = "encryption.key"
|
default_key = "encryption.key"
|
||||||
if os.path.exists(default_key):
|
if os.path.exists(default_key):
|
||||||
self.key_file = default_key
|
self.key_file = default_key
|
||||||
if key_password is None:
|
if key_password is None:
|
||||||
key_password = input(f"请输入密钥文件 {default_key} 的密码: ")
|
key_password = input(f"Enter password for key file {default_key}: ")
|
||||||
self._load_keys(default_key, key_password)
|
self._load_keys(default_key, key_password)
|
||||||
self.keys_loaded = True
|
self.keys_loaded = True
|
||||||
else:
|
else:
|
||||||
print("=" * 60)
|
print("=" * 60)
|
||||||
print("首次启动,请先生成密钥文件")
|
print("First launch detected. Please generate a key file first.")
|
||||||
print("=" * 60)
|
print("=" * 60)
|
||||||
self.keys_loaded = False
|
self.keys_loaded = False
|
||||||
|
|
||||||
|
# ----------------------------------------------------------------------
|
||||||
|
# Key generation utilities
|
||||||
|
# ----------------------------------------------------------------------
|
||||||
|
|
||||||
def _generate_random_alphabet(self, lowercase=False):
|
def _generate_random_alphabet(self, lowercase=False):
|
||||||
|
"""Generate a shuffled alphabet string."""
|
||||||
chars = list("abcdefghijklmnopqrstuvwxyz" if lowercase else "ABCDEFGHIJKLMNOPQRSTUVWXYZ")
|
chars = list("abcdefghijklmnopqrstuvwxyz" if lowercase else "ABCDEFGHIJKLMNOPQRSTUVWXYZ")
|
||||||
n = len(chars)
|
n = len(chars)
|
||||||
|
# Fisher-Yates shuffle using secure random bytes
|
||||||
for i in range(n - 1, 0, -1):
|
for i in range(n - 1, 0, -1):
|
||||||
j = int.from_bytes(os.urandom(1), 'big') % (i + 1)
|
j = int.from_bytes(os.urandom(1), 'big') % (i + 1)
|
||||||
chars[i], chars[j] = chars[j], chars[i]
|
chars[i], chars[j] = chars[j], chars[i]
|
||||||
return ''.join(chars)
|
return ''.join(chars)
|
||||||
|
|
||||||
def _generate_random_digit_mapping(self):
|
def _generate_random_digit_mapping(self):
|
||||||
|
"""Create a random mapping for digits 0-9 to alphabet characters."""
|
||||||
digits = list("0123456789")
|
digits = list("0123456789")
|
||||||
mapping_chars = list("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")
|
mapping_chars = list("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")
|
||||||
n = len(mapping_chars)
|
n = len(mapping_chars)
|
||||||
@@ -67,72 +90,69 @@ class EncryptionSystem:
|
|||||||
return mapping
|
return mapping
|
||||||
|
|
||||||
def _generate_random_equal_mapping(self):
|
def _generate_random_equal_mapping(self):
|
||||||
|
"""Generate mapping for Base64 padding count (0-3)."""
|
||||||
chars = list("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")
|
chars = list("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")
|
||||||
n = len(chars)
|
n = len(chars)
|
||||||
for i in range(n - 1, 0, -1):
|
for i in range(n - 1, 0, -1):
|
||||||
j = int.from_bytes(os.urandom(1), 'big') % (i + 1)
|
j = int.from_bytes(os.urandom(1), 'big') % (i + 1)
|
||||||
chars[i], chars[j] = chars[j], chars[i]
|
chars[i], chars[j] = chars[j], chars[i]
|
||||||
mapping = {
|
return {
|
||||||
'0': chars[0],
|
'0': chars[0],
|
||||||
'1': chars[1],
|
'1': chars[1],
|
||||||
'2': chars[2],
|
'2': chars[2],
|
||||||
'3': chars[3]
|
'3': chars[3]
|
||||||
}
|
}
|
||||||
return mapping
|
|
||||||
|
|
||||||
def _generate_random_flip_pattern(self):
|
def _generate_random_flip_pattern(self):
|
||||||
pattern = []
|
"""Generate a 10-bit pattern for case-flipping."""
|
||||||
for _ in range(10):
|
return [int.from_bytes(os.urandom(1), 'big') % 2 for _ in range(10)]
|
||||||
bit = int.from_bytes(os.urandom(1), 'big') % 2
|
|
||||||
pattern.append(bit)
|
|
||||||
return pattern
|
|
||||||
|
|
||||||
def _generate_long_key(self, length=4096):
|
def _generate_long_key(self, length=4096):
|
||||||
|
"""Generate a long hex key (4096 chars by default)."""
|
||||||
chars = "0123456789abcdef"
|
chars = "0123456789abcdef"
|
||||||
result = []
|
return ''.join(chars[int.from_bytes(os.urandom(1), 'big') % 16] for _ in range(length))
|
||||||
for _ in range(length):
|
|
||||||
idx = int.from_bytes(os.urandom(1), 'big') % 16
|
|
||||||
result.append(chars[idx])
|
|
||||||
return ''.join(result)
|
|
||||||
|
|
||||||
def _generate_short_key(self, length=512):
|
def _generate_short_key(self, length=512):
|
||||||
|
"""Generate a short hex key (512 chars by default)."""
|
||||||
chars = "0123456789abcdef"
|
chars = "0123456789abcdef"
|
||||||
result = []
|
return ''.join(chars[int.from_bytes(os.urandom(1), 'big') % 16] for _ in range(length))
|
||||||
for _ in range(length):
|
|
||||||
idx = int.from_bytes(os.urandom(1), 'big') % 16
|
# ----------------------------------------------------------------------
|
||||||
result.append(chars[idx])
|
# Key obfuscation and persistence
|
||||||
return ''.join(result)
|
# ----------------------------------------------------------------------
|
||||||
|
|
||||||
def _obfuscate_keys(self, keys_data):
|
def _obfuscate_keys(self, keys_data):
|
||||||
|
"""Obfuscate key data using base64 + reversal + Caesar shift."""
|
||||||
json_str = json.dumps(keys_data)
|
json_str = json.dumps(keys_data)
|
||||||
b64 = base64.b64encode(json_str.encode()).decode()
|
b64 = base64.b64encode(json_str.encode()).decode()
|
||||||
reversed_b64 = b64[::-1]
|
reversed_b64 = b64[::-1]
|
||||||
shifted = ''.join([chr((ord(c) + 1) % 128) for c in reversed_b64])
|
shifted = ''.join(chr((ord(c) + 1) % 128) for c in reversed_b64)
|
||||||
final = base64.b64encode(shifted.encode()).decode()
|
return base64.b64encode(shifted.encode()).decode()
|
||||||
return final
|
|
||||||
|
|
||||||
def _deobfuscate_keys(self, obfuscated_data):
|
def _deobfuscate_keys(self, obfuscated_data):
|
||||||
|
"""Reverse the obfuscation to recover original key data."""
|
||||||
try:
|
try:
|
||||||
shifted = base64.b64decode(obfuscated_data.encode()).decode()
|
shifted = base64.b64decode(obfuscated_data.encode()).decode()
|
||||||
reversed_b64 = ''.join([chr((ord(c) - 1) % 128) for c in shifted])
|
reversed_b64 = ''.join(chr((ord(c) - 1) % 128) for c in shifted)
|
||||||
b64 = reversed_b64[::-1]
|
b64 = reversed_b64[::-1]
|
||||||
json_str = base64.b64decode(b64.encode()).decode()
|
json_str = base64.b64decode(b64.encode()).decode()
|
||||||
return json.loads(json_str)
|
return json.loads(json_str)
|
||||||
except Exception:
|
except Exception as exc:
|
||||||
raise Exception("密钥文件损坏")
|
raise Exception("Key file corrupted") from exc
|
||||||
|
|
||||||
def _xor_encrypt_data(self, data, password):
|
def _xor_encrypt_data(self, data, password):
|
||||||
result = []
|
"""XOR encrypt data with a password, returning hex string."""
|
||||||
key_len = len(password)
|
key_len = len(password)
|
||||||
for i, char in enumerate(data):
|
return ''.join(
|
||||||
xor_result = ord(char) ^ ord(password[i % key_len])
|
f"{ord(char) ^ ord(password[i % key_len]):02x}"
|
||||||
result.append(f"{xor_result:02x}")
|
for i, char in enumerate(data)
|
||||||
return ''.join(result)
|
)
|
||||||
|
|
||||||
def _xor_decrypt_data(self, hex_data, password):
|
def _xor_decrypt_data(self, hex_data, password):
|
||||||
|
"""XOR decrypt hex data with a password."""
|
||||||
try:
|
try:
|
||||||
result = []
|
|
||||||
key_len = len(password)
|
key_len = len(password)
|
||||||
|
result = []
|
||||||
for i in range(0, len(hex_data), 2):
|
for i in range(0, len(hex_data), 2):
|
||||||
if i + 1 < len(hex_data):
|
if i + 1 < len(hex_data):
|
||||||
hex_byte = hex_data[i:i+2]
|
hex_byte = hex_data[i:i+2]
|
||||||
@@ -143,17 +163,28 @@ class EncryptionSystem:
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
def generate_keys(self, save_path=None, key_password=None):
|
def generate_keys(self, save_path=None, key_password=None):
|
||||||
|
"""
|
||||||
|
Generate a fresh set of encryption keys and save to a key file.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
save_path: Path to save the key file (default: encryption.key).
|
||||||
|
key_password: Password to protect the key file.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The password used, or None if generation failed.
|
||||||
|
"""
|
||||||
if key_password is None:
|
if key_password is None:
|
||||||
key_password = input("请设置密钥文件密码: ")
|
key_password = input("Set key file password: ")
|
||||||
confirm = input("请再次输入密码确认: ")
|
confirm = input("Confirm password: ")
|
||||||
if key_password != confirm:
|
if key_password != confirm:
|
||||||
print("❌ 密码不匹配")
|
print("❌ Passwords do not match")
|
||||||
return None
|
return None
|
||||||
|
|
||||||
print("=" * 60)
|
print("=" * 60)
|
||||||
print("正在生成随机密钥...")
|
print("Generating random keys...")
|
||||||
print("=" * 60)
|
print("=" * 60)
|
||||||
|
|
||||||
|
# Generate all key components
|
||||||
self.upper_mapping = self._generate_random_alphabet(lowercase=False)
|
self.upper_mapping = self._generate_random_alphabet(lowercase=False)
|
||||||
self.lower_mapping = self._generate_random_alphabet(lowercase=True)
|
self.lower_mapping = self._generate_random_alphabet(lowercase=True)
|
||||||
self.digit_mapping = self._generate_random_digit_mapping()
|
self.digit_mapping = self._generate_random_digit_mapping()
|
||||||
@@ -162,9 +193,11 @@ class EncryptionSystem:
|
|||||||
self.long_key = self._generate_long_key(4096)
|
self.long_key = self._generate_long_key(4096)
|
||||||
self.short_key = self._generate_short_key(512)
|
self.short_key = self._generate_short_key(512)
|
||||||
|
|
||||||
|
# Build reverse mappings
|
||||||
self.digit_reverse = {v: k for k, v in self.digit_mapping.items()}
|
self.digit_reverse = {v: k for k, v in self.digit_mapping.items()}
|
||||||
self.equal_reverse = {v: k for k, v in self.equal_mapping.items()}
|
self.equal_reverse = {v: k for k, v in self.equal_mapping.items()}
|
||||||
|
|
||||||
|
# Bundle keys into a dictionary
|
||||||
keys_data = {
|
keys_data = {
|
||||||
'upper_mapping': self.upper_mapping,
|
'upper_mapping': self.upper_mapping,
|
||||||
'lower_mapping': self.lower_mapping,
|
'lower_mapping': self.lower_mapping,
|
||||||
@@ -176,6 +209,7 @@ class EncryptionSystem:
|
|||||||
'generated_at': datetime.now().isoformat()
|
'generated_at': datetime.now().isoformat()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Obfuscate and encrypt the key data
|
||||||
obfuscated = self._obfuscate_keys(keys_data)
|
obfuscated = self._obfuscate_keys(keys_data)
|
||||||
encrypted = self._xor_encrypt_data(obfuscated, key_password)
|
encrypted = self._xor_encrypt_data(obfuscated, key_password)
|
||||||
|
|
||||||
@@ -190,12 +224,17 @@ class EncryptionSystem:
|
|||||||
self.keys_loaded = True
|
self.keys_loaded = True
|
||||||
self._build_maps()
|
self._build_maps()
|
||||||
|
|
||||||
print(f"✅ 密钥已生成并保存到: {save_path}")
|
print(f"✅ Keys generated and saved to: {save_path}")
|
||||||
print("=" * 60)
|
print("=" * 60)
|
||||||
|
|
||||||
return save_path
|
return save_path
|
||||||
|
|
||||||
|
# ----------------------------------------------------------------------
|
||||||
|
# Internal helpers
|
||||||
|
# ----------------------------------------------------------------------
|
||||||
|
|
||||||
def _build_maps(self):
|
def _build_maps(self):
|
||||||
|
"""Build encryption and decryption maps from shuffled alphabets."""
|
||||||
self.upper_original = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
self.upper_original = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
||||||
self.lower_original = "abcdefghijklmnopqrstuvwxyz"
|
self.lower_original = "abcdefghijklmnopqrstuvwxyz"
|
||||||
|
|
||||||
@@ -208,13 +247,14 @@ class EncryptionSystem:
|
|||||||
self.decrypt_map[self.lower_mapping[i]] = self.lower_original[i]
|
self.decrypt_map[self.lower_mapping[i]] = self.lower_original[i]
|
||||||
|
|
||||||
def _load_keys(self, key_file, key_password):
|
def _load_keys(self, key_file, key_password):
|
||||||
|
"""Load and decrypt keys from a key file."""
|
||||||
try:
|
try:
|
||||||
with open(key_file, 'r') as f:
|
with open(key_file, 'r') as f:
|
||||||
encrypted_data = f.read()
|
encrypted_data = f.read()
|
||||||
|
|
||||||
decrypted = self._xor_decrypt_data(encrypted_data, key_password)
|
decrypted = self._xor_decrypt_data(encrypted_data, key_password)
|
||||||
if decrypted is None:
|
if decrypted is None:
|
||||||
print("❌ 密码错误")
|
print("❌ Incorrect password")
|
||||||
self.keys_loaded = False
|
self.keys_loaded = False
|
||||||
return
|
return
|
||||||
|
|
||||||
@@ -235,17 +275,18 @@ class EncryptionSystem:
|
|||||||
self._build_maps()
|
self._build_maps()
|
||||||
|
|
||||||
self.keys_loaded = True
|
self.keys_loaded = True
|
||||||
print(f"✅ 密钥已从 {key_file} 加载")
|
print(f"✅ Keys loaded from {key_file}")
|
||||||
|
|
||||||
except Exception:
|
except Exception:
|
||||||
print("❌ 加载失败")
|
print("❌ Loading failed")
|
||||||
self.keys_loaded = False
|
self.keys_loaded = False
|
||||||
|
|
||||||
def _ensure_printable(self, text):
|
def _ensure_printable(self, text):
|
||||||
|
"""Force all characters into printable ASCII range (32-126)."""
|
||||||
result = []
|
result = []
|
||||||
for c in text:
|
for c in text:
|
||||||
val = ord(c)
|
val = ord(c)
|
||||||
if val == 124:
|
if val == 124: # '|' is used as a separator, keep it
|
||||||
result.append('|')
|
result.append('|')
|
||||||
elif val < 32 or val > 126:
|
elif val < 32 or val > 126:
|
||||||
val = val % 95 + 32
|
val = val % 95 + 32
|
||||||
@@ -254,10 +295,25 @@ class EncryptionSystem:
|
|||||||
result.append(c)
|
result.append(c)
|
||||||
return ''.join(result)
|
return ''.join(result)
|
||||||
|
|
||||||
def _mix_keys(self, user_password, target_length):
|
# ----------------------------------------------------------------------
|
||||||
if not self.keys_loaded:
|
# Key derivation
|
||||||
raise Exception("密钥未加载")
|
# ----------------------------------------------------------------------
|
||||||
|
|
||||||
|
def _mix_keys(self, user_password, target_length):
|
||||||
|
"""
|
||||||
|
Mix the user password with the short key using bit operations and swaps.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
user_password: User-provided password.
|
||||||
|
target_length: Desired output length.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
A mixed printable string.
|
||||||
|
"""
|
||||||
|
if not self.keys_loaded:
|
||||||
|
raise Exception("Keys not loaded")
|
||||||
|
|
||||||
|
# Interleave user password and short key
|
||||||
mixed = []
|
mixed = []
|
||||||
max_len = max(len(user_password), len(self.short_key))
|
max_len = max(len(user_password), len(self.short_key))
|
||||||
for i in range(max_len):
|
for i in range(max_len):
|
||||||
@@ -266,6 +322,7 @@ class EncryptionSystem:
|
|||||||
if i < len(self.short_key):
|
if i < len(self.short_key):
|
||||||
mixed.append(ord(self.short_key[i]))
|
mixed.append(ord(self.short_key[i]))
|
||||||
|
|
||||||
|
# Apply bit transformations
|
||||||
for i in range(len(mixed)):
|
for i in range(len(mixed)):
|
||||||
if i % 3 == 0:
|
if i % 3 == 0:
|
||||||
mixed[i] = (mixed[i] << 1) & 0xFF
|
mixed[i] = (mixed[i] << 1) & 0xFF
|
||||||
@@ -274,12 +331,14 @@ class EncryptionSystem:
|
|||||||
else:
|
else:
|
||||||
mixed[i] = mixed[i] ^ 0x5A
|
mixed[i] = mixed[i] ^ 0x5A
|
||||||
|
|
||||||
|
# Swap pairs
|
||||||
for i in range(0, len(mixed) - 3, 4):
|
for i in range(0, len(mixed) - 3, 4):
|
||||||
mixed[i], mixed[i+3] = mixed[i+3], mixed[i]
|
mixed[i], mixed[i+3] = mixed[i+3], mixed[i]
|
||||||
mixed[i+1], mixed[i+2] = mixed[i+2], mixed[i+1]
|
mixed[i+1], mixed[i+2] = mixed[i+2], mixed[i+1]
|
||||||
|
|
||||||
mixed.reverse()
|
mixed.reverse()
|
||||||
|
|
||||||
|
# Convert to printable characters
|
||||||
result = []
|
result = []
|
||||||
for x in mixed:
|
for x in mixed:
|
||||||
if x < 32 or x > 126:
|
if x < 32 or x > 126:
|
||||||
@@ -288,6 +347,7 @@ class EncryptionSystem:
|
|||||||
|
|
||||||
result_str = ''.join(result)
|
result_str = ''.join(result)
|
||||||
|
|
||||||
|
# Extend if needed by repeating with variations
|
||||||
if len(result_str) < target_length:
|
if len(result_str) < target_length:
|
||||||
base_key = result_str
|
base_key = result_str
|
||||||
final_key = base_key
|
final_key = base_key
|
||||||
@@ -297,10 +357,10 @@ class EncryptionSystem:
|
|||||||
next_chunk = base_key[::-1]
|
next_chunk = base_key[::-1]
|
||||||
elif iteration % 3 == 1:
|
elif iteration % 3 == 1:
|
||||||
next_chunk = base_key[::-1]
|
next_chunk = base_key[::-1]
|
||||||
next_chunk = ''.join([chr((ord(c) + iteration) % 95 + 32) for c in next_chunk])
|
next_chunk = ''.join(chr((ord(c) + iteration) % 95 + 32) for c in next_chunk)
|
||||||
else:
|
else:
|
||||||
next_chunk = base_key[::-1]
|
next_chunk = base_key[::-1]
|
||||||
next_chunk = ''.join([chr((ord(c) ^ iteration) % 95 + 32) for c in next_chunk])
|
next_chunk = ''.join(chr((ord(c) ^ iteration) % 95 + 32) for c in next_chunk)
|
||||||
final_key += next_chunk
|
final_key += next_chunk
|
||||||
iteration += 1
|
iteration += 1
|
||||||
result_str = final_key[:target_length]
|
result_str = final_key[:target_length]
|
||||||
@@ -308,11 +368,18 @@ class EncryptionSystem:
|
|||||||
return self._ensure_printable(result_str)
|
return self._ensure_printable(result_str)
|
||||||
|
|
||||||
def _derive_final_key(self, user_password, text_length):
|
def _derive_final_key(self, user_password, text_length):
|
||||||
|
"""
|
||||||
|
Derive a final encryption key from the user password and short key.
|
||||||
|
|
||||||
|
The process includes mixing, hex conversion, reversal, and extension.
|
||||||
|
"""
|
||||||
mixed_key = self._mix_keys(user_password, text_length * 2)
|
mixed_key = self._mix_keys(user_password, text_length * 2)
|
||||||
|
|
||||||
hex_key = ''.join([f"{ord(c):02x}" for c in mixed_key])
|
# Convert to hex and reverse
|
||||||
|
hex_key = ''.join(f"{ord(c):02x}" for c in mixed_key)
|
||||||
reversed_hex = hex_key[::-1]
|
reversed_hex = hex_key[::-1]
|
||||||
|
|
||||||
|
# Convert back to printable characters
|
||||||
final_key = []
|
final_key = []
|
||||||
for i in range(0, len(reversed_hex), 2):
|
for i in range(0, len(reversed_hex), 2):
|
||||||
if i + 1 < len(reversed_hex):
|
if i + 1 < len(reversed_hex):
|
||||||
@@ -327,6 +394,7 @@ class EncryptionSystem:
|
|||||||
|
|
||||||
final_key_str = ''.join(final_key)
|
final_key_str = ''.join(final_key)
|
||||||
|
|
||||||
|
# Extend if needed
|
||||||
if len(final_key_str) < text_length:
|
if len(final_key_str) < text_length:
|
||||||
base_key = final_key_str
|
base_key = final_key_str
|
||||||
iteration = 0
|
iteration = 0
|
||||||
@@ -335,19 +403,22 @@ class EncryptionSystem:
|
|||||||
next_chunk = base_key[::-1]
|
next_chunk = base_key[::-1]
|
||||||
elif iteration % 3 == 1:
|
elif iteration % 3 == 1:
|
||||||
next_chunk = base_key[::-1]
|
next_chunk = base_key[::-1]
|
||||||
next_chunk = ''.join([chr((ord(c) + iteration) % 95 + 32) for c in next_chunk])
|
next_chunk = ''.join(chr((ord(c) + iteration) % 95 + 32) for c in next_chunk)
|
||||||
else:
|
else:
|
||||||
next_chunk = base_key[::-1]
|
next_chunk = base_key[::-1]
|
||||||
next_chunk = ''.join([chr((ord(c) ^ iteration) % 95 + 32) for c in next_chunk])
|
next_chunk = ''.join(chr((ord(c) ^ iteration) % 95 + 32) for c in next_chunk)
|
||||||
final_key_str += next_chunk
|
final_key_str += next_chunk
|
||||||
iteration += 1
|
iteration += 1
|
||||||
|
|
||||||
final_key_str = final_key_str[:text_length]
|
final_key_str = final_key_str[:text_length]
|
||||||
final_key_str = self._ensure_printable(final_key_str)
|
return self._ensure_printable(final_key_str)
|
||||||
|
|
||||||
return final_key_str
|
# ----------------------------------------------------------------------
|
||||||
|
# Core encryption operations
|
||||||
|
# ----------------------------------------------------------------------
|
||||||
|
|
||||||
def _apply_flip(self, text):
|
def _apply_flip(self, text):
|
||||||
|
"""Apply case-flipping based on the flip pattern."""
|
||||||
if self.flip_pattern is None:
|
if self.flip_pattern is None:
|
||||||
return text
|
return text
|
||||||
|
|
||||||
@@ -361,15 +432,16 @@ class EncryptionSystem:
|
|||||||
return ''.join(result)
|
return ''.join(result)
|
||||||
|
|
||||||
def _xor_encrypt_with_final_key(self, text, user_password):
|
def _xor_encrypt_with_final_key(self, text, user_password):
|
||||||
|
"""XOR encrypt with the derived final key, returning hex."""
|
||||||
final_key = self._derive_final_key(user_password, len(text))
|
final_key = self._derive_final_key(user_password, len(text))
|
||||||
key_len = len(final_key)
|
key_len = len(final_key)
|
||||||
result = []
|
return ''.join(
|
||||||
for i, char in enumerate(text):
|
f"{ord(char) ^ ord(final_key[i % key_len]):02x}"
|
||||||
xor_result = ord(char) ^ ord(final_key[i % key_len])
|
for i, char in enumerate(text)
|
||||||
result.append(f"{xor_result:02x}")
|
)
|
||||||
return ''.join(result)
|
|
||||||
|
|
||||||
def _xor_decrypt_with_final_key(self, hex_text, user_password):
|
def _xor_decrypt_with_final_key(self, hex_text, user_password):
|
||||||
|
"""XOR decrypt with the derived final key."""
|
||||||
try:
|
try:
|
||||||
text_length = len(hex_text) // 2
|
text_length = len(hex_text) // 2
|
||||||
final_key = self._derive_final_key(user_password, text_length)
|
final_key = self._derive_final_key(user_password, text_length)
|
||||||
@@ -390,47 +462,35 @@ class EncryptionSystem:
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
def _substitute_letters(self, text, mapping):
|
def _substitute_letters(self, text, mapping):
|
||||||
result = []
|
"""Apply a substitution map to letters."""
|
||||||
for char in text:
|
return ''.join(mapping.get(char, char) for char in text)
|
||||||
if char in mapping:
|
|
||||||
result.append(mapping[char])
|
|
||||||
else:
|
|
||||||
result.append(char)
|
|
||||||
return ''.join(result)
|
|
||||||
|
|
||||||
def _encode_digit(self, num_str):
|
def _encode_digit(self, num_str):
|
||||||
result = []
|
"""Encode a digit string using the digit mapping."""
|
||||||
for char in num_str:
|
return ''.join(self.digit_mapping.get(char, char) for char in num_str)
|
||||||
if char in self.digit_mapping:
|
|
||||||
result.append(self.digit_mapping[char])
|
|
||||||
else:
|
|
||||||
result.append(char)
|
|
||||||
return ''.join(result)
|
|
||||||
|
|
||||||
def _decode_digit(self, encoded_str):
|
def _decode_digit(self, encoded_str):
|
||||||
result = []
|
"""Decode a digit string using the reverse digit mapping."""
|
||||||
for char in encoded_str:
|
return ''.join(self.digit_reverse.get(char, char) for char in encoded_str)
|
||||||
if char in self.digit_reverse:
|
|
||||||
result.append(self.digit_reverse[char])
|
|
||||||
else:
|
|
||||||
result.append(char)
|
|
||||||
return ''.join(result)
|
|
||||||
|
|
||||||
def _get_dynamic_key(self, text_length):
|
def _get_dynamic_key(self, text_length):
|
||||||
|
"""Generate a dynamic key from the long key, repeated as needed."""
|
||||||
key = self.long_key
|
key = self.long_key
|
||||||
while len(key) < text_length:
|
if len(key) < text_length:
|
||||||
key += self.long_key
|
repeats = (text_length // len(key)) + 1
|
||||||
|
key = (key * repeats)[:text_length]
|
||||||
return key[:text_length]
|
return key[:text_length]
|
||||||
|
|
||||||
def _xor_encrypt_with_key(self, text, key):
|
def _xor_encrypt_with_key(self, text, key):
|
||||||
|
"""XOR encrypt with a fixed key, returning hex."""
|
||||||
key_len = len(key)
|
key_len = len(key)
|
||||||
result = []
|
return ''.join(
|
||||||
for i, char in enumerate(text):
|
f"{ord(char) ^ ord(key[i % key_len]):02x}"
|
||||||
xor_result = ord(char) ^ ord(key[i % key_len])
|
for i, char in enumerate(text)
|
||||||
result.append(f"{xor_result:02x}")
|
)
|
||||||
return ''.join(result)
|
|
||||||
|
|
||||||
def _xor_decrypt_with_key(self, hex_text, key):
|
def _xor_decrypt_with_key(self, hex_text, key):
|
||||||
|
"""XOR decrypt with a fixed key."""
|
||||||
try:
|
try:
|
||||||
key_len = len(key)
|
key_len = len(key)
|
||||||
result = []
|
result = []
|
||||||
@@ -448,10 +508,28 @@ class EncryptionSystem:
|
|||||||
except Exception:
|
except Exception:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def encrypt(self, plaintext, user_password):
|
# ----------------------------------------------------------------------
|
||||||
if not self.keys_loaded:
|
# Public API
|
||||||
return "❌ 错误:密钥未加载"
|
# ----------------------------------------------------------------------
|
||||||
|
|
||||||
|
def encrypt(self, plaintext, user_password):
|
||||||
|
"""
|
||||||
|
Encrypt plaintext with the given password.
|
||||||
|
|
||||||
|
Workflow:
|
||||||
|
1. Base64 encode the plaintext.
|
||||||
|
2. Apply letter substitution and case-flipping.
|
||||||
|
3. Reverse the string and append padding count.
|
||||||
|
4. XOR encrypt with dynamic key (long key).
|
||||||
|
5. XOR encrypt with derived final key (user password + short key).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Encrypted ciphertext as a hex string.
|
||||||
|
"""
|
||||||
|
if not self.keys_loaded:
|
||||||
|
return "❌ Error: Keys not loaded"
|
||||||
|
|
||||||
|
# Step 1: Base64 encode and handle special chars
|
||||||
b64 = base64.b64encode(plaintext.encode('utf-8')).decode('utf-8')
|
b64 = base64.b64encode(plaintext.encode('utf-8')).decode('utf-8')
|
||||||
equal_count = b64.count('=')
|
equal_count = b64.count('=')
|
||||||
|
|
||||||
@@ -460,33 +538,44 @@ class EncryptionSystem:
|
|||||||
processed = processed.replace(old, new)
|
processed = processed.replace(old, new)
|
||||||
processed = processed.rstrip('=')
|
processed = processed.rstrip('=')
|
||||||
|
|
||||||
|
# Step 2: Letter substitution + flip + reverse
|
||||||
sub = self._substitute_letters(processed, self.encrypt_map)
|
sub = self._substitute_letters(processed, self.encrypt_map)
|
||||||
flipped = self._apply_flip(sub)
|
flipped = self._apply_flip(sub)
|
||||||
reversed_text = flipped[::-1]
|
reversed_text = flipped[::-1]
|
||||||
|
|
||||||
|
# Step 3: Append padding count
|
||||||
equal_char = self.equal_mapping[str(equal_count)]
|
equal_char = self.equal_mapping[str(equal_count)]
|
||||||
with_equal = f"{reversed_text}|{equal_char}"
|
with_equal = f"{reversed_text}|{equal_char}"
|
||||||
|
|
||||||
|
# Step 4: Dynamic key (long key) encryption
|
||||||
key_length_str = str(len(with_equal))
|
key_length_str = str(len(with_equal))
|
||||||
key_length_encoded = self._encode_digit(key_length_str)
|
key_length_encoded = self._encode_digit(key_length_str)
|
||||||
|
|
||||||
dynamic_key = self._get_dynamic_key(len(with_equal))
|
dynamic_key = self._get_dynamic_key(len(with_equal))
|
||||||
encrypted_by_dynamic = self._xor_encrypt_with_key(with_equal, dynamic_key)
|
encrypted_by_dynamic = self._xor_encrypt_with_key(with_equal, dynamic_key)
|
||||||
|
|
||||||
|
# Step 5: Final encryption with derived key
|
||||||
combined = f"{encrypted_by_dynamic}|{key_length_encoded}"
|
combined = f"{encrypted_by_dynamic}|{key_length_encoded}"
|
||||||
final_encrypted = self._xor_encrypt_with_final_key(combined, user_password)
|
final_encrypted = self._xor_encrypt_with_final_key(combined, user_password)
|
||||||
|
|
||||||
return final_encrypted
|
return final_encrypted
|
||||||
|
|
||||||
def decrypt(self, ciphertext, user_password):
|
def decrypt(self, ciphertext, user_password):
|
||||||
|
"""
|
||||||
|
Decrypt ciphertext with the given password.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The original plaintext, or an error message on failure.
|
||||||
|
"""
|
||||||
if not self.keys_loaded:
|
if not self.keys_loaded:
|
||||||
return "❌ 解密失败"
|
return "❌ Decryption failed"
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
# Step 1: Decrypt with derived final key
|
||||||
combined = self._xor_decrypt_with_final_key(ciphertext, user_password)
|
combined = self._xor_decrypt_with_final_key(ciphertext, user_password)
|
||||||
if combined is None:
|
if combined is None:
|
||||||
return "❌ 解密失败"
|
return "❌ Decryption failed"
|
||||||
|
|
||||||
|
# Step 2: Extract hex data and length indicator
|
||||||
if '|' in combined:
|
if '|' in combined:
|
||||||
parts = combined.split('|')
|
parts = combined.split('|')
|
||||||
if len(parts) >= 2:
|
if len(parts) >= 2:
|
||||||
@@ -499,6 +588,7 @@ class EncryptionSystem:
|
|||||||
hex_data = combined
|
hex_data = combined
|
||||||
key_length_encoded = 'g'
|
key_length_encoded = 'g'
|
||||||
|
|
||||||
|
# Step 3: Decode length and get dynamic key
|
||||||
key_length_str = self._decode_digit(key_length_encoded)
|
key_length_str = self._decode_digit(key_length_encoded)
|
||||||
try:
|
try:
|
||||||
key_length = int(key_length_str)
|
key_length = int(key_length_str)
|
||||||
@@ -506,10 +596,13 @@ class EncryptionSystem:
|
|||||||
key_length = 16
|
key_length = 16
|
||||||
|
|
||||||
dynamic_key = self._get_dynamic_key(key_length)
|
dynamic_key = self._get_dynamic_key(key_length)
|
||||||
|
|
||||||
|
# Step 4: Decrypt with dynamic key
|
||||||
xor_decrypted = self._xor_decrypt_with_key(hex_data, dynamic_key)
|
xor_decrypted = self._xor_decrypt_with_key(hex_data, dynamic_key)
|
||||||
if xor_decrypted is None:
|
if xor_decrypted is None:
|
||||||
return "❌ 解密失败"
|
return "❌ Decryption failed"
|
||||||
|
|
||||||
|
# Step 5: Extract main data and padding count
|
||||||
if '|' in xor_decrypted:
|
if '|' in xor_decrypted:
|
||||||
main_part, equal_char = xor_decrypted.split('|')
|
main_part, equal_char = xor_decrypted.split('|')
|
||||||
equal_count = int(self.equal_reverse.get(equal_char, '0'))
|
equal_count = int(self.equal_reverse.get(equal_char, '0'))
|
||||||
@@ -517,192 +610,211 @@ class EncryptionSystem:
|
|||||||
main_part = xor_decrypted
|
main_part = xor_decrypted
|
||||||
equal_count = 0
|
equal_count = 0
|
||||||
|
|
||||||
|
# Step 6: Reverse, flip, substitute
|
||||||
reversed_text = main_part[::-1]
|
reversed_text = main_part[::-1]
|
||||||
flipped = self._apply_flip(reversed_text)
|
flipped = self._apply_flip(reversed_text)
|
||||||
sub = self._substitute_letters(flipped, self.decrypt_map)
|
sub = self._substitute_letters(flipped, self.decrypt_map)
|
||||||
|
|
||||||
|
# Step 7: Restore Base64 special chars and padding
|
||||||
for old, new in self.special_decrypt.items():
|
for old, new in self.special_decrypt.items():
|
||||||
sub = sub.replace(old, new)
|
sub = sub.replace(old, new)
|
||||||
|
|
||||||
b64_with_equal = sub + '=' * equal_count
|
b64_with_equal = sub + '=' * equal_count
|
||||||
|
|
||||||
if len(b64_with_equal) % 4 != 0:
|
if len(b64_with_equal) % 4 != 0:
|
||||||
return "❌ 解密失败"
|
return "❌ Decryption failed"
|
||||||
|
|
||||||
|
# Step 8: Base64 decode
|
||||||
decoded = base64.b64decode(b64_with_equal.encode('utf-8')).decode('utf-8')
|
decoded = base64.b64decode(b64_with_equal.encode('utf-8')).decode('utf-8')
|
||||||
return decoded
|
return decoded
|
||||||
|
|
||||||
except Exception:
|
except Exception:
|
||||||
return "❌ 解密失败"
|
return "❌ Decryption failed"
|
||||||
|
|
||||||
def print_keys(self):
|
def print_keys(self):
|
||||||
|
"""Display information about the currently loaded keys."""
|
||||||
if not self.keys_loaded:
|
if not self.keys_loaded:
|
||||||
print("❌ 未加载密钥")
|
print("❌ Keys not loaded")
|
||||||
return
|
return
|
||||||
|
|
||||||
print("=" * 60)
|
print("=" * 60)
|
||||||
print("密钥信息")
|
print("Key Information")
|
||||||
print("=" * 60)
|
print("=" * 60)
|
||||||
print(f"密钥文件: {self.key_file}")
|
print(f"Key file: {self.key_file}")
|
||||||
print(f"大写映射表: {self.upper_mapping}")
|
print(f"Uppercase mapping: {self.upper_mapping}")
|
||||||
print(f"小写映射表: {self.lower_mapping}")
|
print(f"Lowercase mapping: {self.lower_mapping}")
|
||||||
print(f"翻转模式: {self.flip_pattern}")
|
print(f"Flip pattern: {self.flip_pattern}")
|
||||||
print(f"长密钥长度: {len(self.long_key)} 位")
|
print(f"Long key length: {len(self.long_key)} bits")
|
||||||
print(f"短密钥长度: {len(self.short_key)} 位")
|
print(f"Short key length: {len(self.short_key)} bits")
|
||||||
print("=" * 60)
|
print("=" * 60)
|
||||||
|
|
||||||
|
|
||||||
|
# ----------------------------------------------------------------------
|
||||||
|
# CLI Entry Point
|
||||||
|
# ----------------------------------------------------------------------
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
|
"""Command-line interface for the encryption system."""
|
||||||
print("=" * 60)
|
print("=" * 60)
|
||||||
print("欢迎使用加密系统")
|
print("Welcome to the Encryption System")
|
||||||
print("=" * 60)
|
print("=" * 60)
|
||||||
|
|
||||||
crypto = None
|
crypto = None
|
||||||
key_password = None
|
key_password = None
|
||||||
|
|
||||||
|
# Try loading default key file
|
||||||
if os.path.exists("encryption.key"):
|
if os.path.exists("encryption.key"):
|
||||||
key_password = input("请输入默认密钥文件 (encryption.key) 的密码: ")
|
key_password = input("Enter password for default key file (encryption.key): ")
|
||||||
crypto = EncryptionSystem("encryption.key", key_password)
|
crypto = EncryptionSystem("encryption.key", key_password)
|
||||||
if not crypto.keys_loaded:
|
if not crypto.keys_loaded:
|
||||||
print("❌ 加载失败")
|
print("❌ Loading failed")
|
||||||
crypto = None
|
crypto = None
|
||||||
else:
|
else:
|
||||||
print("\n未找到默认密钥文件,请先生成")
|
print("\nDefault key file not found. Please generate one first.")
|
||||||
choice = input("是否生成默认密钥文件?(y/n): ").strip().lower()
|
choice = input("Generate default key file? (y/n): ").strip().lower()
|
||||||
if choice == 'y':
|
if choice == 'y':
|
||||||
crypto = EncryptionSystem()
|
crypto = EncryptionSystem()
|
||||||
key_password = crypto.generate_keys("encryption.key")
|
result = crypto.generate_keys("encryption.key")
|
||||||
if key_password is None:
|
if result is None:
|
||||||
print("❌ 生成失败")
|
print("❌ Generation failed")
|
||||||
crypto = None
|
crypto = None
|
||||||
else:
|
else:
|
||||||
print("⚠️ 请使用模式4或5指定密钥文件,或模式6生成新密钥")
|
print("⚠️ Use options 4, 5, or 6 to manage key files manually.")
|
||||||
|
|
||||||
|
# Main interaction loop
|
||||||
while True:
|
while True:
|
||||||
print("\n请选择操作:")
|
print("\nSelect an option:")
|
||||||
print("1. 使用默认密钥加密")
|
print("1. Encrypt with default key")
|
||||||
print("2. 使用默认密钥解密")
|
print("2. Decrypt with default key")
|
||||||
print("3. 生成新密钥(覆盖默认)")
|
print("3. Generate new key (overwrite default)")
|
||||||
print("4. 使用指定密钥文件加密")
|
print("4. Encrypt with custom key file")
|
||||||
print("5. 使用指定密钥文件解密")
|
print("5. Decrypt with custom key file")
|
||||||
print("6. 生成密钥并保存到当前文件夹")
|
print("6. Generate key and save to current folder")
|
||||||
print("7. 查看当前密钥信息")
|
print("7. View current key info")
|
||||||
print("8. 退出")
|
print("8. Exit")
|
||||||
|
|
||||||
choice = input("\n请选择操作 (1-8): ").strip()
|
choice = input("\nEnter choice (1-8): ").strip()
|
||||||
|
|
||||||
if choice == '1':
|
if choice == '1':
|
||||||
|
# Encrypt with default key
|
||||||
if crypto is None or not crypto.keys_loaded:
|
if crypto is None or not crypto.keys_loaded:
|
||||||
if os.path.exists("encryption.key"):
|
if os.path.exists("encryption.key"):
|
||||||
if key_password is None:
|
if key_password is None:
|
||||||
key_password = input("请输入默认密钥文件密码: ")
|
key_password = input("Enter default key file password: ")
|
||||||
crypto = EncryptionSystem("encryption.key", key_password)
|
crypto = EncryptionSystem("encryption.key", key_password)
|
||||||
if not crypto.keys_loaded:
|
if not crypto.keys_loaded:
|
||||||
print("❌ 加载失败")
|
print("❌ Loading failed")
|
||||||
continue
|
continue
|
||||||
else:
|
else:
|
||||||
print("❌ 密钥文件不存在")
|
print("❌ Key file not found")
|
||||||
continue
|
continue
|
||||||
|
|
||||||
password = input("请输入加密密码: ")
|
password = input("Enter encryption password: ")
|
||||||
text = input("请输入要加密的文本: ")
|
text = input("Enter text to encrypt: ")
|
||||||
if text and password:
|
if text and password:
|
||||||
encrypted = crypto.encrypt(text, password)
|
encrypted = crypto.encrypt(text, password)
|
||||||
print(f"\n✅ 加密结果: {encrypted}")
|
print(f"\n✅ Encrypted result: {encrypted}")
|
||||||
|
|
||||||
elif choice == '2':
|
elif choice == '2':
|
||||||
|
# Decrypt with default key
|
||||||
if crypto is None or not crypto.keys_loaded:
|
if crypto is None or not crypto.keys_loaded:
|
||||||
if os.path.exists("encryption.key"):
|
if os.path.exists("encryption.key"):
|
||||||
if key_password is None:
|
if key_password is None:
|
||||||
key_password = input("请输入默认密钥文件密码: ")
|
key_password = input("Enter default key file password: ")
|
||||||
crypto = EncryptionSystem("encryption.key", key_password)
|
crypto = EncryptionSystem("encryption.key", key_password)
|
||||||
if not crypto.keys_loaded:
|
if not crypto.keys_loaded:
|
||||||
print("❌ 加载失败")
|
print("❌ Loading failed")
|
||||||
continue
|
continue
|
||||||
else:
|
else:
|
||||||
print("❌ 密钥文件不存在")
|
print("❌ Key file not found")
|
||||||
continue
|
continue
|
||||||
|
|
||||||
password = input("请输入加密密码: ")
|
password = input("Enter encryption password: ")
|
||||||
text = input("请输入要解密的密文: ")
|
text = input("Enter ciphertext to decrypt: ")
|
||||||
if text and password:
|
if text and password:
|
||||||
decrypted = crypto.decrypt(text, password)
|
decrypted = crypto.decrypt(text, password)
|
||||||
print(f"\n✅ 解密结果: {decrypted}")
|
print(f"\n✅ Decrypted result: {decrypted}")
|
||||||
|
|
||||||
elif choice == '3':
|
elif choice == '3':
|
||||||
|
# Generate and overwrite default key
|
||||||
crypto = EncryptionSystem()
|
crypto = EncryptionSystem()
|
||||||
key_password = crypto.generate_keys("encryption.key")
|
result = crypto.generate_keys("encryption.key")
|
||||||
if key_password is None:
|
if result is None:
|
||||||
print("❌ 生成失败")
|
print("❌ Generation failed")
|
||||||
else:
|
else:
|
||||||
print("✅ 默认密钥已更新")
|
print("✅ Default key updated")
|
||||||
|
|
||||||
elif choice == '4':
|
elif choice == '4':
|
||||||
key_file = input("请输入密钥文件路径: ")
|
# Encrypt with custom key file
|
||||||
|
key_file = input("Enter key file path: ")
|
||||||
if not os.path.exists(key_file):
|
if not os.path.exists(key_file):
|
||||||
print(f"❌ 文件不存在")
|
print(f"❌ File not found: {key_file}")
|
||||||
continue
|
continue
|
||||||
|
|
||||||
kp = input(f"请输入密钥文件密码: ")
|
kp = input("Enter key file password: ")
|
||||||
crypto = EncryptionSystem(key_file, kp)
|
crypto = EncryptionSystem(key_file, kp)
|
||||||
if not crypto.keys_loaded:
|
if not crypto.keys_loaded:
|
||||||
print("❌ 加载失败")
|
print("❌ Loading failed")
|
||||||
continue
|
continue
|
||||||
|
|
||||||
password = input("请输入加密密码: ")
|
password = input("Enter encryption password: ")
|
||||||
text = input("请输入要加密的文本: ")
|
text = input("Enter text to encrypt: ")
|
||||||
if text and password:
|
if text and password:
|
||||||
encrypted = crypto.encrypt(text, password)
|
encrypted = crypto.encrypt(text, password)
|
||||||
print(f"\n✅ 加密结果: {encrypted}")
|
print(f"\n✅ Encrypted result: {encrypted}")
|
||||||
|
|
||||||
elif choice == '5':
|
elif choice == '5':
|
||||||
key_file = input("请输入密钥文件路径: ")
|
# Decrypt with custom key file
|
||||||
|
key_file = input("Enter key file path: ")
|
||||||
if not os.path.exists(key_file):
|
if not os.path.exists(key_file):
|
||||||
print(f"❌ 文件不存在")
|
print(f"❌ File not found: {key_file}")
|
||||||
continue
|
continue
|
||||||
|
|
||||||
kp = input(f"请输入密钥文件密码: ")
|
kp = input("Enter key file password: ")
|
||||||
crypto = EncryptionSystem(key_file, kp)
|
crypto = EncryptionSystem(key_file, kp)
|
||||||
if not crypto.keys_loaded:
|
if not crypto.keys_loaded:
|
||||||
print("❌ 加载失败")
|
print("❌ Loading failed")
|
||||||
continue
|
continue
|
||||||
|
|
||||||
password = input("请输入加密密码: ")
|
password = input("Enter encryption password: ")
|
||||||
text = input("请输入要解密的密文: ")
|
text = input("Enter ciphertext to decrypt: ")
|
||||||
if text and password:
|
if text and password:
|
||||||
decrypted = crypto.decrypt(text, password)
|
decrypted = crypto.decrypt(text, password)
|
||||||
print(f"\n✅ 解密结果: {decrypted}")
|
print(f"\n✅ Decrypted result: {decrypted}")
|
||||||
|
|
||||||
elif choice == '6':
|
elif choice == '6':
|
||||||
|
# Generate new key with timestamp
|
||||||
timestamp = int(time.time())
|
timestamp = int(time.time())
|
||||||
filename = f"key_{timestamp}.key"
|
filename = f"key_{timestamp}.key"
|
||||||
crypto = EncryptionSystem()
|
crypto = EncryptionSystem()
|
||||||
kp = crypto.generate_keys(filename)
|
result = crypto.generate_keys(filename)
|
||||||
if kp is None:
|
if result is None:
|
||||||
print("❌ 生成失败")
|
print("❌ Generation failed")
|
||||||
else:
|
else:
|
||||||
print(f"✅ 密钥已保存到: {filename}")
|
print(f"✅ Key saved to: {filename}")
|
||||||
|
|
||||||
elif choice == '7':
|
elif choice == '7':
|
||||||
|
# Show key info
|
||||||
if crypto is None or not crypto.keys_loaded:
|
if crypto is None or not crypto.keys_loaded:
|
||||||
if os.path.exists("encryption.key"):
|
if os.path.exists("encryption.key"):
|
||||||
if key_password is None:
|
if key_password is None:
|
||||||
key_password = input("请输入默认密钥文件密码: ")
|
key_password = input("Enter default key file password: ")
|
||||||
crypto = EncryptionSystem("encryption.key", key_password)
|
crypto = EncryptionSystem("encryption.key", key_password)
|
||||||
if not crypto.keys_loaded:
|
if not crypto.keys_loaded:
|
||||||
print("❌ 加载失败")
|
print("❌ Loading failed")
|
||||||
continue
|
continue
|
||||||
else:
|
else:
|
||||||
print("❌ 未加载密钥")
|
print("❌ Keys not loaded")
|
||||||
continue
|
continue
|
||||||
crypto.print_keys()
|
crypto.print_keys()
|
||||||
|
|
||||||
elif choice == '8':
|
elif choice == '8':
|
||||||
print("感谢使用,再见!")
|
print("Goodbye!")
|
||||||
break
|
break
|
||||||
|
|
||||||
else:
|
else:
|
||||||
print("❌ 无效选择")
|
print("❌ Invalid choice")
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
main()
|
main()
|
||||||
@@ -0,0 +1,603 @@
|
|||||||
|
"""
|
||||||
|
ChaosCrypt test suite.
|
||||||
|
|
||||||
|
Covers round-trip integrity, binary safety, key management, the unified error
|
||||||
|
types, CLI behaviour, i18n, and bidirectional compatibility with the original
|
||||||
|
single-file implementation.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from chaoscrypt import (
|
||||||
|
DEFAULT_KEY_FILE,
|
||||||
|
ChaosCrypt,
|
||||||
|
ChaosCryptCore,
|
||||||
|
ChaosCryptError,
|
||||||
|
ChaosCrypt_ERR_KeyFileNotFound_E001,
|
||||||
|
ChaosCrypt_ERR_KeyFileExists_E005,
|
||||||
|
ChaosCrypt_ERR_KeyNotLoaded_E004,
|
||||||
|
ChaosCrypt_ERR_EmptyPassword_E006,
|
||||||
|
ChaosCrypt_ERR_EmptyPlaintext_E008,
|
||||||
|
ChaosCrypt_ERR_DecryptionFailed_E011,
|
||||||
|
)
|
||||||
|
from chaoscrypt.i18n import LANG_NAMES, t
|
||||||
|
|
||||||
|
KEY_PWD = "key-file-password"
|
||||||
|
USER_PWD = "user-encryption-password"
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Fixtures
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
@pytest.fixture
|
||||||
|
def keyfile(tmp_path):
|
||||||
|
"""Create a key file and return ``(ChaosCrypt, path)``."""
|
||||||
|
path = str(tmp_path / "test.key")
|
||||||
|
cc = ChaosCrypt()
|
||||||
|
cc.create_key(KEY_PWD, path)
|
||||||
|
return cc, path
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def loaded(keyfile):
|
||||||
|
"""Return an instance with key material already loaded."""
|
||||||
|
_, path = keyfile
|
||||||
|
n = ChaosCrypt()
|
||||||
|
n.load(path, KEY_PWD)
|
||||||
|
return n
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Round-trip
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
class TestRoundTrip:
|
||||||
|
SAMPLES = [
|
||||||
|
"hello",
|
||||||
|
"hello 世界",
|
||||||
|
"emoji test 🎉",
|
||||||
|
"a",
|
||||||
|
"x" * 1000,
|
||||||
|
"Mixed mixed 123!@#$%^&*()_+-=[]{}|;':\",./<>?",
|
||||||
|
"line1\nline2\ttabbed",
|
||||||
|
" leading and trailing ",
|
||||||
|
]
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("text", SAMPLES)
|
||||||
|
def test_text_roundtrip(self, loaded, text):
|
||||||
|
ct = loaded.encrypt(text, USER_PWD)
|
||||||
|
assert loaded.decrypt(ct, USER_PWD) == text
|
||||||
|
|
||||||
|
def test_ciphertext_is_hex(self, loaded):
|
||||||
|
ct = loaded.encrypt("data", USER_PWD)
|
||||||
|
int(ct, 16)
|
||||||
|
|
||||||
|
def test_empty_plaintext_rejected(self, loaded):
|
||||||
|
with pytest.raises(ChaosCryptError) as ei:
|
||||||
|
loaded.encrypt("", USER_PWD)
|
||||||
|
assert ei.value.code == "E008"
|
||||||
|
|
||||||
|
def test_empty_password_rejected(self, loaded):
|
||||||
|
with pytest.raises(ChaosCryptError) as ei:
|
||||||
|
loaded.encrypt("data", "")
|
||||||
|
assert ei.value.code == "E006"
|
||||||
|
|
||||||
|
def test_wrong_password_fails(self, loaded):
|
||||||
|
ct = loaded.encrypt("secret", USER_PWD)
|
||||||
|
with pytest.raises(ChaosCryptError) as ei:
|
||||||
|
loaded.decrypt(ct, "wrong-password")
|
||||||
|
assert ei.value.code == "E011"
|
||||||
|
|
||||||
|
def test_ciphertext_differs_per_password(self, loaded):
|
||||||
|
a = loaded.encrypt("same", "pwd-A")
|
||||||
|
b = loaded.encrypt("same", "pwd-B")
|
||||||
|
assert a != b
|
||||||
|
|
||||||
|
def test_non_hex_ciphertext_rejected(self, loaded):
|
||||||
|
with pytest.raises(ChaosCryptError) as ei:
|
||||||
|
loaded.decrypt("zzzz-not-hex", USER_PWD)
|
||||||
|
assert ei.value.code == "E010"
|
||||||
|
|
||||||
|
def test_odd_length_ciphertext_rejected(self, loaded):
|
||||||
|
with pytest.raises(ChaosCryptError) as ei:
|
||||||
|
loaded.decrypt("abc", USER_PWD)
|
||||||
|
assert ei.value.code == "E010"
|
||||||
|
|
||||||
|
def test_empty_ciphertext_rejected(self, loaded):
|
||||||
|
with pytest.raises(ChaosCryptError) as ei:
|
||||||
|
loaded.decrypt("", USER_PWD)
|
||||||
|
assert ei.value.code == "E009"
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Binary
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
class TestBinary:
|
||||||
|
@pytest.mark.parametrize("size", [1, 2, 255, 256, 4096, 100_000])
|
||||||
|
def test_binary_roundtrip(self, loaded, size):
|
||||||
|
raw = os.urandom(size)
|
||||||
|
ct = loaded.encrypt_bytes(raw, USER_PWD)
|
||||||
|
assert loaded.decrypt_bytes(ct, USER_PWD) == raw
|
||||||
|
|
||||||
|
def test_empty_binary_rejected(self, loaded):
|
||||||
|
with pytest.raises(ChaosCryptError):
|
||||||
|
loaded.encrypt_bytes(b"", USER_PWD)
|
||||||
|
|
||||||
|
def test_null_bytes_preserved(self, loaded):
|
||||||
|
raw = b"\x00\x01\x02\xff\xfe" * 100
|
||||||
|
ct = loaded.encrypt_bytes(raw, USER_PWD)
|
||||||
|
assert loaded.decrypt_bytes(ct, USER_PWD) == raw
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Key management
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
class TestKeyManagement:
|
||||||
|
def test_generate_and_load(self, tmp_path):
|
||||||
|
path = str(tmp_path / "k.key")
|
||||||
|
cc = ChaosCrypt()
|
||||||
|
assert cc.create_key(KEY_PWD, path) == path
|
||||||
|
assert os.path.exists(path)
|
||||||
|
|
||||||
|
n = ChaosCrypt()
|
||||||
|
n.load(path, KEY_PWD)
|
||||||
|
assert n.loaded
|
||||||
|
|
||||||
|
def test_keygen_refuses_overwrite(self, tmp_path):
|
||||||
|
path = str(tmp_path / "k.key")
|
||||||
|
ChaosCrypt().create_key(KEY_PWD, path)
|
||||||
|
with pytest.raises(ChaosCryptError) as ei:
|
||||||
|
ChaosCrypt().create_key(KEY_PWD, path)
|
||||||
|
assert ei.value.code == "E005"
|
||||||
|
|
||||||
|
def test_keygen_force_overwrite(self, tmp_path):
|
||||||
|
path = str(tmp_path / "k.key")
|
||||||
|
cc = ChaosCrypt()
|
||||||
|
cc.create_key(KEY_PWD, path)
|
||||||
|
first_upper = cc.core.upper_mapping
|
||||||
|
cc.create_key(KEY_PWD, path, overwrite=True)
|
||||||
|
assert cc.core.upper_mapping != first_upper
|
||||||
|
|
||||||
|
def test_load_missing_file(self):
|
||||||
|
with pytest.raises(ChaosCryptError) as ei:
|
||||||
|
ChaosCrypt().load("/definitely/not/here.key", KEY_PWD)
|
||||||
|
assert ei.value.code == "E001"
|
||||||
|
|
||||||
|
def test_load_wrong_key_password(self, keyfile):
|
||||||
|
_, path = keyfile
|
||||||
|
with pytest.raises(ChaosCryptError) as ei:
|
||||||
|
ChaosCrypt().load(path, "bad-password")
|
||||||
|
assert ei.value.code == "E003"
|
||||||
|
|
||||||
|
def test_load_corrupted_file(self, tmp_path):
|
||||||
|
path = tmp_path / "bad.key"
|
||||||
|
path.write_text("this is not a chaoscrypt key file!!!", encoding="utf-8")
|
||||||
|
with pytest.raises(ChaosCryptError) as ei:
|
||||||
|
ChaosCrypt().load(str(path), KEY_PWD)
|
||||||
|
assert ei.value.code == "E002"
|
||||||
|
|
||||||
|
def test_load_empty_file(self, tmp_path):
|
||||||
|
path = tmp_path / "empty.key"
|
||||||
|
path.write_text("", encoding="utf-8")
|
||||||
|
with pytest.raises(ChaosCryptError) as ei:
|
||||||
|
ChaosCrypt().load(str(path), KEY_PWD)
|
||||||
|
assert ei.value.code == "E002"
|
||||||
|
|
||||||
|
def test_encrypt_without_key_raises(self):
|
||||||
|
cc = ChaosCrypt()
|
||||||
|
with pytest.raises(ChaosCryptError) as ei:
|
||||||
|
cc.encrypt("data", USER_PWD)
|
||||||
|
assert ei.value.code == "E004"
|
||||||
|
|
||||||
|
def test_change_key_password(self, keyfile):
|
||||||
|
cc, path = keyfile
|
||||||
|
cc.change_key_password(KEY_PWD, "new-key-password", path)
|
||||||
|
|
||||||
|
ok = ChaosCrypt()
|
||||||
|
ok.load(path, "new-key-password")
|
||||||
|
assert ok.loaded
|
||||||
|
|
||||||
|
with pytest.raises(ChaosCryptError) as ei:
|
||||||
|
ChaosCrypt().load(path, KEY_PWD)
|
||||||
|
assert ei.value.code == "E003"
|
||||||
|
|
||||||
|
def test_change_password_preserves_data(self, keyfile):
|
||||||
|
cc, path = keyfile
|
||||||
|
ct = cc.encrypt("preserve me", USER_PWD)
|
||||||
|
cc.change_key_password(KEY_PWD, "brand-new-pwd", path)
|
||||||
|
|
||||||
|
n = ChaosCrypt()
|
||||||
|
n.load(path, "brand-new-pwd")
|
||||||
|
assert n.decrypt(ct, USER_PWD) == "preserve me"
|
||||||
|
|
||||||
|
def test_info_reports_key_sizes(self, loaded):
|
||||||
|
info = loaded.info()
|
||||||
|
assert info["long_key_length"] == 4096
|
||||||
|
assert info["short_key_length"] == 512
|
||||||
|
assert len(info["upper_mapping"]) == 26
|
||||||
|
assert len(info["flip_pattern"]) == 10
|
||||||
|
|
||||||
|
def test_export_and_import_key_text(self):
|
||||||
|
cc = ChaosCrypt()
|
||||||
|
text = cc.export_key_text(KEY_PWD)
|
||||||
|
assert text and isinstance(text, str)
|
||||||
|
assert cc.loaded, "export_key_text should leave the instance usable"
|
||||||
|
|
||||||
|
n = ChaosCrypt()
|
||||||
|
n.load_from_text(text, KEY_PWD)
|
||||||
|
ct = n.encrypt("via text", USER_PWD)
|
||||||
|
assert cc.decrypt(ct, USER_PWD) == "via text"
|
||||||
|
|
||||||
|
def test_load_from_text_wrong_password(self):
|
||||||
|
cc = ChaosCrypt()
|
||||||
|
text = cc.export_key_text(KEY_PWD)
|
||||||
|
with pytest.raises(ChaosCryptError) as ei:
|
||||||
|
ChaosCrypt().load_from_text(text, "not-the-password")
|
||||||
|
assert ei.value.code == "E003"
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Key isolation
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
class TestKeyIsolation:
|
||||||
|
def test_two_keys_produce_different_ciphertext(self, tmp_path):
|
||||||
|
a = ChaosCrypt()
|
||||||
|
a.create_key(KEY_PWD, str(tmp_path / "a.key"))
|
||||||
|
b = ChaosCrypt()
|
||||||
|
b.create_key(KEY_PWD, str(tmp_path / "b.key"))
|
||||||
|
assert a.encrypt("same text", USER_PWD) != b.encrypt("same text", USER_PWD)
|
||||||
|
|
||||||
|
def test_cross_key_decryption_fails(self, tmp_path):
|
||||||
|
a = ChaosCrypt()
|
||||||
|
a.create_key(KEY_PWD, str(tmp_path / "a.key"))
|
||||||
|
b = ChaosCrypt()
|
||||||
|
b.create_key(KEY_PWD, str(tmp_path / "b.key"))
|
||||||
|
|
||||||
|
ct = a.encrypt("cross-key test", USER_PWD)
|
||||||
|
try:
|
||||||
|
got = b.decrypt(ct, USER_PWD)
|
||||||
|
except ChaosCryptError:
|
||||||
|
got = None
|
||||||
|
assert got != "cross-key test"
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# File API
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
class TestFileAPI:
|
||||||
|
def test_encrypt_decrypt_file(self, loaded, tmp_path):
|
||||||
|
src = tmp_path / "data.bin"
|
||||||
|
payload = os.urandom(2048)
|
||||||
|
src.write_bytes(payload)
|
||||||
|
|
||||||
|
cc_file = str(tmp_path / "data.bin.cc")
|
||||||
|
out = loaded.encrypt_file(str(src), USER_PWD, cc_file)
|
||||||
|
assert os.path.exists(out)
|
||||||
|
|
||||||
|
dst = str(tmp_path / "restored.bin")
|
||||||
|
back = loaded.decrypt_file(cc_file, USER_PWD, dst)
|
||||||
|
assert open(back, "rb").read() == payload
|
||||||
|
|
||||||
|
def test_default_suffixes(self, loaded, tmp_path):
|
||||||
|
src = tmp_path / "note.txt"
|
||||||
|
src.write_text("hello file", encoding="utf-8")
|
||||||
|
out = loaded.encrypt_file(str(src), USER_PWD)
|
||||||
|
assert out.endswith(".cc")
|
||||||
|
|
||||||
|
back = loaded.decrypt_file(out, USER_PWD)
|
||||||
|
assert open(back, encoding="utf-8").read() == "hello file"
|
||||||
|
|
||||||
|
def test_missing_source_raises(self, loaded):
|
||||||
|
with pytest.raises(ChaosCryptError) as ei:
|
||||||
|
loaded.encrypt_file("/no/such/file.bin", USER_PWD)
|
||||||
|
assert ei.value.code == "E014"
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Unified error types
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
class TestErrorClass:
|
||||||
|
def test_message_format(self):
|
||||||
|
from chaoscrypt import ChaosCrypt_ERR_DecryptionFailed_E011
|
||||||
|
e = ChaosCrypt_ERR_DecryptionFailed_E011()
|
||||||
|
assert str(e).startswith("ChaosCrypt_ERR_")
|
||||||
|
assert str(e).endswith("_E011")
|
||||||
|
|
||||||
|
def test_code_and_detail_attributes(self):
|
||||||
|
e = ChaosCrypt_ERR_EmptyPlaintext_E008()
|
||||||
|
assert e.code == "E008"
|
||||||
|
assert e.detail == "EmptyPlaintext"
|
||||||
|
assert e.message == "ChaosCrypt_ERR_EmptyPlaintext_E008"
|
||||||
|
|
||||||
|
def test_all_errors_share_base(self):
|
||||||
|
from chaoscrypt import errors
|
||||||
|
for name in errors.__all__:
|
||||||
|
obj = getattr(errors, name)
|
||||||
|
if name == "ChaosCryptError":
|
||||||
|
continue
|
||||||
|
assert issubclass(obj, ChaosCryptError)
|
||||||
|
assert issubclass(obj, Exception)
|
||||||
|
|
||||||
|
def test_codes_are_unique(self):
|
||||||
|
from chaoscrypt import errors
|
||||||
|
codes = []
|
||||||
|
for name in errors.__all__:
|
||||||
|
obj = getattr(errors, name)
|
||||||
|
if name == "ChaosCryptError":
|
||||||
|
continue
|
||||||
|
codes.append(obj.CODE)
|
||||||
|
assert len(codes) == len(set(codes)), "duplicate error codes"
|
||||||
|
|
||||||
|
def test_custom_detail(self):
|
||||||
|
e = ChaosCrypt_ERR_KeyFileNotFound_E001(
|
||||||
|
detail="CustomDetail", code="E001"
|
||||||
|
)
|
||||||
|
assert e.detail == "CustomDetail"
|
||||||
|
assert e.code == "E001"
|
||||||
|
|
||||||
|
def test_catchable_as_generic_exception(self):
|
||||||
|
from chaoscrypt import ChaosCrypt_ERR_DecryptionFailed_E011
|
||||||
|
with pytest.raises(Exception):
|
||||||
|
raise ChaosCrypt_ERR_DecryptionFailed_E011()
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Algorithm compatibility
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
class TestLegacyCompatibility:
|
||||||
|
def test_format_matches_original_chain(self, loaded):
|
||||||
|
"""Reproduce the original decryption chain step by step."""
|
||||||
|
text = "compat check compatibility"
|
||||||
|
ct = loaded.encrypt(text, USER_PWD)
|
||||||
|
|
||||||
|
core = loaded.core
|
||||||
|
combined = core._xor_decrypt_with_final_key(ct, USER_PWD)
|
||||||
|
hex_data, key_len_enc = combined.split("|")
|
||||||
|
key_len = int(core._decode_digit(key_len_enc))
|
||||||
|
x = core._xor_decrypt_with_key(hex_data, core._get_dynamic_key(key_len))
|
||||||
|
main, eq_char = x.split("|")
|
||||||
|
eq_count = int(core.equal_reverse[eq_char])
|
||||||
|
sub = core._substitute_letters(
|
||||||
|
core._apply_flip(main[::-1]), core.decrypt_map
|
||||||
|
)
|
||||||
|
for o, n in core.special_decrypt.items():
|
||||||
|
sub = sub.replace(o, n)
|
||||||
|
assert base64.b64decode((sub + "=" * eq_count).encode()).decode() == text
|
||||||
|
|
||||||
|
def test_keyfile_readable_by_original_scheme(self, keyfile):
|
||||||
|
"""A newly generated key file must satisfy the original format."""
|
||||||
|
_, path = keyfile
|
||||||
|
core = ChaosCryptCore()
|
||||||
|
with open(path, "r") as f:
|
||||||
|
enc = f.read()
|
||||||
|
|
||||||
|
decrypted = core._xor_decrypt_data(enc, KEY_PWD)
|
||||||
|
assert decrypted is not None
|
||||||
|
data = core._deobfuscate_keys(decrypted)
|
||||||
|
assert set(data) >= {
|
||||||
|
"upper_mapping", "lower_mapping", "digit_mapping",
|
||||||
|
"equal_mapping", "flip_pattern", "long_key", "short_key",
|
||||||
|
}
|
||||||
|
assert len(data["long_key"]) == 4096
|
||||||
|
assert len(data["short_key"]) == 512
|
||||||
|
|
||||||
|
def test_reference_vector_stable(self):
|
||||||
|
"""Fixed key material must always produce the same ciphertext."""
|
||||||
|
core = ChaosCryptCore()
|
||||||
|
core.upper_mapping = "BCDEFGHIJKLMNOPQRSTUVWXYZA"
|
||||||
|
core.lower_mapping = "bcdefghijklmnopqrstuvwxyza"
|
||||||
|
core.digit_mapping = {
|
||||||
|
str(i): c for i, c in enumerate("ABCDEFGHIJ")
|
||||||
|
}
|
||||||
|
core.equal_mapping = {"0": "X", "1": "Y", "2": "Z", "3": "W"}
|
||||||
|
core.flip_pattern = [1, 0, 1, 0, 0, 1, 0, 0, 1, 0]
|
||||||
|
core.long_key = "0123456789abcdef" * 256
|
||||||
|
core.short_key = "fedcba9876543210" * 32
|
||||||
|
core.digit_reverse = {v: k for k, v in core.digit_mapping.items()}
|
||||||
|
core.equal_reverse = {v: k for k, v in core.equal_mapping.items()}
|
||||||
|
core._build_maps()
|
||||||
|
core.keys_loaded = True
|
||||||
|
|
||||||
|
plaintext = "reference vector"
|
||||||
|
ct1 = core.encrypt_text(plaintext, USER_PWD)
|
||||||
|
ct2 = core.encrypt_text(plaintext, USER_PWD)
|
||||||
|
assert ct1 == ct2
|
||||||
|
assert core.decrypt_text(ct1, USER_PWD) == plaintext
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# i18n
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
class TestI18n:
|
||||||
|
def test_english_is_default(self):
|
||||||
|
import chaoscrypt.i18n as i18n
|
||||||
|
assert i18n.DEFAULT_LANG == "en"
|
||||||
|
|
||||||
|
def test_langs_available(self):
|
||||||
|
assert "en" in LANG_NAMES
|
||||||
|
assert "zh" in LANG_NAMES
|
||||||
|
|
||||||
|
def test_t_returns_both_languages(self):
|
||||||
|
en = t("app_title", "en")
|
||||||
|
zh = t("app_title", "zh")
|
||||||
|
assert en != zh
|
||||||
|
assert "ChaosCrypt" in en
|
||||||
|
|
||||||
|
def test_t_default_is_english(self):
|
||||||
|
assert t("app_title") == t("app_title", "en")
|
||||||
|
|
||||||
|
def test_t_fallback_for_unknown_key(self):
|
||||||
|
assert t("nonexistent_key_xyz", "en") == "nonexistent_key_xyz"
|
||||||
|
|
||||||
|
def test_missing_language_falls_back(self):
|
||||||
|
assert t("app_title", "fr") == t("app_title", "en")
|
||||||
|
|
||||||
|
def test_every_key_has_both_languages(self):
|
||||||
|
from chaoscrypt.i18n import TEXTS
|
||||||
|
for key, entry in TEXTS.items():
|
||||||
|
assert "en" in entry, f"{key} missing English"
|
||||||
|
assert "zh" in entry, f"{key} missing Chinese"
|
||||||
|
|
||||||
|
def test_tui_defaults_to_english(self):
|
||||||
|
from chaoscrypt.tui import TUI
|
||||||
|
tui = TUI()
|
||||||
|
assert tui.lang == "en"
|
||||||
|
assert tui._tr("menu_encrypt") == "Encrypt text"
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# CLI
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
class TestCLI:
|
||||||
|
@staticmethod
|
||||||
|
def _run(args, **kw):
|
||||||
|
return subprocess.run(
|
||||||
|
[sys.executable, "-m", "chaoscrypt"] + args,
|
||||||
|
capture_output=True, text=True, **kw,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_version(self):
|
||||||
|
r = self._run(["--version"])
|
||||||
|
assert r.returncode == 0
|
||||||
|
assert "2.1.6" in r.stdout
|
||||||
|
|
||||||
|
def test_help_mentions_scope(self):
|
||||||
|
r = self._run(["--help"])
|
||||||
|
assert r.returncode == 0
|
||||||
|
assert "unaudited" in r.stdout.lower()
|
||||||
|
|
||||||
|
def test_keygen_and_encrypt_decrypt(self, tmp_path):
|
||||||
|
kf = str(tmp_path / "cli.key")
|
||||||
|
|
||||||
|
r = self._run(["keygen", "-k", kf, "-P", KEY_PWD])
|
||||||
|
assert r.returncode == 0, r.stderr
|
||||||
|
assert os.path.exists(kf)
|
||||||
|
|
||||||
|
r = self._run(["encrypt", "cli round trip", "-p", USER_PWD,
|
||||||
|
"-k", kf, "-P", KEY_PWD])
|
||||||
|
assert r.returncode == 0, r.stderr
|
||||||
|
ct = r.stdout.strip()
|
||||||
|
|
||||||
|
r = self._run(["decrypt", ct, "-p", USER_PWD, "-k", kf, "-P", KEY_PWD])
|
||||||
|
assert r.returncode == 0, r.stderr
|
||||||
|
assert r.stdout.strip() == "cli round trip"
|
||||||
|
|
||||||
|
def test_json_output(self, tmp_path):
|
||||||
|
kf = str(tmp_path / "j.key")
|
||||||
|
self._run(["keygen", "-k", kf, "-P", KEY_PWD])
|
||||||
|
|
||||||
|
r = self._run(["--json", "encrypt", "json test", "-p", USER_PWD,
|
||||||
|
"-k", kf, "-P", KEY_PWD])
|
||||||
|
payload = json.loads(r.stdout)
|
||||||
|
assert payload["ok"] is True
|
||||||
|
assert payload["mode"] == "encrypt"
|
||||||
|
assert payload["ciphertext"]
|
||||||
|
|
||||||
|
def test_info_json_redacts_maps(self, tmp_path):
|
||||||
|
kf = str(tmp_path / "i.key")
|
||||||
|
self._run(["keygen", "-k", kf, "-P", KEY_PWD])
|
||||||
|
r = self._run(["--json", "info", "-k", kf, "-P", KEY_PWD])
|
||||||
|
payload = json.loads(r.stdout)
|
||||||
|
assert payload["long_key_length"] == 4096
|
||||||
|
assert "hidden" in payload["upper_mapping"]
|
||||||
|
|
||||||
|
def test_error_exit_code(self, tmp_path):
|
||||||
|
r = self._run(["decrypt", "zzzz", "-p", USER_PWD,
|
||||||
|
"-k", str(tmp_path / "nope.key"), "-P", KEY_PWD])
|
||||||
|
assert r.returncode == 1
|
||||||
|
assert "ChaosCrypt_ERR_" in r.stderr
|
||||||
|
|
||||||
|
def test_password_from_env(self, tmp_path):
|
||||||
|
kf = str(tmp_path / "env.key")
|
||||||
|
env = dict(os.environ, CC_KP=KEY_PWD, CC_UP=USER_PWD)
|
||||||
|
r = self._run(["keygen", "-k", kf, "--key-pwd-env", "CC_KP"], env=env)
|
||||||
|
assert r.returncode == 0, r.stderr
|
||||||
|
|
||||||
|
r = self._run(["encrypt", "env test", "--pwd-env", "CC_UP",
|
||||||
|
"-k", kf, "-P", KEY_PWD], env=env)
|
||||||
|
assert r.returncode == 0, r.stderr
|
||||||
|
|
||||||
|
def test_password_from_file(self, tmp_path):
|
||||||
|
kf = str(tmp_path / "f.key")
|
||||||
|
pwd_file = tmp_path / ".pwd"
|
||||||
|
pwd_file.write_text(KEY_PWD + "\n", encoding="utf-8")
|
||||||
|
r = self._run(["keygen", "-k", kf, "--key-pwd-file", str(pwd_file)])
|
||||||
|
assert r.returncode == 0, r.stderr
|
||||||
|
|
||||||
|
def test_file_encrypt_decrypt(self, tmp_path):
|
||||||
|
kf = str(tmp_path / "f.key")
|
||||||
|
src = tmp_path / "in.txt"
|
||||||
|
src.write_text("file cli test", encoding="utf-8")
|
||||||
|
|
||||||
|
self._run(["keygen", "-k", kf, "-P", KEY_PWD])
|
||||||
|
r = self._run(["file", "encrypt", str(src), "-p", USER_PWD,
|
||||||
|
"-k", kf, "-P", KEY_PWD])
|
||||||
|
assert r.returncode == 0, r.stderr
|
||||||
|
|
||||||
|
cc_file = str(src) + ".cc"
|
||||||
|
assert os.path.exists(cc_file)
|
||||||
|
|
||||||
|
dst = str(tmp_path / "out.txt")
|
||||||
|
r = self._run(["file", "decrypt", cc_file, "-o", dst, "-p", USER_PWD,
|
||||||
|
"-k", kf, "-P", KEY_PWD])
|
||||||
|
assert r.returncode == 0, r.stderr
|
||||||
|
assert open(dst, encoding="utf-8").read() == "file cli test"
|
||||||
|
|
||||||
|
def test_chpwd(self, tmp_path):
|
||||||
|
kf = str(tmp_path / "c.key")
|
||||||
|
self._run(["keygen", "-k", kf, "-P", KEY_PWD])
|
||||||
|
r = self._run(["chpwd", "-k", kf, "-P", KEY_PWD,
|
||||||
|
"--new-pwd", "brand-new"])
|
||||||
|
assert r.returncode == 0, r.stderr
|
||||||
|
|
||||||
|
r = self._run(["info", "-k", kf, "-P", "brand-new"])
|
||||||
|
assert r.returncode == 0, r.stderr
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Core used directly
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
class TestCoreDirect:
|
||||||
|
def test_core_generate_and_use(self):
|
||||||
|
c = ChaosCryptCore()
|
||||||
|
data = c.generate_keymaterial()
|
||||||
|
ct = c.encrypt_text("core direct", USER_PWD)
|
||||||
|
assert c.decrypt_text(ct, USER_PWD) == "core direct"
|
||||||
|
|
||||||
|
text = c._xor_encrypt_data(c._obfuscate_keys(data), KEY_PWD)
|
||||||
|
c2 = ChaosCryptCore()
|
||||||
|
c2.load_keys_from_text(text, KEY_PWD)
|
||||||
|
assert c2.decrypt_text(ct, USER_PWD) == "core direct"
|
||||||
|
|
||||||
|
def test_key_material_sizes(self):
|
||||||
|
c = ChaosCryptCore()
|
||||||
|
c.generate_keymaterial()
|
||||||
|
assert len(c.upper_mapping) == 26
|
||||||
|
assert len(c.lower_mapping) == 26
|
||||||
|
assert len(c.digit_mapping) == 10
|
||||||
|
assert len(c.equal_mapping) == 4
|
||||||
|
assert len(c.flip_pattern) == 10
|
||||||
|
assert len(c.long_key) == 4096
|
||||||
|
assert len(c.short_key) == 512
|
||||||
|
|
||||||
|
def test_mappings_are_bijections(self):
|
||||||
|
c = ChaosCryptCore()
|
||||||
|
c.generate_keymaterial()
|
||||||
|
assert sorted(c.upper_mapping) == sorted("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
|
||||||
|
assert sorted(c.lower_mapping) == sorted("abcdefghijklmnopqrstuvwxyz")
|
||||||
|
assert len(set(c.digit_mapping.values())) == 10
|
||||||
|
assert len(set(c.equal_mapping.values())) == 4
|
||||||
|
|
||||||
|
def test_key_material_is_random_between_instances(self):
|
||||||
|
a = ChaosCryptCore()
|
||||||
|
a.generate_keymaterial()
|
||||||
|
b = ChaosCryptCore()
|
||||||
|
b.generate_keymaterial()
|
||||||
|
assert a.long_key != b.long_key
|
||||||
|
assert a.short_key != b.short_key
|
||||||
|
assert a.upper_mapping != b.upper_mapping
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
"""
|
||||||
|
Bidirectional interoperability tests against the original implementation.
|
||||||
|
|
||||||
|
These tests load ``chaoscrypt/legacy/chaoscrypt_legacy.py`` and prove that:
|
||||||
|
|
||||||
|
* ciphertext produced by the original script decrypts with the packaged
|
||||||
|
library, and
|
||||||
|
* ciphertext produced by the packaged library decrypts with the original
|
||||||
|
script.
|
||||||
|
|
||||||
|
They are the regression guard for the promise that the algorithm itself was
|
||||||
|
ported without any behavioural change.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import importlib.util
|
||||||
|
import os
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from chaoscrypt import ChaosCrypt
|
||||||
|
|
||||||
|
KEY_PWD = "legacy-key-password"
|
||||||
|
USER_PWD = "legacy-user-password"
|
||||||
|
|
||||||
|
SAMPLES = [
|
||||||
|
"legacy compatibility",
|
||||||
|
"兼容性检查",
|
||||||
|
"x" * 300,
|
||||||
|
"emoji test 🎉",
|
||||||
|
"multi\nline\ttabbed",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _load_legacy():
|
||||||
|
"""Import the legacy single-file implementation, or skip if absent."""
|
||||||
|
here = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||||
|
legacy = os.path.join(here, "legacy", "chaoscrypt_legacy.py")
|
||||||
|
if not os.path.exists(legacy):
|
||||||
|
pytest.skip("legacy implementation not present")
|
||||||
|
spec = importlib.util.spec_from_file_location("cc_legacy", legacy)
|
||||||
|
mod = importlib.util.module_from_spec(spec)
|
||||||
|
spec.loader.exec_module(mod)
|
||||||
|
return mod
|
||||||
|
|
||||||
|
|
||||||
|
class TestLegacyInterop:
|
||||||
|
def test_library_decrypts_legacy_ciphertext(self, tmp_path):
|
||||||
|
legacy_mod = _load_legacy()
|
||||||
|
kf = str(tmp_path / "legacy.key")
|
||||||
|
|
||||||
|
old = legacy_mod.EncryptionSystem()
|
||||||
|
old.generate_keys(kf, KEY_PWD)
|
||||||
|
|
||||||
|
pairs = [(tx, old.encrypt(tx, USER_PWD)) for tx in SAMPLES]
|
||||||
|
|
||||||
|
new = ChaosCrypt()
|
||||||
|
new.load(kf, KEY_PWD)
|
||||||
|
for tx, ct in pairs:
|
||||||
|
assert new.decrypt(ct, USER_PWD) == tx
|
||||||
|
|
||||||
|
def test_legacy_decrypts_library_ciphertext(self, tmp_path):
|
||||||
|
legacy_mod = _load_legacy()
|
||||||
|
kf = str(tmp_path / "legacy2.key")
|
||||||
|
|
||||||
|
new = ChaosCrypt()
|
||||||
|
new.create_key(KEY_PWD, kf)
|
||||||
|
|
||||||
|
old = legacy_mod.EncryptionSystem()
|
||||||
|
old._load_keys(kf, KEY_PWD)
|
||||||
|
|
||||||
|
for tx in SAMPLES:
|
||||||
|
ct = new.encrypt(tx, USER_PWD)
|
||||||
|
assert old.decrypt(ct, USER_PWD) == tx
|
||||||
|
|
||||||
|
def test_key_files_are_identical_in_format(self, tmp_path):
|
||||||
|
"""A library key file must load in the original implementation."""
|
||||||
|
legacy_mod = _load_legacy()
|
||||||
|
kf = str(tmp_path / "fmt.key")
|
||||||
|
|
||||||
|
ChaosCrypt().create_key(KEY_PWD, kf)
|
||||||
|
|
||||||
|
old = legacy_mod.EncryptionSystem()
|
||||||
|
old._load_keys(kf, KEY_PWD)
|
||||||
|
assert old.keys_loaded
|
||||||
@@ -0,0 +1,139 @@
|
|||||||
|
"""
|
||||||
|
Interactive TUI tests.
|
||||||
|
|
||||||
|
A key sequence is piped into the UI and the rendered output is inspected.
|
||||||
|
Outside a TTY the UI falls back from ``getpass`` to ``input``, which is what
|
||||||
|
makes it scriptable.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
KEY_PWD = "tui-key-password"
|
||||||
|
USER_PWD = "tui-user-password"
|
||||||
|
|
||||||
|
|
||||||
|
def _run_tui(seq: str, cwd: str, timeout: int = 90):
|
||||||
|
env = dict(os.environ, PYTHONIOENCODING="utf-8", NO_COLOR="1")
|
||||||
|
return subprocess.run(
|
||||||
|
[sys.executable, "-m", "chaoscrypt"],
|
||||||
|
input=seq, capture_output=True, text=True,
|
||||||
|
encoding="utf-8", env=env, cwd=cwd, timeout=timeout,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def tui_dir(tmp_path):
|
||||||
|
"""Create a TUI key file in an isolated directory."""
|
||||||
|
seq = f"5\nt.key\n{KEY_PWD}\n{KEY_PWD}\n\nq\n"
|
||||||
|
r = _run_tui(seq, str(tmp_path))
|
||||||
|
assert (tmp_path / "t.key").exists(), r.stdout
|
||||||
|
return str(tmp_path)
|
||||||
|
|
||||||
|
|
||||||
|
class TestTUI:
|
||||||
|
def test_launches_in_english_by_default(self, tmp_path):
|
||||||
|
r = _run_tui("q\n", str(tmp_path))
|
||||||
|
assert r.returncode == 0
|
||||||
|
assert "ChaosCrypt" in r.stdout
|
||||||
|
assert "Select an action" in r.stdout
|
||||||
|
assert "Encrypt text" in r.stdout
|
||||||
|
|
||||||
|
def test_shows_scope_notice(self, tmp_path):
|
||||||
|
r = _run_tui("q\n", str(tmp_path))
|
||||||
|
assert "unaudited" in r.stdout
|
||||||
|
assert "not for production" in r.stdout.lower()
|
||||||
|
|
||||||
|
def test_keygen_creates_file(self, tmp_path):
|
||||||
|
r = _run_tui(f"5\nmy.key\n{KEY_PWD}\n{KEY_PWD}\n\nq\n", str(tmp_path))
|
||||||
|
assert (tmp_path / "my.key").exists(), r.stdout
|
||||||
|
assert "Key file written to" in r.stdout
|
||||||
|
|
||||||
|
def test_keygen_password_mismatch(self, tmp_path):
|
||||||
|
r = _run_tui("5\nm.key\npwd-one\npwd-two\n\nq\n", str(tmp_path))
|
||||||
|
assert "E007" in r.stdout
|
||||||
|
assert not (tmp_path / "m.key").exists()
|
||||||
|
|
||||||
|
def test_encrypt_then_decrypt_in_new_session(self, tmp_path):
|
||||||
|
seq = (f"5\nt.key\n{KEY_PWD}\n{KEY_PWD}\n\n"
|
||||||
|
f"1\nsecret payload\n{USER_PWD}\n\nq\n")
|
||||||
|
r1 = _run_tui(seq, str(tmp_path))
|
||||||
|
m = re.search(r"Ciphertext:\s*\n([0-9a-f]{16,})", r1.stdout)
|
||||||
|
assert m, r1.stdout
|
||||||
|
ct = m.group(1).strip()
|
||||||
|
|
||||||
|
seq2 = f"6\nt.key\n{KEY_PWD}\n\n2\n{ct}\n{USER_PWD}\n\nq\n"
|
||||||
|
r2 = _run_tui(seq2, str(tmp_path))
|
||||||
|
assert "secret payload" in r2.stdout, r2.stdout
|
||||||
|
|
||||||
|
def test_load_remembers_key_file(self, tui_dir):
|
||||||
|
seq = f"6\nt.key\n{KEY_PWD}\n\n1\nremembers\n{USER_PWD}\n\nq\n"
|
||||||
|
r = _run_tui(seq, tui_dir)
|
||||||
|
assert re.search(r"Ciphertext:\s*\n([0-9a-f]{16,})", r.stdout), r.stdout
|
||||||
|
|
||||||
|
def test_wrong_user_password_shows_error(self, tui_dir):
|
||||||
|
seq = f"6\nt.key\n{KEY_PWD}\n\n2\n{'a' * 64}\nWRONG-{USER_PWD}\n\nq\n"
|
||||||
|
r = _run_tui(seq, tui_dir)
|
||||||
|
assert "ChaosCrypt_ERR_" in r.stdout
|
||||||
|
|
||||||
|
def test_wrong_key_password_shows_e003(self, tui_dir):
|
||||||
|
r = _run_tui("6\nt.key\nWRONG-KEY-PWD\n\nq\n", tui_dir)
|
||||||
|
assert "_E003" in r.stdout
|
||||||
|
|
||||||
|
def test_language_switch_to_chinese(self, tmp_path):
|
||||||
|
r = _run_tui("9\n2\n\nq\n", str(tmp_path))
|
||||||
|
assert "混沌混淆加密" in r.stdout
|
||||||
|
assert "请选择操作" in r.stdout
|
||||||
|
|
||||||
|
def test_language_switch_back_to_english(self, tmp_path):
|
||||||
|
r = _run_tui("9\n2\n\n9\n1\n\nq\n", str(tmp_path))
|
||||||
|
assert "Select an action" in r.stdout
|
||||||
|
|
||||||
|
def test_chinese_mode_encrypt_works(self, tui_dir):
|
||||||
|
seq = (f"6\nt.key\n{KEY_PWD}\n\n9\n2\n\n"
|
||||||
|
f"1\n中文内容\n{USER_PWD}\n\nq\n")
|
||||||
|
r = _run_tui(seq, tui_dir)
|
||||||
|
assert re.search(r"密文:\s*\n([0-9a-f]{16,})", r.stdout), r.stdout
|
||||||
|
|
||||||
|
def test_about_page_has_design_notes(self, tmp_path):
|
||||||
|
r = _run_tui("a\n\nq\n", str(tmp_path))
|
||||||
|
assert "10^5621" in r.stdout
|
||||||
|
assert "MIT" in r.stdout
|
||||||
|
assert "Shor" in r.stdout
|
||||||
|
|
||||||
|
def test_key_info_shows_sizes(self, tui_dir):
|
||||||
|
r = _run_tui(f"6\nt.key\n{KEY_PWD}\n\n7\n\nq\n", tui_dir)
|
||||||
|
assert "4096" in r.stdout
|
||||||
|
assert "512" in r.stdout
|
||||||
|
|
||||||
|
def test_invalid_option_reprompts(self, tmp_path):
|
||||||
|
r = _run_tui("zzz\n\nq\n", str(tmp_path))
|
||||||
|
assert "Unrecognised option" in r.stdout
|
||||||
|
|
||||||
|
def test_change_key_password_in_session(self, tui_dir):
|
||||||
|
seq = f"8\nt.key\n{KEY_PWD}\nnewkeypass\nnewkeypass\n\nq\n"
|
||||||
|
r = _run_tui(seq, tui_dir)
|
||||||
|
assert "updated" in r.stdout
|
||||||
|
|
||||||
|
r2 = _run_tui("6\nt.key\nnewkeypass\n\nq\n", tui_dir)
|
||||||
|
assert "Key file loaded" in r2.stdout
|
||||||
|
|
||||||
|
def test_file_encrypt_decrypt_via_tui(self, tui_dir):
|
||||||
|
src = os.path.join(tui_dir, "payload.txt")
|
||||||
|
with open(src, "w", encoding="utf-8") as f:
|
||||||
|
f.write("TUI file payload")
|
||||||
|
|
||||||
|
seq = (f"6\nt.key\n{KEY_PWD}\n\n"
|
||||||
|
f"3\n{src}\n{src}.cc\n{USER_PWD}\n\nq\n")
|
||||||
|
r = _run_tui(seq, tui_dir)
|
||||||
|
assert os.path.exists(src + ".cc"), r.stdout
|
||||||
|
|
||||||
|
seq2 = (f"6\nt.key\n{KEY_PWD}\n\n"
|
||||||
|
f"4\n{src}.cc\n{src}.out\n{USER_PWD}\n\nq\n")
|
||||||
|
r2 = _run_tui(seq2, tui_dir)
|
||||||
|
assert os.path.exists(src + ".out"), r2.stdout
|
||||||
|
assert open(src + ".out", encoding="utf-8").read() == "TUI file payload"
|
||||||
@@ -0,0 +1,473 @@
|
|||||||
|
"""
|
||||||
|
ChaosCrypt interactive terminal UI.
|
||||||
|
|
||||||
|
A dependency-free menu-driven interface, intended for people who would
|
||||||
|
rather not memorise command line flags. English is the default language;
|
||||||
|
the menu can switch to Chinese at runtime.
|
||||||
|
|
||||||
|
Running ``chaoscrypt`` with no arguments launches this UI. The module is
|
||||||
|
imported lazily so that library users never pay for it.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from . import DEFAULT_KEY_FILE, __version__, ChaosCrypt
|
||||||
|
from .errors import ChaosCryptError
|
||||||
|
from .i18n import DEFAULT_LANG, LANG_NAMES, t
|
||||||
|
|
||||||
|
__all__ = ["run_tui", "TUI"]
|
||||||
|
|
||||||
|
WIDTH = 66
|
||||||
|
|
||||||
|
# ANSI styling; degrades to plain text when the terminal cannot handle it.
|
||||||
|
_C = {
|
||||||
|
"reset": "\033[0m",
|
||||||
|
"bold": "\033[1m",
|
||||||
|
"dim": "\033[2m",
|
||||||
|
"cyan": "\033[36m",
|
||||||
|
"green": "\033[32m",
|
||||||
|
"yellow": "\033[33m",
|
||||||
|
"red": "\033[31m",
|
||||||
|
"magenta": "\033[35m",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _supports_color() -> bool:
|
||||||
|
"""Whether the attached stdout can render ANSI colour."""
|
||||||
|
if os.environ.get("NO_COLOR"):
|
||||||
|
return False
|
||||||
|
if not sys.stdout.isatty():
|
||||||
|
return False
|
||||||
|
if os.name == "nt":
|
||||||
|
try:
|
||||||
|
import ctypes
|
||||||
|
kernel32 = ctypes.windll.kernel32
|
||||||
|
kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)
|
||||||
|
return True
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
_COLOR = _supports_color()
|
||||||
|
|
||||||
|
|
||||||
|
def c(text: str, *styles: str) -> str:
|
||||||
|
"""Wrap ``text`` in ANSI styles, or return it unchanged."""
|
||||||
|
if not _COLOR or not styles:
|
||||||
|
return text
|
||||||
|
return "".join(_C.get(s, "") for s in styles) + text + _C["reset"]
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Input helpers
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
class _Abort(Exception):
|
||||||
|
"""Raised when the user asks to return to the main menu."""
|
||||||
|
|
||||||
|
|
||||||
|
def _ask(prompt: str, default: Optional[str] = None) -> str:
|
||||||
|
suffix = f" [{default}]" if default else ""
|
||||||
|
try:
|
||||||
|
val = input(f"{c('>', 'cyan')} {prompt}{suffix}: ").strip()
|
||||||
|
except (EOFError, KeyboardInterrupt):
|
||||||
|
print()
|
||||||
|
raise _Abort()
|
||||||
|
if not val and default is not None:
|
||||||
|
return default
|
||||||
|
return val
|
||||||
|
|
||||||
|
|
||||||
|
def _ask_secret(prompt: str) -> str:
|
||||||
|
"""Read a password without echoing it when possible.
|
||||||
|
|
||||||
|
Interactive terminals use ``getpass`` so the input is not shown. Piped or
|
||||||
|
redirected input cannot use ``getpass``, so it falls back to ``input``,
|
||||||
|
which keeps the UI scriptable.
|
||||||
|
"""
|
||||||
|
label = f"{c('>', 'cyan')} {prompt}: "
|
||||||
|
|
||||||
|
if sys.stdin is not None and sys.stdin.isatty():
|
||||||
|
try:
|
||||||
|
import getpass
|
||||||
|
return getpass.getpass(label)
|
||||||
|
except (EOFError, KeyboardInterrupt):
|
||||||
|
print()
|
||||||
|
raise _Abort()
|
||||||
|
except Exception:
|
||||||
|
pass # Fall through to the non-echoing fallback below.
|
||||||
|
|
||||||
|
try:
|
||||||
|
return input(label).strip()
|
||||||
|
except (EOFError, KeyboardInterrupt):
|
||||||
|
print()
|
||||||
|
raise _Abort()
|
||||||
|
|
||||||
|
|
||||||
|
def _ask_yes_no(prompt: str, lang: str) -> bool:
|
||||||
|
try:
|
||||||
|
val = input(f"{c('>', 'cyan')} {prompt} [y/n]: ").strip().lower()
|
||||||
|
except (EOFError, KeyboardInterrupt):
|
||||||
|
print()
|
||||||
|
raise _Abort()
|
||||||
|
return val in ("y", "yes")
|
||||||
|
|
||||||
|
|
||||||
|
def _pause(lang: str) -> None:
|
||||||
|
try:
|
||||||
|
input(c(f" {t('press_enter', lang)}", "dim"))
|
||||||
|
except (EOFError, KeyboardInterrupt):
|
||||||
|
print()
|
||||||
|
|
||||||
|
|
||||||
|
def _rule() -> str:
|
||||||
|
return "-" * WIDTH
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# TUI
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
class TUI:
|
||||||
|
"""Menu-driven bilingual interface over :class:`~chaoscrypt.ChaosCrypt`."""
|
||||||
|
|
||||||
|
def __init__(self, lang: str = DEFAULT_LANG,
|
||||||
|
key_file: str = DEFAULT_KEY_FILE) -> None:
|
||||||
|
self.lang = lang if lang in LANG_NAMES else DEFAULT_LANG
|
||||||
|
self.key_file = key_file
|
||||||
|
self.cc = ChaosCrypt()
|
||||||
|
self.key_password: Optional[str] = None
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------ view
|
||||||
|
def _tr(self, key: str) -> str:
|
||||||
|
return t(key, self.lang)
|
||||||
|
|
||||||
|
def banner(self) -> None:
|
||||||
|
print()
|
||||||
|
print(c("+" + "=" * (WIDTH - 2) + "+", "magenta"))
|
||||||
|
title = f" {self._tr('app_title')} v{__version__}"
|
||||||
|
print(c("|", "magenta")
|
||||||
|
+ c(title.ljust(WIDTH - 2), "bold", "cyan")
|
||||||
|
+ c("|", "magenta"))
|
||||||
|
print(c("+" + "=" * (WIDTH - 2) + "+", "magenta"))
|
||||||
|
for line in self._tr("warn_banner").split("\n"):
|
||||||
|
print(c(line, "yellow"))
|
||||||
|
|
||||||
|
shown = self.cc.key_file or self.key_file or DEFAULT_KEY_FILE
|
||||||
|
state = (
|
||||||
|
c("[*] " + self._tr("key_loaded"), "green")
|
||||||
|
if self.cc.loaded
|
||||||
|
else c("[ ] " + self._tr("no_key_loaded"), "red")
|
||||||
|
)
|
||||||
|
print(f"\n{state} {c(shown, 'dim')}")
|
||||||
|
|
||||||
|
def _print_error(self, exc: Exception) -> None:
|
||||||
|
"""Render a unified error, with a hint where one applies."""
|
||||||
|
print()
|
||||||
|
print(c("+" + "-" * (WIDTH - 2) + "+", "red"))
|
||||||
|
print(c("| ", "red")
|
||||||
|
+ c(f"{self._tr('err_prefix')}: {exc}", "red", "bold"))
|
||||||
|
print(c("+" + "-" * (WIDTH - 2) + "+", "red"))
|
||||||
|
|
||||||
|
msg = str(exc)
|
||||||
|
if "_E011" in msg or "_E003" in msg:
|
||||||
|
print(c(" " + self._tr("err_hint_password"), "dim"))
|
||||||
|
elif "_E004" in msg or "_E001" in msg:
|
||||||
|
print(c(" " + self._tr("err_hint_key_required"), "dim"))
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------ menu
|
||||||
|
def menu(self) -> str:
|
||||||
|
items = [
|
||||||
|
("1", "menu_encrypt"),
|
||||||
|
("2", "menu_decrypt"),
|
||||||
|
("3", "menu_encrypt_file"),
|
||||||
|
("4", "menu_decrypt_file"),
|
||||||
|
("5", "menu_keygen"),
|
||||||
|
("6", "menu_loadkey"),
|
||||||
|
("7", "menu_keyinfo"),
|
||||||
|
("8", "menu_chpwd"),
|
||||||
|
("9", "menu_lang"),
|
||||||
|
("a", "menu_about"),
|
||||||
|
("q", "menu_quit"),
|
||||||
|
]
|
||||||
|
print()
|
||||||
|
print(c(_rule(), "dim"))
|
||||||
|
print(c(" " + self._tr("menu_choose"), "bold"))
|
||||||
|
print(c(_rule(), "dim"))
|
||||||
|
for key, label in items:
|
||||||
|
print(f" {c('[' + key + ']', 'cyan')} {self._tr(label)}")
|
||||||
|
print(c(_rule(), "dim"))
|
||||||
|
return _ask(self._tr("menu_prompt")).lower()
|
||||||
|
|
||||||
|
# ------------------------------------------------------------ key state
|
||||||
|
def _ensure_key(self) -> bool:
|
||||||
|
"""Make sure a key is loaded, offering to create one if none exists.
|
||||||
|
|
||||||
|
Searches the instance's loaded key, then the remembered file, then
|
||||||
|
the default name.
|
||||||
|
"""
|
||||||
|
if self.cc.loaded:
|
||||||
|
return True
|
||||||
|
|
||||||
|
path = (
|
||||||
|
self.cc.key_file
|
||||||
|
or self.key_file
|
||||||
|
or DEFAULT_KEY_FILE
|
||||||
|
)
|
||||||
|
self.key_file = path
|
||||||
|
|
||||||
|
if not os.path.exists(path):
|
||||||
|
if _ask_yes_no(self._tr("prompt_create_if_missing"), self.lang):
|
||||||
|
return self.action_keygen()
|
||||||
|
return False
|
||||||
|
|
||||||
|
try:
|
||||||
|
pwd = self.key_password or _ask_secret(self._tr("prompt_key_password"))
|
||||||
|
self.cc.load(path, pwd)
|
||||||
|
self.key_password = pwd
|
||||||
|
print(c(f"{self._tr('key_loaded')}: {path}", "green"))
|
||||||
|
return True
|
||||||
|
except ChaosCryptError as exc:
|
||||||
|
self._print_error(exc)
|
||||||
|
return False
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- actions
|
||||||
|
def action_encrypt(self) -> None:
|
||||||
|
if not self._ensure_key():
|
||||||
|
return
|
||||||
|
text = _ask(self._tr("prompt_plaintext"))
|
||||||
|
if not text:
|
||||||
|
print(c(" " + self._tr("cancelled"), "dim"))
|
||||||
|
return
|
||||||
|
pwd = _ask_secret(self._tr("prompt_user_password"))
|
||||||
|
try:
|
||||||
|
ct = self.cc.encrypt(text, pwd)
|
||||||
|
print()
|
||||||
|
print(c(f"{self._tr('result_ciphertext')}:", "green", "bold"))
|
||||||
|
print(c(ct, "cyan"))
|
||||||
|
except ChaosCryptError as exc:
|
||||||
|
self._print_error(exc)
|
||||||
|
|
||||||
|
def action_decrypt(self) -> None:
|
||||||
|
if not self._ensure_key():
|
||||||
|
return
|
||||||
|
text = _ask(self._tr("prompt_ciphertext"))
|
||||||
|
if not text:
|
||||||
|
print(c(" " + self._tr("cancelled"), "dim"))
|
||||||
|
return
|
||||||
|
pwd = _ask_secret(self._tr("prompt_user_password"))
|
||||||
|
try:
|
||||||
|
pt = self.cc.decrypt(text, pwd)
|
||||||
|
print()
|
||||||
|
print(c(f"{self._tr('result_plaintext')}:", "green", "bold"))
|
||||||
|
print(c(pt, "cyan"))
|
||||||
|
except ChaosCryptError as exc:
|
||||||
|
self._print_error(exc)
|
||||||
|
|
||||||
|
def action_encrypt_file(self) -> None:
|
||||||
|
if not self._ensure_key():
|
||||||
|
return
|
||||||
|
src = _ask(self._tr("prompt_src_file"))
|
||||||
|
if not src or not os.path.exists(src):
|
||||||
|
print(c(f" {self._tr('failed')}: {src}", "red"))
|
||||||
|
return
|
||||||
|
dst = _ask(self._tr("prompt_dst_file")) or None
|
||||||
|
pwd = _ask_secret(self._tr("prompt_user_password"))
|
||||||
|
try:
|
||||||
|
out = self.cc.encrypt_file(src, pwd, dst)
|
||||||
|
print(c(f"{self._tr('file_written')}: {out}", "green"))
|
||||||
|
except ChaosCryptError as exc:
|
||||||
|
self._print_error(exc)
|
||||||
|
|
||||||
|
def action_decrypt_file(self) -> None:
|
||||||
|
if not self._ensure_key():
|
||||||
|
return
|
||||||
|
src = _ask(self._tr("prompt_src_file"))
|
||||||
|
if not src or not os.path.exists(src):
|
||||||
|
print(c(f" {self._tr('failed')}: {src}", "red"))
|
||||||
|
return
|
||||||
|
dst = _ask(self._tr("prompt_dst_file")) or None
|
||||||
|
pwd = _ask_secret(self._tr("prompt_user_password"))
|
||||||
|
try:
|
||||||
|
out = self.cc.decrypt_file(src, pwd, dst)
|
||||||
|
print(c(f"{self._tr('file_written')}: {out}", "green"))
|
||||||
|
except ChaosCryptError as exc:
|
||||||
|
self._print_error(exc)
|
||||||
|
|
||||||
|
def action_keygen(self) -> bool:
|
||||||
|
default = self.cc.key_file or self.key_file or DEFAULT_KEY_FILE
|
||||||
|
path = _ask(self._tr("prompt_key_file"), default)
|
||||||
|
|
||||||
|
overwrite = False
|
||||||
|
if os.path.exists(path):
|
||||||
|
if not _ask_yes_no(self._tr("prompt_overwrite"), self.lang):
|
||||||
|
print(c(" " + self._tr("cancelled"), "dim"))
|
||||||
|
return False
|
||||||
|
overwrite = True
|
||||||
|
|
||||||
|
pwd = _ask_secret(self._tr("prompt_key_password_new"))
|
||||||
|
if not pwd:
|
||||||
|
print(c(" " + self._tr("failed"), "red"))
|
||||||
|
return False
|
||||||
|
confirm = _ask_secret(self._tr("prompt_key_password_confirm"))
|
||||||
|
if pwd != confirm:
|
||||||
|
print(c(" ChaosCrypt_ERR_PasswordMismatch_E007", "red"))
|
||||||
|
return False
|
||||||
|
|
||||||
|
try:
|
||||||
|
out = self.cc.create_key(pwd, path, overwrite=overwrite)
|
||||||
|
self.key_file = out
|
||||||
|
self.key_password = pwd
|
||||||
|
print(c(f"{self._tr('key_saved')}: {out}", "green"))
|
||||||
|
return True
|
||||||
|
except ChaosCryptError as exc:
|
||||||
|
self._print_error(exc)
|
||||||
|
return False
|
||||||
|
|
||||||
|
def action_loadkey(self) -> None:
|
||||||
|
default = self.cc.key_file or self.key_file or DEFAULT_KEY_FILE
|
||||||
|
path = _ask(self._tr("prompt_key_file"), default)
|
||||||
|
pwd = _ask_secret(self._tr("prompt_key_password"))
|
||||||
|
try:
|
||||||
|
self.cc.load(path, pwd)
|
||||||
|
self.key_file = path
|
||||||
|
self.key_password = pwd
|
||||||
|
print(c(f"{self._tr('key_loaded')}: {path}", "green"))
|
||||||
|
except ChaosCryptError as exc:
|
||||||
|
self._print_error(exc)
|
||||||
|
|
||||||
|
def action_keyinfo(self) -> None:
|
||||||
|
if not self._ensure_key():
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
info = self.cc.info()
|
||||||
|
except ChaosCryptError as exc:
|
||||||
|
self._print_error(exc)
|
||||||
|
return
|
||||||
|
|
||||||
|
rows = [
|
||||||
|
("info_key_file", info["key_file"]),
|
||||||
|
("info_version", info["version"]),
|
||||||
|
("info_upper", info["upper_mapping"]),
|
||||||
|
("info_lower", info["lower_mapping"]),
|
||||||
|
("info_digit", "".join(info["digit_mapping"].values())),
|
||||||
|
("info_equal", "".join(info["equal_mapping"].values())),
|
||||||
|
("info_flip", info["flip_pattern"]),
|
||||||
|
("info_long_key",
|
||||||
|
f"{info['long_key_length']} {self._tr('characters')}"),
|
||||||
|
("info_short_key",
|
||||||
|
f"{info['short_key_length']} {self._tr('characters')}"),
|
||||||
|
("info_loaded", self._tr("yes")),
|
||||||
|
]
|
||||||
|
print()
|
||||||
|
print(c(_rule(), "dim"))
|
||||||
|
for key, val in rows:
|
||||||
|
print(f" {c(self._tr(key), 'bold'):<38} {val}")
|
||||||
|
print(c(_rule(), "dim"))
|
||||||
|
|
||||||
|
def action_chpwd(self) -> None:
|
||||||
|
default = self.cc.key_file or self.key_file or DEFAULT_KEY_FILE
|
||||||
|
path = _ask(self._tr("prompt_key_file"), default)
|
||||||
|
if not os.path.exists(path):
|
||||||
|
print(c(" ChaosCrypt_ERR_KeyFileNotFound_E001", "red"))
|
||||||
|
return
|
||||||
|
old = _ask_secret(self._tr("prompt_key_password_old"))
|
||||||
|
new = _ask_secret(self._tr("prompt_key_password_new"))
|
||||||
|
confirm = _ask_secret(self._tr("prompt_key_password_confirm"))
|
||||||
|
if new != confirm:
|
||||||
|
print(c(" ChaosCrypt_ERR_PasswordMismatch_E007", "red"))
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
out = self.cc.change_key_password(old, new, path)
|
||||||
|
self.key_password = new
|
||||||
|
print(c(f"{self._tr('key_password_changed')}: {out}", "green"))
|
||||||
|
except ChaosCryptError as exc:
|
||||||
|
self._print_error(exc)
|
||||||
|
|
||||||
|
def action_lang(self) -> None:
|
||||||
|
codes = list(LANG_NAMES.keys())
|
||||||
|
print()
|
||||||
|
for i, (code, name) in enumerate(LANG_NAMES.items(), 1):
|
||||||
|
mark = "*" if code == self.lang else " "
|
||||||
|
print(f" {c('[' + str(i) + ']', 'cyan')} {mark} {name} ({code})")
|
||||||
|
|
||||||
|
default_index = str(codes.index(self.lang) + 1) if self.lang in codes else "1"
|
||||||
|
choice = _ask("Language", default_index)
|
||||||
|
try:
|
||||||
|
idx = int(choice) - 1
|
||||||
|
if 0 <= idx < len(codes):
|
||||||
|
self.lang = codes[idx]
|
||||||
|
except ValueError:
|
||||||
|
if choice in codes:
|
||||||
|
self.lang = choice
|
||||||
|
print(c(f" -> {LANG_NAMES[self.lang]}", "green"))
|
||||||
|
|
||||||
|
def action_about(self) -> None:
|
||||||
|
print()
|
||||||
|
print(c(self._tr("about_body"), "cyan"))
|
||||||
|
|
||||||
|
# ------------------------------------------------------------- main loop
|
||||||
|
def run(self) -> int:
|
||||||
|
while True:
|
||||||
|
self.banner()
|
||||||
|
try:
|
||||||
|
choice = self.menu()
|
||||||
|
except _Abort:
|
||||||
|
print()
|
||||||
|
print(c(self._tr("bye"), "green"))
|
||||||
|
return 0
|
||||||
|
|
||||||
|
try:
|
||||||
|
if choice == "1":
|
||||||
|
self.action_encrypt()
|
||||||
|
elif choice == "2":
|
||||||
|
self.action_decrypt()
|
||||||
|
elif choice == "3":
|
||||||
|
self.action_encrypt_file()
|
||||||
|
elif choice == "4":
|
||||||
|
self.action_decrypt_file()
|
||||||
|
elif choice == "5":
|
||||||
|
self.action_keygen()
|
||||||
|
elif choice == "6":
|
||||||
|
self.action_loadkey()
|
||||||
|
elif choice == "7":
|
||||||
|
self.action_keyinfo()
|
||||||
|
elif choice == "8":
|
||||||
|
self.action_chpwd()
|
||||||
|
elif choice == "9":
|
||||||
|
self.action_lang()
|
||||||
|
elif choice in ("a", "about"):
|
||||||
|
self.action_about()
|
||||||
|
elif choice in ("q", "quit", "exit"):
|
||||||
|
print()
|
||||||
|
print(c(self._tr("bye"), "green"))
|
||||||
|
return 0
|
||||||
|
else:
|
||||||
|
print(c(" " + self._tr("menu_invalid"), "yellow"))
|
||||||
|
continue
|
||||||
|
except _Abort:
|
||||||
|
print(c(" " + self._tr("cancelled"), "dim"))
|
||||||
|
continue
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
print()
|
||||||
|
print(c(self._tr("bye"), "green"))
|
||||||
|
return 0
|
||||||
|
|
||||||
|
_pause(self.lang)
|
||||||
|
|
||||||
|
|
||||||
|
def run_tui(lang: str = DEFAULT_LANG,
|
||||||
|
key_file: str = DEFAULT_KEY_FILE) -> int:
|
||||||
|
"""Launch the interactive UI and return the process exit code."""
|
||||||
|
try:
|
||||||
|
return TUI(lang=lang, key_file=key_file).run()
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
print()
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__": # pragma: no cover
|
||||||
|
sys.exit(run_tui())
|
||||||
+463
@@ -0,0 +1,463 @@
|
|||||||
|
# API Reference
|
||||||
|
|
||||||
|
Complete reference for the `chaoscrypt` Python API.
|
||||||
|
|
||||||
|
```python
|
||||||
|
from chaoscrypt import ChaosCrypt # high-level facade
|
||||||
|
from chaoscrypt import ChaosCryptCore # raw algorithm
|
||||||
|
from chaoscrypt import ChaosCryptError # base error class
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Package contents
|
||||||
|
|
||||||
|
| Name | Kind | Description |
|
||||||
|
|---|---|---|
|
||||||
|
| `ChaosCrypt` | class | Key file management plus encryption helpers |
|
||||||
|
| `ChaosCryptCore` | class | The algorithm, with no file handling |
|
||||||
|
| `ChaosCryptError` | exception | Base class for every error raised |
|
||||||
|
| `encrypt` | function | One-shot encrypt using a key file |
|
||||||
|
| `decrypt` | function | One-shot decrypt using a key file |
|
||||||
|
| `create_key` | function | One-shot key file generation |
|
||||||
|
| `DEFAULT_KEY_FILE` | constant | `"encryption.key"` |
|
||||||
|
| `KEYFILE_VERSION` | constant | On-disk key file format version (`1`) |
|
||||||
|
| `__version__` | constant | Library version string |
|
||||||
|
| `__license__` | constant | `"MIT"` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## `class ChaosCrypt`
|
||||||
|
|
||||||
|
The facade most callers should use. Wraps key file handling around
|
||||||
|
`ChaosCryptCore`.
|
||||||
|
|
||||||
|
### Constructor
|
||||||
|
|
||||||
|
```python
|
||||||
|
ChaosCrypt(
|
||||||
|
key_file: str | None = None,
|
||||||
|
key_password: str | None = None,
|
||||||
|
*,
|
||||||
|
auto_load: bool = False,
|
||||||
|
default_key_file: str = "encryption.key",
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
| Parameter | Type | Default | Description |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `key_file` | `str \| None` | `None` | Path to a key file |
|
||||||
|
| `key_password` | `str \| None` | `None` | Password protecting that key file |
|
||||||
|
| `auto_load` | `bool` | `False` | Load the key file during construction |
|
||||||
|
| `default_key_file` | `str` | `"encryption.key"` | File name used when `key_file` is omitted |
|
||||||
|
|
||||||
|
When `auto_load=True` and the file cannot be loaded, the corresponding
|
||||||
|
exception is raised from the constructor.
|
||||||
|
|
||||||
|
```python
|
||||||
|
cc = ChaosCrypt("my.key", "key-password", auto_load=True)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Properties
|
||||||
|
|
||||||
|
#### `loaded -> bool`
|
||||||
|
|
||||||
|
Whether usable key material is currently held in memory.
|
||||||
|
|
||||||
|
```python
|
||||||
|
cc = ChaosCrypt()
|
||||||
|
assert cc.loaded is False
|
||||||
|
cc.create_key("pwd", "my.key")
|
||||||
|
assert cc.loaded is True
|
||||||
|
```
|
||||||
|
|
||||||
|
#### `is_loaded() -> bool`
|
||||||
|
|
||||||
|
Method form of the same check, for call sites that read better that way.
|
||||||
|
|
||||||
|
### Key management
|
||||||
|
|
||||||
|
#### `create_key(key_password, key_file=None, *, overwrite=False) -> str`
|
||||||
|
|
||||||
|
Generate a fresh key file.
|
||||||
|
|
||||||
|
| Parameter | Type | Default | Description |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `key_password` | `str` | required | Password that will protect the file |
|
||||||
|
| `key_file` | `str \| None` | `None` | Destination; defaults to the configured name |
|
||||||
|
| `overwrite` | `bool` | `False` | Replace an existing file rather than refusing |
|
||||||
|
|
||||||
|
**Returns** the path written.
|
||||||
|
|
||||||
|
**Raises** `ChaosCrypt_ERR_EmptyPassword_E006` for an empty password, or
|
||||||
|
`ChaosCrypt_ERR_KeyFileExists_E005` if the file exists and `overwrite` is
|
||||||
|
false.
|
||||||
|
|
||||||
|
```python
|
||||||
|
cc = ChaosCrypt()
|
||||||
|
cc.create_key("strong-password", "my.key")
|
||||||
|
cc.create_key("strong-password", "my.key", overwrite=True) # replace
|
||||||
|
```
|
||||||
|
|
||||||
|
Aliases `generate_keys` and `create_key_file` are provided for readability.
|
||||||
|
|
||||||
|
#### `load(key_file=None, key_password=None) -> ChaosCrypt`
|
||||||
|
|
||||||
|
Load a key file from disk. Falls back to the instance attributes, then to the
|
||||||
|
default file name. Returns `self`, so calls can be chained.
|
||||||
|
|
||||||
|
**Raises** `ChaosCrypt_ERR_KeyFileNotFound_E001`,
|
||||||
|
`ChaosCrypt_ERR_EmptyPassword_E006`, `ChaosCrypt_ERR_KeyPasswordIncorrect_E003`,
|
||||||
|
or `ChaosCrypt_ERR_KeyFileCorrupted_E002`.
|
||||||
|
|
||||||
|
```python
|
||||||
|
cc = ChaosCrypt().load("my.key", "key-password")
|
||||||
|
```
|
||||||
|
|
||||||
|
#### `load_from_text(key_text, key_password) -> ChaosCrypt`
|
||||||
|
|
||||||
|
Load key material directly from a key file's contents, without touching disk.
|
||||||
|
Useful when the key is stored in a password manager or retrieved from a vault.
|
||||||
|
|
||||||
|
```python
|
||||||
|
text = vault.read("chaoscrypt-key")
|
||||||
|
cc = ChaosCrypt().load_from_text(text, "key-password")
|
||||||
|
```
|
||||||
|
|
||||||
|
#### `export_key_text(key_password) -> str`
|
||||||
|
|
||||||
|
Generate key material and return it as text, writing nothing to disk. The
|
||||||
|
instance becomes loaded and immediately usable.
|
||||||
|
|
||||||
|
```python
|
||||||
|
cc = ChaosCrypt()
|
||||||
|
text = cc.export_key_text("key-password")
|
||||||
|
vault.write("chaoscrypt-key", text)
|
||||||
|
token = cc.encrypt("data", "encryption-password") # usable right away
|
||||||
|
```
|
||||||
|
|
||||||
|
#### `change_key_password(old_password, new_password, key_file=None) -> str`
|
||||||
|
|
||||||
|
Re-wrap an existing key file under a new password. The key material is
|
||||||
|
unchanged, so previously encrypted data remains readable.
|
||||||
|
|
||||||
|
**Raises** `ChaosCrypt_ERR_EmptyPassword_E006` if the new password is empty,
|
||||||
|
or `ChaosCrypt_ERR_KeyFileNotFound_E001` / `ChaosCrypt_ERR_KeyPasswordIncorrect_E003`
|
||||||
|
if the old password does not unlock the file.
|
||||||
|
|
||||||
|
```python
|
||||||
|
cc.change_key_password("old-password", "new-password", "my.key")
|
||||||
|
```
|
||||||
|
|
||||||
|
#### `info() -> dict`
|
||||||
|
|
||||||
|
Return a summary of the loaded key material.
|
||||||
|
|
||||||
|
```python
|
||||||
|
{
|
||||||
|
"key_file": "my.key",
|
||||||
|
"version": 1,
|
||||||
|
"upper_mapping": "QWERTYUIOPASDFGHJKLZXCVBNM",
|
||||||
|
"lower_mapping": "qwertyuiopasdfghjklzxcvbnm",
|
||||||
|
"digit_mapping": {...},
|
||||||
|
"equal_mapping": {...},
|
||||||
|
"flip_pattern": [1, 0, 1, 0, 0, 1, 0, 0, 1, 0],
|
||||||
|
"long_key_length": 4096,
|
||||||
|
"short_key_length": 512,
|
||||||
|
"loaded": True,
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The substitution tables describe the structure of your key file. Treat the
|
||||||
|
result as sensitive.
|
||||||
|
|
||||||
|
**Raises** `ChaosCrypt_ERR_KeyNotLoaded_E004` if nothing is loaded.
|
||||||
|
|
||||||
|
### Encryption
|
||||||
|
|
||||||
|
#### `encrypt(plaintext, password) -> str`
|
||||||
|
|
||||||
|
Encrypt a string, returning a hexadecimal ciphertext.
|
||||||
|
|
||||||
|
```python
|
||||||
|
token = cc.encrypt("hello world", "encryption-password")
|
||||||
|
```
|
||||||
|
|
||||||
|
**Raises** `ChaosCrypt_ERR_KeyNotLoaded_E004`,
|
||||||
|
`ChaosCrypt_ERR_EmptyPassword_E006`, or `ChaosCrypt_ERR_EmptyPlaintext_E008`.
|
||||||
|
|
||||||
|
#### `decrypt(ciphertext, password) -> str`
|
||||||
|
|
||||||
|
Decrypt a hexadecimal ciphertext back into a string.
|
||||||
|
|
||||||
|
```python
|
||||||
|
plain = cc.decrypt(token, "encryption-password")
|
||||||
|
```
|
||||||
|
|
||||||
|
**Raises** `ChaosCrypt_ERR_MalformedCiphertext_E010` if the input is not
|
||||||
|
valid hexadecimal, or `ChaosCrypt_ERR_DecryptionFailed_E011` if the password
|
||||||
|
is wrong, the key file does not match, or the ciphertext was altered.
|
||||||
|
|
||||||
|
#### `encrypt_bytes(data, password) -> str`
|
||||||
|
|
||||||
|
Encrypt arbitrary binary data. Returns a hexadecimal ciphertext.
|
||||||
|
|
||||||
|
```python
|
||||||
|
raw = open("archive.zip", "rb").read()
|
||||||
|
token = cc.encrypt_bytes(raw, "encryption-password")
|
||||||
|
```
|
||||||
|
|
||||||
|
#### `decrypt_bytes(ciphertext, password) -> bytes`
|
||||||
|
|
||||||
|
Decrypt back into the original binary data.
|
||||||
|
|
||||||
|
```python
|
||||||
|
restored = cc.decrypt_bytes(token, "encryption-password")
|
||||||
|
open("archive.restored.zip", "wb").write(restored)
|
||||||
|
```
|
||||||
|
|
||||||
|
### File helpers
|
||||||
|
|
||||||
|
#### `encrypt_file(src, password, dst=None) -> str`
|
||||||
|
|
||||||
|
Encrypt a file on disk, writing UTF-8 hexadecimal ciphertext. When `dst` is
|
||||||
|
omitted, the output path is `src + ".cc"`. Returns the output path.
|
||||||
|
|
||||||
|
**Raises** `ChaosCrypt_ERR_FileReadFailed_E014` or
|
||||||
|
`ChaosCrypt_ERR_FileWriteFailed_E015`.
|
||||||
|
|
||||||
|
#### `decrypt_file(src, password, dst=None) -> str`
|
||||||
|
|
||||||
|
Decrypt a `.cc` ciphertext file, restoring the original bytes. When `dst` is
|
||||||
|
omitted, a trailing `.cc` is stripped, or `.out` is appended. Returns the
|
||||||
|
output path.
|
||||||
|
|
||||||
|
```python
|
||||||
|
cc.encrypt_file("report.pdf", "encryption-password")
|
||||||
|
cc.decrypt_file("report.pdf.cc", "encryption-password")
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## `class ChaosCryptCore`
|
||||||
|
|
||||||
|
The algorithm itself, with no file handling and no user interaction. Use it
|
||||||
|
when you manage key material yourself — for example by loading it from a
|
||||||
|
database or a secrets service.
|
||||||
|
|
||||||
|
```python
|
||||||
|
from chaoscrypt import ChaosCryptCore
|
||||||
|
|
||||||
|
core = ChaosCryptCore()
|
||||||
|
core.generate_keymaterial() # random key material
|
||||||
|
token = core.encrypt_text("hello", "password")
|
||||||
|
assert core.decrypt_text(token, "password") == "hello"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Key material methods
|
||||||
|
|
||||||
|
| Method | Description |
|
||||||
|
|---|---|
|
||||||
|
| `generate_keymaterial() -> dict` | Generate a complete random key set; leaves the instance loaded |
|
||||||
|
| `serialize_keys(key_password, save_path) -> str` | Generate and write a key file |
|
||||||
|
| `load_keys(key_file, key_password) -> None` | Load a key file from disk |
|
||||||
|
| `load_keys_from_text(text, key_password) -> None` | Load from key file contents |
|
||||||
|
|
||||||
|
### Encryption methods
|
||||||
|
|
||||||
|
| Method | Description |
|
||||||
|
|---|---|
|
||||||
|
| `encrypt_text(plaintext, password) -> str` | Encrypt a string to hexadecimal |
|
||||||
|
| `decrypt_text(ciphertext, password) -> str` | Decrypt to a string |
|
||||||
|
| `encrypt_bytes(data, password) -> str` | Encrypt binary data |
|
||||||
|
| `decrypt_bytes(ciphertext, password) -> bytes` | Decrypt to binary data |
|
||||||
|
|
||||||
|
### Attributes
|
||||||
|
|
||||||
|
Set by `generate_keymaterial()` or one of the `load_keys*` methods:
|
||||||
|
|
||||||
|
| Attribute | Type | Description |
|
||||||
|
|---|---|---|
|
||||||
|
| `keys_loaded` | `bool` | Whether key material is present |
|
||||||
|
| `upper_mapping` | `str` | Bijection over `A–Z`, 26 characters |
|
||||||
|
| `lower_mapping` | `str` | Bijection over `a–z`, 26 characters |
|
||||||
|
| `digit_mapping` | `dict` | Digits `0–9` to distinct alphanumerics |
|
||||||
|
| `equal_mapping` | `dict` | Padding counts `0–3` to distinct characters |
|
||||||
|
| `flip_pattern` | `list[int]` | Ten bits controlling case flipping |
|
||||||
|
| `long_key` | `str` | 4096 hexadecimal nibbles |
|
||||||
|
| `short_key` | `str` | 512 hexadecimal nibbles |
|
||||||
|
|
||||||
|
Attributes prefixed with an underscore are internal and not covered by the
|
||||||
|
compatibility guarantee.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Error hierarchy
|
||||||
|
|
||||||
|
Every error is a subclass of `ChaosCryptError`, so a single `except` clause
|
||||||
|
catches everything:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from chaoscrypt import ChaosCryptError
|
||||||
|
|
||||||
|
try:
|
||||||
|
cc.decrypt(token, "password")
|
||||||
|
except ChaosCryptError as e:
|
||||||
|
print(e.message) # ChaosCrypt_ERR_DecryptionFailed_E011
|
||||||
|
print(e.code) # E011
|
||||||
|
print(e.detail) # DecryptionFailed
|
||||||
|
```
|
||||||
|
|
||||||
|
| Code | Class | Raised when |
|
||||||
|
|---|---|---|
|
||||||
|
| `E001` | `ChaosCrypt_ERR_KeyFileNotFound_E001` | The key file does not exist |
|
||||||
|
| `E002` | `ChaosCrypt_ERR_KeyFileCorrupted_E002` | The key file cannot be parsed |
|
||||||
|
| `E003` | `ChaosCrypt_ERR_KeyPasswordIncorrect_E003` | Wrong key file password |
|
||||||
|
| `E004` | `ChaosCrypt_ERR_KeyNotLoaded_E004` | Operation needs a key, none loaded |
|
||||||
|
| `E005` | `ChaosCrypt_ERR_KeyFileExists_E005` | File exists and overwrite not permitted |
|
||||||
|
| `E006` | `ChaosCrypt_ERR_EmptyPassword_E006` | A required password was missing |
|
||||||
|
| `E007` | `ChaosCrypt_ERR_PasswordMismatch_E007` | Two password entries differed |
|
||||||
|
| `E008` | `ChaosCrypt_ERR_EmptyPlaintext_E008` | The plaintext was empty |
|
||||||
|
| `E009` | `ChaosCrypt_ERR_EmptyCiphertext_E009` | The ciphertext was empty |
|
||||||
|
| `E010` | `ChaosCrypt_ERR_MalformedCiphertext_E010` | Not valid hexadecimal, or odd length |
|
||||||
|
| `E011` | `ChaosCrypt_ERR_DecryptionFailed_E011` | Decryption produced invalid data |
|
||||||
|
| `E012` | `ChaosCrypt_ERR_EncodingFailed_E012` | Base64 or UTF-8 conversion failed |
|
||||||
|
| `E013` | `ChaosCrypt_ERR_InvalidArgument_E013` | An argument had an invalid value |
|
||||||
|
| `E014` | `ChaosCrypt_ERR_FileReadFailed_E014` | Reading a file failed |
|
||||||
|
| `E015` | `ChaosCrypt_ERR_FileWriteFailed_E015` | Writing a file failed |
|
||||||
|
| `E016` | `ChaosCrypt_ERR_UnsupportedKeyVersion_E016` | Key file version not supported |
|
||||||
|
|
||||||
|
Codes are stable and safe to branch on. The human-readable portion of the
|
||||||
|
message may be reworded between minor releases.
|
||||||
|
|
||||||
|
### Custom details
|
||||||
|
|
||||||
|
Each error accepts an optional `detail` and `code`, which is useful for
|
||||||
|
adding context such as a file path:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from chaoscrypt.errors import ChaosCrypt_ERR_KeyFileNotFound_E001
|
||||||
|
|
||||||
|
raise ChaosCrypt_ERR_KeyFileNotFound_E001(
|
||||||
|
detail="KeyFileNotFound:/etc/keys/prod.key", code="E001"
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Module-level functions
|
||||||
|
|
||||||
|
Convenience wrappers for scripts that perform a single operation.
|
||||||
|
|
||||||
|
### `encrypt(plaintext, password, key_file="encryption.key", key_password=None) -> str`
|
||||||
|
|
||||||
|
Load a key file and encrypt in one call. When `key_password` is omitted it
|
||||||
|
falls back to `password`, which suits setups where one secret guards both
|
||||||
|
layers.
|
||||||
|
|
||||||
|
```python
|
||||||
|
import chaoscrypt
|
||||||
|
|
||||||
|
token = chaoscrypt.encrypt("data", "user-pwd", "my.key", "key-pwd")
|
||||||
|
```
|
||||||
|
|
||||||
|
### `decrypt(ciphertext, password, key_file="encryption.key", key_password=None) -> str`
|
||||||
|
|
||||||
|
The inverse of the above.
|
||||||
|
|
||||||
|
```python
|
||||||
|
plain = chaoscrypt.decrypt(token, "user-pwd", "my.key", "key-pwd")
|
||||||
|
```
|
||||||
|
|
||||||
|
### `create_key(key_password, key_file="encryption.key", *, overwrite=False) -> str`
|
||||||
|
|
||||||
|
Generate a key file in one call. Returns the path written.
|
||||||
|
|
||||||
|
```python
|
||||||
|
chaoscrypt.create_key("key-pwd", "my.key")
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Complete example
|
||||||
|
|
||||||
|
```python
|
||||||
|
"""Encrypt a config file, then restore it."""
|
||||||
|
|
||||||
|
from chaoscrypt import ChaosCrypt, ChaosCryptError
|
||||||
|
|
||||||
|
KEY_FILE = "secrets.key"
|
||||||
|
KEY_PASSWORD = "key-file-password"
|
||||||
|
DATA_PASSWORD = "encryption-password"
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
cc = ChaosCrypt()
|
||||||
|
|
||||||
|
# Reuse an existing key file, or create one on first run.
|
||||||
|
try:
|
||||||
|
cc.load(KEY_FILE, KEY_PASSWORD)
|
||||||
|
except ChaosCryptError:
|
||||||
|
cc.create_key(KEY_PASSWORD, KEY_FILE)
|
||||||
|
|
||||||
|
# Text round trip.
|
||||||
|
token = cc.encrypt("API_KEY=abc123", DATA_PASSWORD)
|
||||||
|
print(f"Ciphertext: {token}")
|
||||||
|
print(f"Restored: {cc.decrypt(token, DATA_PASSWORD)}")
|
||||||
|
|
||||||
|
# File round trip.
|
||||||
|
cc.encrypt_file("config.json", DATA_PASSWORD)
|
||||||
|
cc.decrypt_file("config.json.cc", DATA_PASSWORD, "config.restored.json")
|
||||||
|
|
||||||
|
# A wrong password is reported clearly.
|
||||||
|
try:
|
||||||
|
cc.decrypt(token, "not-the-password")
|
||||||
|
except ChaosCryptError as e:
|
||||||
|
print(f"Rejected as expected: {e} (code {e.code})")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Thread safety
|
||||||
|
|
||||||
|
`ChaosCrypt` and `ChaosCryptCore` instances are **not** thread-safe. Key
|
||||||
|
material is mutable state on the instance, and loading a key while an
|
||||||
|
encryption is in progress is a data race.
|
||||||
|
|
||||||
|
Either use one instance per thread, or create the instance once and guard it
|
||||||
|
with a lock:
|
||||||
|
|
||||||
|
```python
|
||||||
|
import threading
|
||||||
|
from chaoscrypt import ChaosCrypt
|
||||||
|
|
||||||
|
cc = ChaosCrypt().load("my.key", "key-password")
|
||||||
|
lock = threading.Lock()
|
||||||
|
|
||||||
|
|
||||||
|
def encrypt_safely(text: str, password: str) -> str:
|
||||||
|
with lock:
|
||||||
|
return cc.encrypt(text, password)
|
||||||
|
```
|
||||||
|
|
||||||
|
The module-level functions create a fresh instance on each call, so they are
|
||||||
|
safe to use concurrently without a lock — at the cost of reloading the key
|
||||||
|
file each time.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Compatibility guarantee
|
||||||
|
|
||||||
|
Within a major version:
|
||||||
|
|
||||||
|
- the public API described here will not change incompatibly;
|
||||||
|
- error codes will not be renumbered;
|
||||||
|
- the key file format will not change;
|
||||||
|
- ciphertexts produced by any earlier release will continue to decrypt.
|
||||||
|
|
||||||
|
The underscore-prefixed members of `ChaosCryptCore` are internal and may
|
||||||
|
change without notice.
|
||||||
@@ -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
|
||||||
|
```
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
# Documentation
|
||||||
|
|
||||||
|
Reference material for ChaosCrypt.
|
||||||
|
|
||||||
|
| Document | Contents |
|
||||||
|
|---|---|
|
||||||
|
| [API.md](API.md) | Complete Python API reference |
|
||||||
|
| [CLI.md](CLI.md) | Command line reference, pipelines, troubleshooting |
|
||||||
|
| [ARCHITECTURE.md](ARCHITECTURE.md) | Module map, data flow, design decisions |
|
||||||
|
| [BUILDING.md](BUILDING.md) | Building, testing and releasing |
|
||||||
|
| [../SECURITY.md](../SECURITY.md) | Design, key space, threat model, attack analysis |
|
||||||
|
| [../README.md](../README.md) | Project overview and quick start |
|
||||||
|
| [../CHANGELOG.md](../CHANGELOG.md) | Release history |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Where to start
|
||||||
|
|
||||||
|
**Evaluating whether ChaosCrypt suits your use case**
|
||||||
|
Read the [Scope](../README.md#scope) section of the README, then
|
||||||
|
[SECURITY.md](../SECURITY.md) for the full analysis.
|
||||||
|
|
||||||
|
**Using the library in Python**
|
||||||
|
[API.md](API.md) — start with the `ChaosCrypt` facade and the error table.
|
||||||
|
|
||||||
|
**Using the command line**
|
||||||
|
[CLI.md](CLI.md) — covers every subcommand, plus pipelines and shell aliases.
|
||||||
|
|
||||||
|
**Understanding how it works**
|
||||||
|
[ARCHITECTURE.md](ARCHITECTURE.md) for the code structure, and
|
||||||
|
[SECURITY.md §3](../SECURITY.md) for the algorithm itself.
|
||||||
|
|
||||||
|
**Contributing or building a release**
|
||||||
|
[BUILDING.md](BUILDING.md).
|
||||||
+116
@@ -0,0 +1,116 @@
|
|||||||
|
[build-system]
|
||||||
|
requires = ["setuptools>=77", "wheel"]
|
||||||
|
build-backend = "setuptools.build_meta"
|
||||||
|
|
||||||
|
[project]
|
||||||
|
name = "chaoscrypt"
|
||||||
|
version = "2.1.6"
|
||||||
|
description = "A chaos-based obfuscation cipher with a bilingual TUI, a full CLI and a clean Python API."
|
||||||
|
readme = "README.md"
|
||||||
|
requires-python = ">=3.8"
|
||||||
|
license = "MIT"
|
||||||
|
license-files = ["LICENSE"]
|
||||||
|
authors = [
|
||||||
|
{ name = "Dvs (DvsXT)", email = "dvs6666@163.com" },
|
||||||
|
]
|
||||||
|
maintainers = [
|
||||||
|
{ name = "Dvs (DvsXT)", email = "dvs6666@163.com" },
|
||||||
|
]
|
||||||
|
keywords = [
|
||||||
|
"encryption",
|
||||||
|
"cipher",
|
||||||
|
"obfuscation",
|
||||||
|
"chaos",
|
||||||
|
"xor",
|
||||||
|
"keystream",
|
||||||
|
"tui",
|
||||||
|
"cli",
|
||||||
|
"education",
|
||||||
|
]
|
||||||
|
classifiers = [
|
||||||
|
"Development Status :: 5 - Production/Stable",
|
||||||
|
"Environment :: Console",
|
||||||
|
"Intended Audience :: Developers",
|
||||||
|
"Intended Audience :: Education",
|
||||||
|
"Intended Audience :: End Users/Desktop",
|
||||||
|
"Natural Language :: Chinese (Simplified)",
|
||||||
|
"Natural Language :: English",
|
||||||
|
"Operating System :: OS Independent",
|
||||||
|
"Programming Language :: Python :: 3",
|
||||||
|
"Programming Language :: Python :: 3 :: Only",
|
||||||
|
"Programming Language :: Python :: 3.8",
|
||||||
|
"Programming Language :: Python :: 3.9",
|
||||||
|
"Programming Language :: Python :: 3.10",
|
||||||
|
"Programming Language :: Python :: 3.11",
|
||||||
|
"Programming Language :: Python :: 3.12",
|
||||||
|
"Programming Language :: Python :: 3.13",
|
||||||
|
"Topic :: Education",
|
||||||
|
"Topic :: Security :: Cryptography",
|
||||||
|
"Topic :: Utilities",
|
||||||
|
]
|
||||||
|
|
||||||
|
# No third-party runtime dependencies: works immediately after `pip install`.
|
||||||
|
dependencies = []
|
||||||
|
|
||||||
|
[project.optional-dependencies]
|
||||||
|
dev = [
|
||||||
|
"build>=1.0",
|
||||||
|
"twine>=4.0",
|
||||||
|
"pytest>=7.0",
|
||||||
|
"pytest-cov>=4.0",
|
||||||
|
]
|
||||||
|
|
||||||
|
[project.urls]
|
||||||
|
Homepage = "https://git.dvscloud.net/dvs/ChaosCrypt"
|
||||||
|
Documentation = "https://git.dvscloud.net/dvs/ChaosCrypt/src/branch/main/docs"
|
||||||
|
Source = "https://git.dvscloud.net/dvs/ChaosCrypt"
|
||||||
|
Changelog = "https://git.dvscloud.net/dvs/ChaosCrypt/src/branch/main/CHANGELOG.md"
|
||||||
|
"Security Policy" = "https://git.dvscloud.net/dvs/ChaosCrypt/src/branch/main/SECURITY.md"
|
||||||
|
"Issue Tracker" = "https://git.dvscloud.net/dvs/ChaosCrypt/issues"
|
||||||
|
|
||||||
|
[project.scripts]
|
||||||
|
chaoscrypt = "chaoscrypt.cli:cli_main"
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Layout
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# ChaosCrypt/ repository root: docs and build artefacts
|
||||||
|
# ├── README.md SECURITY.md LICENSE CHANGELOG.md
|
||||||
|
# ├── docs/
|
||||||
|
# ├── pyproject.toml
|
||||||
|
# ├── dist/
|
||||||
|
# └── chaoscrypt/ source tree
|
||||||
|
# ├── __init__.py the importable package
|
||||||
|
# ├── _core.py cli.py tui.py errors.py i18n.py
|
||||||
|
# ├── tests/
|
||||||
|
# ├── examples/
|
||||||
|
# └── legacy/
|
||||||
|
#
|
||||||
|
# The package sits alongside tests/, examples/ and legacy/ in the same
|
||||||
|
# directory, so the distribution contents are stated explicitly. Automatic
|
||||||
|
# discovery would treat those directories as namespace packages and ship them
|
||||||
|
# in the wheel.
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
[tool.setuptools]
|
||||||
|
py-modules = []
|
||||||
|
packages = ["chaoscrypt"]
|
||||||
|
|
||||||
|
[tool.setuptools.package-data]
|
||||||
|
chaoscrypt = ["py.typed"]
|
||||||
|
|
||||||
|
[tool.pytest.ini_options]
|
||||||
|
testpaths = ["chaoscrypt/tests"]
|
||||||
|
addopts = "-q"
|
||||||
|
filterwarnings = [
|
||||||
|
"error::DeprecationWarning:chaoscrypt.*",
|
||||||
|
]
|
||||||
|
|
||||||
|
[tool.coverage.run]
|
||||||
|
source = ["chaoscrypt"]
|
||||||
|
|
||||||
|
[tool.coverage.report]
|
||||||
|
exclude_lines = [
|
||||||
|
"pragma: no cover",
|
||||||
|
"if TYPE_CHECKING:",
|
||||||
|
"if __name__ == .__main__.:",
|
||||||
|
]
|
||||||
@@ -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