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:
@@ -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.
|
||||
Reference in New Issue
Block a user