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

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

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

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

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

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

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

329 lines
10 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# ChaosCrypt
**A chaos-based obfuscation cipher with a self-describing format, four
performance modes, a bilingual TUI, a full CLI, and a clean Python API.**
[![Python](https://img.shields.io/badge/python-3.8%2B-blue)](https://www.python.org/)
[![License](https://img.shields.io/badge/license-MIT-green)](LICENSE)
[![Dependencies](https://img.shields.io/badge/dependencies-none-brightgreen)](#installation)
---
## Scope
ChaosCrypt is an **unaudited, non-standardised** cipher. It is built for three
purposes:
| | Purpose | What it means in practice |
|---|---|---|
| 1 | **Obfuscation** | Making data unreadable to casual inspection |
| 2 | **Personal use** | Protecting your own notes, journals and backups |
| 3 | **Research & teaching** | Studying how layered obfuscation behaves |
**If you need standardised cryptography, use a standardised cipher.** AES-GCM
or ChaCha20-Poly1305 from a vetted library such as
[`cryptography`](https://cryptography.io) are the right tools for production
systems, regulated data, and long-lived secrets.
See [SECURITY.md](SECURITY.md) for the full design and threat analysis, and
[docs/FORMAT.md](docs/FORMAT.md) for the normative format specification.
---
## Every artefact describes itself
Each key file and ciphertext begins with a header that states how it was made.
A reader never has to be told the mode, the encoding, or anything else — it
reads them from the artefact.
```
69CES
385aeff1f4179a744c8fb0c5ae4702d325f6230d059f4251135c2536409dee93
{"alg":"chaoscrypt","kind":"ciphertext","mode":"turbo","out":"hex","mid":"bt",...}
2025ea4e4b4b93803f2ccadeaf318d1957ce42ff5409410f660348be96a4c0f2
<payload>
```
The consequence is deliberate: **input without a valid header is rejected**
(`E017`), rather than guessed at. A ciphertext decrypted under the wrong
parameters produces garbage that looks like a wrong password, and the header
removes that ambiguity entirely.
```python
from chaoscrypt import ChaosCrypt
cc = ChaosCrypt(key_file="my.key", key_password="key-file-password",
auto_load=True)
# whatever produced this, it will be read correctly
plain = cc.decrypt(open("message.ces").read(), "encryption-password")
```
---
## Performance modes
Four modes, selectable at construction, on the command line, and from the TUI.
| Mode | Algorithm | Ciphertext | Compatible with pre-4.2.6 material |
|---|---|---|---|
| `reference` | the original algorithm, character pipeline | 5.33x | payload identical |
| `fast` *(default)* | same algorithm, bulk operations | 5.33x | payload identical |
| `turbo` | SHAKE256 keystream, byte pipeline | 2.00x / 1.33x | no |
| `raw` | SHAKE256 plus the long-key layer | 2.00x / 1.33x | no |
`turbo` and `raw` take two extra settings:
| Setting | Values | Meaning |
|---|---|---|
| `encoding` | `hex` (default), `base64` | final output encoding: 2.00x or 1.33x expansion |
| `mid` | `bt` (default), `hex` | whether bytes or hexadecimal text are carried between the XOR layers |
```python
from chaoscrypt import ChaosCrypt
cc = ChaosCrypt(mode="raw", encoding="base64", mid="bt")
```
```bash
chaoscrypt encrypt "hello" -p pw -k my.key -P kp --mode raw --encoding base64
```
### Measured throughput
Hex output, `raw` mode, 1 MiB payloads and above:
| mid | Encrypt | Decrypt | Ciphertext |
|---|---:|---:|---:|
| `bt` (default) | **57–63 MB/s** | **61–73 MB/s** | 2.00x |
| `hex` | 18–21 MB/s | 18–23 MB/s | 8.00x |
Throughput holds steady from 64 KiB to 1 GiB, which is what a linear algorithm
looks like. Full figures, including the profiling behind them, are in
[docs/benchmark.md](docs/benchmark.md).
For scale: the original implementation managed **0.08 MB/s**, about twelve
seconds per megabyte.
---
## Reading artefacts from before 4.2.6
Artefacts written before the header existed have none. They are read through a
compatibility API, which synthesises a minimal header and then uses the ordinary
path — so the strict path stays strict, and there is no lenient branch inside
it.
```python
from chaoscrypt import ChaosCrypt
cc = ChaosCrypt(key_file="my.key", key_password="key-file-password",
auto_load=True)
# a ciphertext with no header
plain = cc.decrypt_legacy("72370655031311011c111f261365172716020b69",
"encryption-password")
# a key file with no header
cc.load_legacy_keys(open("old.key", encoding="utf-8").read(), "key-password")
# or modernise one, once
open("new.key", "w", encoding="utf-8").write(
cc.wrap_legacy(open("old.key", encoding="utf-8").read(), is_key=True)
)
```
`decrypt_legacy_auto` probes whether the artefact is a key file or a ciphertext,
so the caller does not have to know. See
[docs/FORMAT.md §12](docs/FORMAT.md) for the legacy standard.
---
## Installation
```bash
pip install chaoscrypt
```
**Requires** Python 3.8 or newer. No third-party runtime dependencies.
---
## Three ways to use it
### 1. As a library
```python
from chaoscrypt import ChaosCrypt
cc = ChaosCrypt()
cc.create_key("key-file-password", "my.key")
token = cc.encrypt("hello world", "encryption-password")
assert cc.decrypt(token, "encryption-password") == "hello world"
```
Binary data and files:
```python
cc = ChaosCrypt("my.key", "key-file-password", auto_load=True)
raw = open("photo.png", "rb").read()
open("photo.cc", "w").write(cc.encrypt_bytes(raw, "encryption-password"))
cc.encrypt_file("photo.png", "encryption-password") # -> photo.png.cc
cc.decrypt_file("photo.png.cc", "encryption-password") # -> photo.png
```
Error handling — every failure is a `ChaosCryptError` and renders as
`ChaosCrypt_ERR_<Detail>_<Code>`:
```python
from chaoscrypt import ChaosCrypt, ChaosCryptError
try:
ChaosCrypt().load("my.key", "wrong-password")
except ChaosCryptError as e:
print(e) # ChaosCrypt_ERR_KeyPasswordIncorrect_E003
print(e.code) # E003
```
### 2. As a command line tool
**No arguments** launches the interactive TUI. **With arguments** it is a
scriptable CLI:
```bash
chaoscrypt keygen -k my.key --key-pwd-env KEY_PWD
chaoscrypt encrypt "hello world" -p mypass -k my.key -P keypass
chaoscrypt decrypt "1a2b3c..." -p mypass -k my.key -P keypass
chaoscrypt file encrypt photo.png -p mypass -k my.key -P keypass
chaoscrypt info -k my.key -P keypass --json
chaoscrypt chpwd -k my.key -P oldpass --new-pwd newpass
```
`-p`/`--pwd` is the **encryption password**; `-P`/`--key-pwd` is the **key file
password**. Passwords may come inline, from an environment variable, or from a
file.
**Exit codes:** `0` success, `1` runtime error, `2` usage error. See
[docs/CLI.md](docs/CLI.md) for the full reference.
### 3. As an interactive TUI
```bash
chaoscrypt
```
```
+================================================================+
| ChaosCrypt - Chaos Obfuscation Cipher v4.2.6 |
+================================================================+
[*] Key file loaded my.key [fast]
------------------------------------------------------------------
Select an action
------------------------------------------------------------------
[1] Encrypt text
[2] Decrypt text
[3] Encrypt file
[4] Decrypt file
[5] Generate a new key file
[6] Load a key file
[7] Show key information
[8] Change key file password
[9] Switch language
[m] Performance mode
[e] Output encoding
[a] About / security notice
[q] Quit
------------------------------------------------------------------
```
Bilingual (option `[9]`), passwords are not echoed, and the interface degrades
cleanly when output is piped.
---
## Error codes
| Code | Meaning |
|---|---|
| `E001` | Key file not found |
| `E002` | Key file corrupted |
| `E003` | Key file password incorrect |
| `E004` | No key loaded |
| `E005` | Key file already exists |
| `E006` | A required password was missing |
| `E007` | Password mismatch |
| `E008` | Empty plaintext |
| `E009` | Empty ciphertext |
| `E010` | Malformed payload (not valid hexadecimal, or bad length) |
| `E011` | Decryption failed (wrong password, wrong key, or tampered) |
| `E012` | Encoding failure |
| `E013` | Invalid argument |
| `E014` | File read failed |
| `E015` | File write failed |
| `E016` | Unsupported key file version |
| `E017` | **Missing magic header** — not a CES artefact |
| `E018` | **Malformed header** — marker missing, JSON unusable, or `kind` mismatch |
Codes are stable and safe to branch on.
---
## Documentation
| Document | Contents |
|---|---|
| [SECURITY.md](SECURITY.md) | Design, key space, threat model, attack analysis |
| [docs/FORMAT.md](docs/FORMAT.md) | **Normative format specification**, with examples |
| [docs/benchmark.md](docs/benchmark.md) | Measured throughput and the profiling behind it |
| [docs/API.md](docs/API.md) | Complete Python API reference |
| [docs/CLI.md](docs/CLI.md) | Command line reference and troubleshooting |
| [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) | Internal design and module map |
| [docs/BUILDING.md](docs/BUILDING.md) | Building, testing and releasing |
| [CHANGELOG.md](CHANGELOG.md) | Release history |
---
## Development
```bash
pip install -e ".[dev]"
pytest # run the test suite
python -m build # build sdist + wheel
twine check dist/* # validate package metadata
```
### Repository layout
```
ChaosCrypt/
├── README.md SECURITY.md LICENSE CHANGELOG.md
├── docs/
├── pyproject.toml
├── dist/
└── chaoscrypt/
├── __init__.py public API and the ChaosCrypt facade
├── _core.py the algorithm and the pipelines
├── _header.py the self-describing header
├── cli.py argument-driven command line interface
├── tui.py interactive bilingual interface
├── errors.py the unified error hierarchy
├── i18n.py UI strings
├── tests/ test suite, including frozen vectors
├── examples/ runnable examples
└── legacy/ the original implementation, for reference
```
---
## Licence
[MIT](LICENSE) — provided as-is, without warranty of any kind.
ChaosCrypt has not been independently audited. It is intended for obfuscation,
personal use, and research or teaching. Do not deploy it where an audited,
standardised cryptographic primitive is required.