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:
dvs
2026-09-27 17:03:05 +08:00
parent 124b511d5f
commit 2529edac1d
29 changed files with 6802 additions and 6459 deletions
+463
View File
@@ -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.
+386
View File
@@ -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.
+356
View File
@@ -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
View File
@@ -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
```
+34
View File
@@ -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).