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
+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
```