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
This commit is contained in:
dvs
2026-09-27 22:06:34 +08:00
parent 24a36d6fb4
commit dd49043171
25 changed files with 5348 additions and 852 deletions
View File
+31
View File
@@ -0,0 +1,31 @@
# -*- coding: utf-8 -*-
"""Test-vector loading helper.
Mirrors the loader used by the sibling ``purepycrypto`` project so the two
repositories share the same layout convention: a ``vectors/`` directory next to
the tests, one JSON file per subject, loaded by name.
"""
import json
import os
VEC_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "vectors")
def path_for(name):
"""Absolute path of ``vectors/<name>.json``."""
return os.path.join(VEC_DIR, name + ".json")
def load(name):
"""Load ``vectors/<name>.json`` and return the parsed dictionary."""
with open(path_for(name), "r", encoding="utf-8") as f:
return json.load(f)
def available():
"""Names of every vector file present, without the ``.json`` suffix."""
if not os.path.isdir(VEC_DIR):
return []
return sorted(
f[:-5] for f in os.listdir(VEC_DIR) if f.endswith(".json")
)
+92 -17
View File
@@ -73,8 +73,9 @@ class TestRoundTrip:
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)
def test_ciphertext_payload_is_hex(self, loaded):
from chaoscrypt._header import strip_header
ct = strip_header(loaded.encrypt("data", USER_PWD))
int(ct, 16)
def test_empty_plaintext_rejected(self, loaded):
@@ -98,21 +99,37 @@ class TestRoundTrip:
b = loaded.encrypt("same", "pwd-B")
assert a != b
def test_non_hex_ciphertext_rejected(self, loaded):
def test_every_ciphertext_carries_a_header(self, loaded):
from chaoscrypt._header import MAGIC, read_header
ct = loaded.encrypt("data", USER_PWD)
assert ct.startswith(MAGIC.decode())
cfg = read_header(ct)
assert cfg["kind"] == "ciphertext"
def test_headerless_ciphertext_rejected(self, loaded):
"""Input without the magic header is not a CES artefact."""
with pytest.raises(ChaosCryptError) as ei:
loaded.decrypt("zzzz-not-hex", USER_PWD)
assert ei.value.code == "E010"
assert ei.value.code == "E017"
def test_odd_length_ciphertext_rejected(self, loaded):
def test_headerless_odd_length_rejected(self, loaded):
with pytest.raises(ChaosCryptError) as ei:
loaded.decrypt("abc", USER_PWD)
assert ei.value.code == "E010"
assert ei.value.code == "E017"
def test_empty_ciphertext_rejected(self, loaded):
with pytest.raises(ChaosCryptError) as ei:
loaded.decrypt("", USER_PWD)
assert ei.value.code == "E009"
def test_malformed_payload_rejected(self, loaded):
"""A valid header with a broken payload fails on the payload."""
from chaoscrypt._header import build_header
bad = build_header(loaded.core.header_config("ciphertext")) + "zzzz"
with pytest.raises(ChaosCryptError) as ei:
loaded.decrypt(bad, USER_PWD)
assert ei.value.code == "E010"
# ---------------------------------------------------------------------------
# Binary
@@ -148,6 +165,33 @@ class TestKeyManagement:
n.load(path, KEY_PWD)
assert n.loaded
def test_key_file_carries_a_header(self, tmp_path):
from chaoscrypt._header import MAGIC, read_header
path = str(tmp_path / "hdr.key")
ChaosCrypt().create_key(KEY_PWD, path)
text = open(path, encoding="utf-8").read()
assert text.startswith(MAGIC.decode())
cfg = read_header(text)
assert cfg["kind"] == "key"
assert cfg["alg"] == "chaoscrypt"
def test_headerless_key_file_rejected(self, tmp_path):
path = tmp_path / "bare.key"
path.write_text("deadbeef" * 200, encoding="utf-8")
with pytest.raises(ChaosCryptError) as ei:
ChaosCrypt().load(str(path), KEY_PWD)
assert ei.value.code == "E017"
def test_key_file_rejected_as_ciphertext(self, tmp_path):
path = str(tmp_path / "k2.key")
ChaosCrypt().create_key(KEY_PWD, path)
text = open(path, encoding="utf-8").read()
cc = ChaosCrypt()
cc.load(path, KEY_PWD)
with pytest.raises(ChaosCryptError) as ei:
cc.decrypt(text, USER_PWD)
assert ei.value.code == "E018"
def test_keygen_refuses_overwrite(self, tmp_path):
path = str(tmp_path / "k.key")
ChaosCrypt().create_key(KEY_PWD, path)
@@ -179,14 +223,14 @@ class TestKeyManagement:
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"
assert ei.value.code == "E017"
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"
assert ei.value.code in ("E002", "E017")
def test_encrypt_without_key_raises(self):
cc = ChaosCrypt()
@@ -223,10 +267,13 @@ class TestKeyManagement:
assert len(info["flip_pattern"]) == 10
def test_export_and_import_key_text(self):
from chaoscrypt._header import MAGIC, read_header
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"
assert text.startswith(MAGIC.decode())
assert read_header(text)["kind"] == "key"
n = ChaosCrypt()
n.load_from_text(text, KEY_PWD)
@@ -283,6 +330,13 @@ class TestFileAPI:
back = loaded.decrypt_file(cc_file, USER_PWD, dst)
assert open(back, "rb").read() == payload
def test_encrypted_file_carries_a_header(self, loaded, tmp_path):
from chaoscrypt._header import MAGIC
src = tmp_path / "h.txt"
src.write_text("header check", encoding="utf-8")
out = loaded.encrypt_file(str(src), USER_PWD)
assert open(out, encoding="utf-8").read().startswith(MAGIC.decode())
def test_default_suffixes(self, loaded, tmp_path):
src = tmp_path / "note.txt"
src.write_text("hello file", encoding="utf-8")
@@ -351,9 +405,14 @@ class TestErrorClass:
# ---------------------------------------------------------------------------
class TestLegacyCompatibility:
def test_format_matches_original_chain(self, loaded):
"""Reproduce the original decryption chain step by step."""
"""Reproduce the original decryption chain step by step.
The artefact carries a header, so the payload is taken from it first;
the chain that follows is the original one, unchanged.
"""
from chaoscrypt._header import strip_header
text = "compat check compatibility"
ct = loaded.encrypt(text, USER_PWD)
ct = strip_header(loaded.encrypt(text, USER_PWD))
core = loaded.core
combined = core._xor_decrypt_with_final_key(ct, USER_PWD)
@@ -370,11 +429,12 @@ class TestLegacyCompatibility:
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."""
"""The payload of a new key file must satisfy the original format."""
from chaoscrypt._header import strip_header
_, path = keyfile
core = ChaosCryptCore()
with open(path, "r") as f:
enc = f.read()
enc = strip_header(f.read())
decrypted = core._xor_decrypt_data(enc, KEY_PWD)
assert decrypted is not None
@@ -462,9 +522,10 @@ class TestCLI:
)
def test_version(self):
from chaoscrypt import __version__
r = self._run(["--version"])
assert r.returncode == 0
assert "2.1.6" in r.stdout
assert __version__ in r.stdout
def test_help_mentions_scope(self):
r = self._run(["--help"])
@@ -574,13 +635,22 @@ class TestCLI:
assert r.stdout.strip() == "", args
def test_plain_output_is_bare_ciphertext(self, tmp_path):
"""Without --json the ciphertext goes to stdout on its own."""
"""Without --json the artefact goes to stdout on its own.
"On its own" means no JSON envelope around it. The artefact does contain
the word ``ciphertext`` inside its header's ``kind`` field, so the check
is for the envelope rather than for the word.
"""
from chaoscrypt._header import MAGIC, strip_header
kf = str(tmp_path / "p.key")
self._run(["keygen", "-k", kf, "-P", KEY_PWD])
r = self._run(["encrypt", "x", "-p", USER_PWD, "-k", kf, "-P", KEY_PWD])
out = r.stdout.strip()
assert out and "ciphertext" not in out
int(out, 16)
assert out
assert not out.startswith("{"), "unexpected JSON envelope"
assert out.startswith(MAGIC.decode())
int(strip_header(out), 16)
def test_chpwd(self, tmp_path):
kf = str(tmp_path / "c.key")
@@ -598,12 +668,17 @@ class TestCLI:
# ---------------------------------------------------------------------------
class TestCoreDirect:
def test_core_generate_and_use(self):
"""Key material moves between instances through the key file scheme."""
from chaoscrypt._header import build_legacy_header
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)
# load_keys_from_text now requires a header, as every artefact does.
# A minimal one is enough when the material is already at hand.
text = build_legacy_header(is_key=True) + \
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"
+25 -75
View File
@@ -1,84 +1,34 @@
# -*- coding: utf-8 -*-
"""
Bidirectional interoperability tests against the original implementation.
Legacy interoperability: deliberately removed.
These tests load ``chaoscrypt/legacy/chaoscrypt_legacy.py`` and prove that:
Until 4.2.6 the library could exchange key files and ciphertexts with the
original single-file script. That interoperability was given up when the
self-describing header was introduced: every artefact now begins with a magic
value, two fixed markers and a configuration record, and a reader rejects
anything without one.
* ciphertext produced by the original script decrypts with the packaged
library, and
* ciphertext produced by the packaged library decrypts with the original
script.
The break is intentional in both directions:
They are the regression guard for the promise that the algorithm itself was
ported without any behavioural change.
* a key file written by this version cannot be read by the original script;
* a ciphertext written by this version cannot be decrypted by the original
script;
* artefacts written before the header existed are rejected with
``E017 MissingMagicHeader``.
Reading old material is still possible through the compatibility API, which
synthesises a minimal header and then uses the ordinary path. That is covered
by ``test_header.py``; there is nothing left to assert here.
The original implementation is kept under ``legacy/`` for reference only.
"""
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
@pytest.mark.skip(reason="interoperability with pre-4.2.6 artefacts was "
"intentionally dropped when the header was added; "
"see the compatibility API instead")
def test_legacy_interop_removed():
"""Placeholder so the removal shows up in the test report."""
assert True
+416
View File
@@ -0,0 +1,416 @@
# -*- coding: utf-8 -*-
"""
Performance-mode tests.
Four modes exist:
reference the original algorithm, character pipeline
fast same algorithm, bulk-operation implementation, identical output
turbo SHAKE256 keystream, byte pipeline, own ciphertext format
raw byte pipeline with the long-key layer retained
``reference`` and ``fast`` produce indistinguishable ciphertexts and always use
hex. ``turbo`` and ``raw`` accept either ``hex`` or ``base64`` output, and
either a ``bt`` (bytes) or ``hex`` intermediate representation.
Every artefact carries a self-describing header, so anything that inspects the
ciphertext body strips it first, and anything that feeds headerless input
expects ``E017``.
"""
import os
import pytest
from chaoscrypt import (
ChaosCrypt,
ChaosCryptCore,
ChaosCryptError,
MODES,
MODE_REFERENCE,
MODE_FAST,
MODE_TURBO,
MODE_RAW,
DEFAULT_MODE,
ENCODINGS,
ENC_HEX,
ENC_BASE64,
MIDS,
MID_BYTES,
MID_HEX,
)
from chaoscrypt._header import MAGIC, strip_header, read_header
from ._vectors import load
KEY_PWD = "mode-key-password"
USER_PWD = "mode-user-password"
SAMPLES = [
"hello",
"hello world",
"emoji test",
"a",
"x" * 300,
"Mixed 123!@#$%^&*",
"line1\nline2\ttabbed",
]
def _payload(text: str) -> str:
"""The payload of an artefact, with its self-describing header removed."""
return strip_header(text)
def _core(mode, vectors, enc="hex", mid="bt"):
"""A ChaosCryptCore in ``mode`` carrying the frozen key material."""
km = vectors["key_material"]
c = ChaosCryptCore(mode, "hash", enc, mid)
c.upper_mapping = km["upper_mapping"]
c.lower_mapping = km["lower_mapping"]
c.digit_mapping = km["digit_mapping"]
c.equal_mapping = km["equal_mapping"]
c.flip_pattern = km["flip_pattern"]
c.long_key = km["long_key"]
c.short_key = km["short_key"]
c.digit_reverse = {v: k for k, v in c.digit_mapping.items()}
c.equal_reverse = {v: k for k, v in c.equal_mapping.items()}
c._build_maps()
c.keys_loaded = True
return c
@pytest.fixture(scope="module")
def vectors():
return load("chaoscrypt_reference")
@pytest.fixture(scope="module")
def cores(vectors):
return {m: _core(m, vectors) for m in MODES}
@pytest.fixture
def keyfile(tmp_path):
path = str(tmp_path / "modes.key")
ChaosCrypt().create_key(KEY_PWD, path)
return path
# ---------------------------------------------------------------------------
# Mode surface
# ---------------------------------------------------------------------------
class TestModeSurface:
def test_all_four_modes_are_exported(self):
assert MODES == (MODE_REFERENCE, MODE_FAST, MODE_TURBO, MODE_RAW)
def test_default_mode_is_fast(self):
assert DEFAULT_MODE == MODE_FAST
def test_core_defaults_to_the_default_mode(self):
assert ChaosCryptCore().mode == DEFAULT_MODE
def test_unknown_mode_is_rejected(self):
with pytest.raises(ValueError):
ChaosCryptCore("turbo-charged")
def test_valid_mode_is_accepted(self):
for m in MODES:
assert ChaosCryptCore(m).mode == m
# ---------------------------------------------------------------------------
# reference and fast
# ---------------------------------------------------------------------------
class TestReferenceAndFast:
def test_reference_reproduces_frozen_vectors(self, cores, vectors):
core = cores[MODE_REFERENCE]
pwd = vectors["passwords"]["user_password"]
for case in vectors["cases"]:
if case.get("mode", "fast") not in ("reference", "fast"):
continue
got = _payload(core.encrypt_text(case["plaintext"], pwd))
want = _payload(case["ciphertext"])
assert got == want, f"reference drifted for {case['id']}"
def test_fast_is_indistinguishable_from_reference(self, cores, vectors):
"""The whole point of `fast`: same bytes, less time."""
pwd = vectors["passwords"]["user_password"]
for case in vectors["cases"]:
a = cores[MODE_REFERENCE].encrypt_text(case["plaintext"], pwd)
b = cores[MODE_FAST].encrypt_text(case["plaintext"], pwd)
# payloads identical; only the recorded mode differs
assert _payload(a) == _payload(b), case["id"]
assert read_header(a)["mode"] == MODE_REFERENCE
assert read_header(b)["mode"] == MODE_FAST
@pytest.mark.parametrize("text", SAMPLES)
def test_fast_matches_reference_on_samples(self, cores, text):
a = _payload(cores[MODE_REFERENCE].encrypt_text(text, USER_PWD))
b = _payload(cores[MODE_FAST].encrypt_text(text, USER_PWD))
assert a == b
def test_agree_on_large_input(self, cores):
big = "A" * 40_000
a = _payload(cores[MODE_REFERENCE].encrypt_text(big, USER_PWD))
b = _payload(cores[MODE_FAST].encrypt_text(big, USER_PWD))
assert a == b
@pytest.mark.parametrize("mode", [MODE_REFERENCE, MODE_FAST])
def test_ciphertext_payload_is_hex(self, cores, mode):
int(_payload(cores[mode].encrypt_text("data", USER_PWD)), 16)
# ---------------------------------------------------------------------------
# turbo and raw
# ---------------------------------------------------------------------------
class TestTurboAndRaw:
@pytest.mark.parametrize("mode", [MODE_TURBO, MODE_RAW])
@pytest.mark.parametrize("text", SAMPLES)
def test_roundtrip(self, cores, mode, text):
ct = cores[mode].encrypt_text(text, USER_PWD)
assert cores[mode].decrypt_text(ct, USER_PWD) == text
@pytest.mark.parametrize("mode", [MODE_TURBO, MODE_RAW])
@pytest.mark.parametrize("size", [1, 2, 255, 4096])
def test_binary_roundtrip(self, cores, mode, size):
raw = os.urandom(size)
ct = cores[mode].encrypt_bytes(raw, USER_PWD)
assert cores[mode].decrypt_bytes(ct, USER_PWD) == raw
@pytest.mark.parametrize("mode", MODES)
def test_every_ciphertext_carries_a_header(self, cores, mode):
ct = cores[mode].encrypt_text("data", USER_PWD)
assert ct.startswith(MAGIC.decode())
assert read_header(ct)["kind"] == "ciphertext"
@pytest.mark.parametrize("mode", [MODE_TURBO, MODE_RAW])
def test_wrong_password_fails(self, cores, mode):
ct = cores[mode].encrypt_text("secret", USER_PWD)
with pytest.raises(ChaosCryptError):
cores[mode].decrypt_text(ct, "wrong-password")
# ---------------------------------------------------------------------------
# Intermediates and encodings
# ---------------------------------------------------------------------------
class TestIntermediatesAndEncodings:
@pytest.mark.parametrize("mode", [MODE_TURBO, MODE_RAW])
@pytest.mark.parametrize("mid", MIDS)
@pytest.mark.parametrize("enc", ENCODINGS)
def test_all_combinations_round_trip(self, vectors, mode, mid, enc):
c = _core(mode, vectors, enc, mid)
for text in SAMPLES:
ct = c.encrypt_text(text, USER_PWD)
assert c.decrypt_text(ct, USER_PWD) == text, (mode, mid, enc)
@pytest.mark.parametrize("mode", [MODE_TURBO, MODE_RAW])
@pytest.mark.parametrize("mid", MIDS)
def test_binary_round_trip_all_mids(self, vectors, mode, mid):
c = _core(mode, vectors, "hex", mid)
raw = os.urandom(2_000)
assert c.decrypt_bytes(c.encrypt_bytes(raw, USER_PWD), USER_PWD) == raw
@pytest.mark.parametrize("mid", MIDS)
def test_header_records_the_mid(self, vectors, mid):
for mode in (MODE_TURBO, MODE_RAW):
c = _core(mode, vectors, "hex", mid)
cfg = read_header(c.encrypt_text("x", USER_PWD))
assert cfg["mid"] == mid, mode
@pytest.mark.parametrize("enc", ENCODINGS)
def test_header_records_the_encoding(self, vectors, enc):
for mode in (MODE_TURBO, MODE_RAW):
c = _core(mode, vectors, enc, "bt")
cfg = read_header(c.encrypt_text("x", USER_PWD))
want = "base" if enc == ENC_BASE64 else "hex"
assert cfg["out"] == want, mode
def test_legacy_modes_always_report_hex(self, vectors):
for mode in (MODE_REFERENCE, MODE_FAST):
c = _core(mode, vectors, ENC_BASE64, MID_HEX)
cfg = read_header(c.encrypt_text("x", USER_PWD))
assert cfg["out"] == "hex"
assert cfg["mid"] == "hex"
def test_hex_artefact_is_larger_than_bt(self, vectors):
"""A hex intermediate doubles the payload at each layer."""
big = "A" * 5_000
sizes = {}
for mid in MIDS:
c = _core(MODE_TURBO, vectors, "hex", mid)
sizes[mid] = len(_payload(c.encrypt_text(big, USER_PWD)))
assert sizes[MID_HEX] > sizes[MID_BYTES]
def test_base64_output_is_smaller_than_hex(self, vectors):
big = "A" * 5_000
sizes = {}
for enc in ENCODINGS:
c = _core(MODE_TURBO, vectors, enc, MID_BYTES)
sizes[enc] = len(_payload(c.encrypt_text(big, USER_PWD)))
assert sizes[ENC_BASE64] < sizes[ENC_HEX]
def test_hex_payload_is_hex(self, vectors):
c = _core(MODE_TURBO, vectors, "hex", MID_BYTES)
int(_payload(c.encrypt_text("data", USER_PWD)), 16)
def test_base64_payload_is_base64(self, vectors):
import base64 as b64
c = _core(MODE_TURBO, vectors, ENC_BASE64, MID_BYTES)
b64.b64decode(_payload(c.encrypt_text("data", USER_PWD)).encode(),
validate=True)
def test_unknown_encoding_rejected(self):
with pytest.raises(ValueError):
ChaosCryptCore(MODE_TURBO, encoding="base85")
def test_unknown_mid_rejected(self):
with pytest.raises(ValueError):
ChaosCryptCore(MODE_TURBO, mid="nonsense")
def test_mid_aliases_are_accepted(self):
"""'bytes' is an accepted spelling of 'bt', and 'base' of 'base64'."""
assert ChaosCryptCore(MODE_TURBO, mid="bytes").mid == MID_BYTES
assert ChaosCryptCore(MODE_TURBO, encoding="base").encoding == ENC_BASE64
# ---------------------------------------------------------------------------
# The header decides how an artefact is read
# ---------------------------------------------------------------------------
class TestHeaderDrivesDecryption:
def test_a_misconfigured_reader_still_works(self, vectors):
"""The artefact states its own parameters; the reader need not."""
writer = _core(MODE_TURBO, vectors, ENC_BASE64, MID_HEX)
ct = writer.encrypt_text("header rules", USER_PWD)
reader = _core(MODE_TURBO, vectors, "hex", MID_BYTES) # wrong on both
assert reader.decrypt_text(ct, USER_PWD) == "header rules"
def test_headerless_input_is_rejected(self, cores):
for mode in MODES:
with pytest.raises(ChaosCryptError) as ei:
cores[mode].decrypt_text("72370655cafe", USER_PWD)
assert ei.value.code == "E017", mode
def test_malformed_payload_is_rejected(self, vectors):
from chaoscrypt._header import build_header
c = _core(MODE_TURBO, vectors)
bad = build_header(c.header_config("ciphertext")) + "zz"
with pytest.raises(ChaosCryptError) as ei:
c.decrypt_text(bad, USER_PWD)
assert ei.value.code == "E010"
# ---------------------------------------------------------------------------
# Key material must still contribute
# ---------------------------------------------------------------------------
class TestKeyMaterialContributes:
@pytest.mark.parametrize("mode", MODES)
def test_long_key_contributes(self, vectors, mode):
a = _core(mode, vectors)
b = _core(mode, vectors)
b.long_key = "0" * 4096
b._build_maps()
assert (a.encrypt_text("UPPER and lower", USER_PWD)
!= b.encrypt_text("UPPER and lower", USER_PWD))
@pytest.mark.parametrize("mode", MODES)
def test_short_key_contributes(self, vectors, mode):
a = _core(mode, vectors)
b = _core(mode, vectors)
b.short_key = "0" * 512
b._build_maps()
assert (a.encrypt_text("UPPER and lower", USER_PWD)
!= b.encrypt_text("UPPER and lower", USER_PWD))
@pytest.mark.parametrize("mode", MODES)
def test_password_contributes(self, vectors, mode):
c = _core(mode, vectors)
assert (c.encrypt_text("same", "pw-a") != c.encrypt_text("same", "pw-b"))
@pytest.mark.parametrize("mode", MODES)
def test_substitution_tables_contribute(self, vectors, mode):
a = _core(mode, vectors)
b = _core(mode, vectors)
b.upper_mapping = "ZYXWVUTSRQPONMLKJIHGFEDCBA"
b._build_maps()
# both cases present, so upper_mapping cannot be bypassed
assert (a.encrypt_text("UPPER and lower", USER_PWD)
!= b.encrypt_text("UPPER and lower", USER_PWD))
@pytest.mark.parametrize("mode", MODES)
def test_lower_mapping_contributes(self, vectors, mode):
a = _core(mode, vectors)
b = _core(mode, vectors)
b.lower_mapping = "zyxwvutsrqponmlkjihgfedcba"
b._build_maps()
assert (a.encrypt_text("UPPER and lower", USER_PWD)
!= b.encrypt_text("UPPER and lower", USER_PWD))
@pytest.mark.parametrize("mode", MODES)
def test_flip_pattern_contributes(self, vectors, mode):
a = _core(mode, vectors)
b = _core(mode, vectors)
b.flip_pattern = [0] * 10
sample = "UPPER and lower"
assert (a.encrypt_text(sample, USER_PWD)
!= b.encrypt_text(sample, USER_PWD))
# ---------------------------------------------------------------------------
# Public API
# ---------------------------------------------------------------------------
class TestPublicAPI:
@pytest.mark.parametrize("mode", MODES)
def test_facade_roundtrip(self, keyfile, mode):
cc = ChaosCrypt(key_file=keyfile, key_password=KEY_PWD,
auto_load=True, mode=mode)
ct = cc.encrypt("facade mode test", USER_PWD)
assert cc.decrypt(ct, USER_PWD) == "facade mode test"
@pytest.mark.parametrize("enc", ENCODINGS)
def test_facade_supports_encoding(self, keyfile, enc):
cc = ChaosCrypt(key_file=keyfile, key_password=KEY_PWD, auto_load=True,
mode=MODE_TURBO, encoding=enc)
ct = cc.encrypt("encoding via facade", USER_PWD)
assert cc.decrypt(ct, USER_PWD) == "encoding via facade"
@pytest.mark.parametrize("mid", MIDS)
def test_facade_supports_mid(self, keyfile, mid):
cc = ChaosCrypt(key_file=keyfile, key_password=KEY_PWD, auto_load=True,
mode=MODE_TURBO, mid=mid)
ct = cc.encrypt("mid via facade", USER_PWD)
assert cc.decrypt(ct, USER_PWD) == "mid via facade"
@pytest.mark.parametrize("mode", MODES)
def test_facade_file_roundtrip(self, keyfile, tmp_path, mode):
cc = ChaosCrypt(key_file=keyfile, key_password=KEY_PWD,
auto_load=True, mode=mode)
payload = os.urandom(1_500)
src = tmp_path / "payload.bin"
src.write_bytes(payload)
enc = cc.encrypt_file(str(src), USER_PWD)
out = cc.decrypt_file(enc, USER_PWD, str(tmp_path / "out.bin"))
assert open(out, "rb").read() == payload
# ---------------------------------------------------------------------------
# Errors, common to every mode
# ---------------------------------------------------------------------------
class TestModeErrors:
@pytest.mark.parametrize("mode", MODES)
def test_empty_plaintext_rejected(self, cores, mode):
with pytest.raises(ChaosCryptError) as ei:
cores[mode].encrypt_text("", USER_PWD)
assert ei.value.code == "E008"
@pytest.mark.parametrize("mode", MODES)
def test_empty_password_rejected(self, cores, mode):
with pytest.raises(ChaosCryptError) as ei:
cores[mode].encrypt_text("data", "")
assert ei.value.code == "E006"
def test_empty_ciphertext_rejected(self, cores):
with pytest.raises(ChaosCryptError) as ei:
cores[MODE_FAST].decrypt_text("", USER_PWD)
assert ei.value.code == "E009"
+3 -3
View File
@@ -62,7 +62,7 @@ class TestTUI:
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)
m = re.search(r"Ciphertext:\s*\n(69CES[^\s]+)", r1.stdout)
assert m, r1.stdout
ct = m.group(1).strip()
@@ -73,7 +73,7 @@ class TestTUI:
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
assert re.search(r"Ciphertext:\s*\n(69CES[^\s]+)", 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"
@@ -97,7 +97,7 @@ class TestTUI:
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
assert re.search(r"密文:\s*\n(69CES[^\s]+)", r.stdout), r.stdout
def test_about_page_has_design_notes(self, tmp_path):
r = _run_tui("a\n\nq\n", str(tmp_path))
+294
View File
@@ -0,0 +1,294 @@
# -*- coding: utf-8 -*-
"""
Strict reference-vector tests.
ChaosCrypt is a self-designed construction, so unlike AES or SHA-3 there are no
FIPS or RFC vectors to check it against. What can be checked is that the format
and the algorithm do not drift: the vectors in
``vectors/chaoscrypt_reference.json`` are generated from the implementation and
then frozen. If anything changes -- a substitution table, a bit operation, a
loop bound, the header layout, an encoding -- these tests fail.
Every artefact now carries a self-describing header, so each case is checked
for three things: the header is present and consistent, the ciphertext matches
the frozen value exactly, and the payload round-trips.
"""
import pytest
from chaoscrypt._core import ChaosCryptCore
from chaoscrypt.errors import ChaosCryptError
from chaoscrypt._header import (
MAGIC, BEGIN_MARKER, END_MARKER, read_header, strip_header,
MIDS, OUTS, KIND_CIPHERTEXT,
)
from ._vectors import available, load
VECTOR_NAME = "chaoscrypt_reference"
@pytest.fixture(scope="module")
def vectors():
return load(VECTOR_NAME)
def _core_from(km, mode="fast", enc="hex", mid="bt"):
"""Build a ChaosCryptCore preloaded with fixed key material."""
c = ChaosCryptCore(mode, "hash", enc, mid)
c.upper_mapping = km["upper_mapping"]
c.lower_mapping = km["lower_mapping"]
c.digit_mapping = km["digit_mapping"]
c.equal_mapping = km["equal_mapping"]
c.flip_pattern = km["flip_pattern"]
c.long_key = km["long_key"]
c.short_key = km["short_key"]
c.digit_reverse = {v: k for k, v in c.digit_mapping.items()}
c.equal_reverse = {v: k for k, v in c.equal_mapping.items()}
c._build_maps()
c.keys_loaded = True
return c
@pytest.fixture(scope="module")
def core(vectors):
return _core_from(vectors["key_material"])
def _per_case_core(case, km):
"""A core configured the way the case was produced."""
return _core_from(km,
mode=case.get("mode", "fast"),
enc=case.get("out", "hex"),
mid=case.get("mid", "bt"))
# ---------------------------------------------------------------------------
# Vector file integrity
# ---------------------------------------------------------------------------
class TestVectorFile:
def test_vector_file_is_present(self):
assert VECTOR_NAME in available()
def test_required_sections_exist(self, vectors):
for key in ("key_material", "passwords", "cases",
"error_cases", "key_material_properties"):
assert key in vectors, f"missing section: {key}"
def test_long_key_is_4096_nibbles(self, vectors):
assert len(vectors["key_material"]["long_key"]) == 4096
def test_short_key_is_512_nibbles(self, vectors):
assert len(vectors["key_material"]["short_key"]) == 512
def test_keys_are_valid_hex(self, vectors):
int(vectors["key_material"]["long_key"], 16)
int(vectors["key_material"]["short_key"], 16)
def test_case_ids_are_unique(self, vectors):
ids = [c["id"] for c in vectors["cases"]]
assert len(ids) == len(set(ids))
def test_case_modes_are_known(self, vectors):
from chaoscrypt import MODES
for case in vectors["cases"]:
assert case.get("mode", "fast") in MODES, case["id"]
def test_case_mids_and_outs_are_known(self, vectors):
for case in vectors["cases"]:
assert case.get("mid", "bt") in MIDS, case["id"]
assert case.get("out", "hex") in OUTS, case["id"]
# ---------------------------------------------------------------------------
# Key material invariants
# ---------------------------------------------------------------------------
class TestKeyMaterialInvariants:
def test_upper_mapping_is_a_bijection(self, vectors):
m = vectors["key_material"]["upper_mapping"]
assert len(m) == 26
assert sorted(m) == sorted("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
def test_lower_mapping_is_a_bijection(self, vectors):
m = vectors["key_material"]["lower_mapping"]
assert len(m) == 26
assert sorted(m) == sorted("abcdefghijklmnopqrstuvwxyz")
def test_digit_mapping_covers_all_digits(self, vectors):
m = vectors["key_material"]["digit_mapping"]
assert sorted(m.keys()) == sorted("0123456789")
assert len(set(m.values())) == 10
def test_equal_mapping_covers_padding_counts(self, vectors):
m = vectors["key_material"]["equal_mapping"]
assert sorted(m.keys()) == ["0", "1", "2", "3"]
assert len(set(m.values())) == 4
def test_flip_pattern_is_ten_bits(self, vectors):
p = vectors["key_material"]["flip_pattern"]
assert len(p) == 10
assert all(b in (0, 1) for b in p)
# ---------------------------------------------------------------------------
# Header conformance of every frozen case
# ---------------------------------------------------------------------------
class TestFrozenHeaders:
def test_every_case_starts_with_the_magic(self, vectors):
magic = MAGIC.decode()
for case in vectors["cases"]:
assert case["ciphertext"].startswith(magic), case["id"]
def test_every_case_carries_both_markers(self, vectors):
for case in vectors["cases"]:
ct = case["ciphertext"]
assert BEGIN_MARKER in ct, case["id"]
assert END_MARKER in ct, case["id"]
def test_every_case_header_parses(self, vectors):
for case in vectors["cases"]:
cfg = read_header(case["ciphertext"])
assert cfg["kind"] == KIND_CIPHERTEXT, case["id"]
def test_header_mode_matches_the_case(self, vectors):
for case in vectors["cases"]:
cfg = read_header(case["ciphertext"])
assert cfg["mode"] == case.get("mode", "fast"), case["id"]
def test_header_mid_matches_the_case(self, vectors):
"""The header's mid must match what the case says, or hex for the
character pipelines, which have no mid of their own."""
for case in vectors["cases"]:
cfg = read_header(case["ciphertext"])
mode = case.get("mode", "fast")
if mode in ("reference", "fast"):
assert cfg["mid"] == "hex", case["id"]
else:
assert cfg["mid"] == case.get("mid", "bt"), case["id"]
def test_header_out_matches_the_case(self, vectors):
for case in vectors["cases"]:
cfg = read_header(case["ciphertext"])
mode = case.get("mode", "fast")
if mode in ("reference", "fast"):
assert cfg["out"] == "hex", case["id"]
else:
assert cfg["out"] == case.get("out", "hex"), case["id"]
def test_reference_and_fast_always_report_hex(self, vectors):
"""The character pipelines ignore mid and always use hex."""
for case in vectors["cases"]:
if case.get("mode") in ("reference", "fast"):
cfg = read_header(case["ciphertext"])
assert cfg["mid"] == "hex", case["id"]
assert cfg["out"] == "hex", case["id"]
def test_payload_is_not_empty(self, vectors):
for case in vectors["cases"]:
assert strip_header(case["ciphertext"]), case["id"]
# ---------------------------------------------------------------------------
# The frozen ciphertexts themselves
# ---------------------------------------------------------------------------
class TestFrozenVectors:
def test_encryption_reproduces_frozen_ciphertext(self, vectors):
"""Encrypting the recorded plaintext must yield the recorded artefact."""
km = vectors["key_material"]
pwd = vectors["passwords"]["user_password"]
failures = []
for case in vectors["cases"]:
c = _per_case_core(case, km)
got = c.encrypt_text(case["plaintext"], pwd)
if got != case["ciphertext"]:
failures.append(
f"{case['id']}:\n expected {case['ciphertext'][:80]}\n"
f" got {got[:80]}"
)
assert not failures, (
"frozen vectors no longer match -- format or algorithm changed:\n"
+ "\n".join(failures)
)
def test_decryption_round_trips(self, vectors):
km = vectors["key_material"]
pwd = vectors["passwords"]["user_password"]
for case in vectors["cases"]:
c = _per_case_core(case, km)
got = c.decrypt_text(case["ciphertext"], pwd)
assert got == case["plaintext"], case["id"]
def test_encryption_is_deterministic(self, vectors):
km = vectors["key_material"]
pwd = vectors["passwords"]["user_password"]
for case in vectors["cases"]:
c = _per_case_core(case, km)
a = c.encrypt_text(case["plaintext"], pwd)
b = c.encrypt_text(case["plaintext"], pwd)
assert a == b, f"{case['id']} is not deterministic"
def test_wrong_password_does_not_reproduce_plaintext(self, core, vectors):
case = vectors["cases"][0]
try:
got = core.decrypt_text(case["ciphertext"], "not-the-password")
except ChaosCryptError:
return
assert got != case["plaintext"]
# ---------------------------------------------------------------------------
# Error behaviour
# ---------------------------------------------------------------------------
class TestFrozenErrorCases:
def test_error_cases_raise_expected_codes(self, core, vectors):
failures = []
for case in vectors["error_cases"]:
try:
if case["kind"] == "encrypt":
core.encrypt_text(case["plaintext"], case["password"])
else:
core.decrypt_text(case["ciphertext"], case["password"])
except ChaosCryptError as e:
if e.code != case["expect_code"]:
failures.append(
f"{case['id']}: expected {case['expect_code']}, got {e.code}"
)
else:
failures.append(
f"{case['id']}: expected {case['expect_code']}, no error raised"
)
assert not failures, "\n".join(failures)
def test_headerless_input_is_rejected(self, core, vectors):
"""The deliberate break from pre-4.2.6 material."""
with pytest.raises(ChaosCryptError) as ei:
core.decrypt_text("72370655031311011c111f261365172716020b69", "pw")
assert ei.value.code == "E017"
# ---------------------------------------------------------------------------
# Known-answer tests for the building blocks
# ---------------------------------------------------------------------------
class TestKnownAnswers:
def test_digit_mapping_encode(self, core, vectors):
kat = next(k for k in vectors["known_answer_tests"]
if k["id"] == "digit_mapping_encode")
assert core._encode_digit(kat["input"]) == kat["expected"]
def test_digit_mapping_round_trip(self, core, vectors):
kat = next(k for k in vectors["known_answer_tests"]
if k["id"] == "digit_mapping_encode")
assert core._decode_digit(kat["expected"]) == kat["input"]
def test_equal_mapping_values(self, vectors):
kat = next(k for k in vectors["known_answer_tests"]
if k["id"] == "equal_mapping_values")
assert vectors["key_material"]["equal_mapping"] == kat["expected"]
def test_substitution_round_trip(self, core):
sample = "ABCXYZabcxyz"
subbed = core._substitute_letters(sample, core.encrypt_map)
assert core._substitute_letters(subbed, core.decrypt_map) == sample
def test_case_flip_is_its_own_inverse(self, core):
sample = "AbCdEfGhIjKlMnOp"
assert core._apply_flip(core._apply_flip(sample)) == sample
@@ -0,0 +1,215 @@
{
"_comment": "ChaosCrypt frozen reference vectors for the headed format (4.2.6 onward). Every artefact carries a self-describing header: magic b'69CES', a begin marker, a JSON configuration record, an end marker, then the payload. ChaosCrypt is a self-designed construction, so no FIPS or RFC vectors exist for it; these are generated from the implementation and then frozen, which turns them into a regression guard. They are NOT a proof of strength. Regenerating them means the format or the algorithm changed, which is a compatibility break.",
"name": "chaoscrypt_reference",
"source": "Self-generated from the implementation, then frozen",
"version": "4.2.6",
"notes": [
"Key material below is fixed so the vectors are reproducible; never use it for real data.",
"Every ciphertext starts with the magic bytes b'69CES'.",
"The configuration block names the mode, the intermediate representation (mid) and the output encoding (out).",
"reference and fast share one ciphertext form and always use hex; only mode is recorded differently.",
"turbo and raw support out=hex|base and mid=bt|hex, producing distinct formats.",
"Headerless input is rejected with E017, by design."
],
"key_material": {
"upper_mapping": "BCDEFGHIJKLMNOPQRSTUVWXYZA",
"lower_mapping": "bcdefghijklmnopqrstuvwxyza",
"digit_mapping": {
"0": "A",
"1": "B",
"2": "C",
"3": "D",
"4": "E",
"5": "F",
"6": "G",
"7": "H",
"8": "I",
"9": "J"
},
"equal_mapping": {
"0": "W",
"1": "X",
"2": "Z",
"3": "Y"
},
"flip_pattern": [
1,
0,
1,
0,
0,
1,
0,
0,
1,
0
],
"long_key": "39d65637ec0f62b69ca5d3c5ab08385d533d000dc2d8984d23406b2cb30e3ce304ab21201994888a838d10100ff5688702850c3cb7c828123be21f3f0fca661065db7b80d40b05717d7c18d8374e925044a9ce53e9445c1d12bed49340b1bc8e44fd81c3a63e933da598f9384fc25cded0d8c5e9d5a1462beeca11d631f5e65e578e95bcf67600c993436722dd4cd582487efff016f034c54be236ad3562ddcff16fc53e34597734c8326c54326343c6f4bda1cf82b884080a521dae535b7a6b45ba3350b56ea5b61fe1757b8f51328001975fd898057a6d7bcae3225d9b8742539b29023476500cccee48835dac749908dbf1003bcd754093a6a8ca4bf8f0159716e7c28877c5c7f66fd3885604c94a100372b691aff5811fc75fa91573e8677e56663fecf2314f1fada7239737396398228417a72c7335fb3af6949b3925d6127f2461d711dbf0a45fef7f4fe71ea981cfff4ccc51e52ab46af1fe98c24365c18fa8e368b891c9fb38307f627b877c73487c9fce2250eea6c6be1bdeea24500548b902e9795f8290907bbef77dcf05251d3e412cbac121a1703abc2329f091e27f48736b52db793a8cf03016aec910386ea811dbded8af82cbb1ed331a4e67e24441d95c69607b4f0278b398fc7bb44b12da5bca48bdfba3506e4604615c6ec426ebd4db7996d889bdd53088105d916d84f37b7f781fd49455d533356af6b85d15a3eec3047f933d0212cf53483c752cfc0eea4bca27fe2bd7fded49851324d80c02d8145e4bf5f90d479436850e37875fac00257db3e53b3a0fb3b782338113a1cd7b554e0fe606195a8a51e2898f8469d20b4896f928d113b7bc82ef0dd3b7d8237f98cc7044cb94c2ef513f32de92d59f0aa65f201528f2c1a5b2c18d8db7e2b87755cb273317133bdaf398e229b8bc519cc753b381f5555309763ceeaaf8134e7e9d14707de6382af9664ec9d6d3d0244d241c23070362b8f0b1497f5b6182b2bd3a60f7f03463ffa2e79c68efe169453489f153cc65251e140e72c7c3752c515b604238f65e5ba06dcffce9f9b1566934ca052eb30026b8d4236623c157f20ca480a53b22f95e979471d0c05b0b8f3755833b9396241679eb78c63ccd2170b3213660c0d2275f7ac3f4618f8a688e35d1a59cdd0177bcb23c4a283f487bcafc63ce5c1cba9baec57093cf12c8dd0c8d7f352333cd660814c94b27385445390056d75077d33c6cd977fa5f6aa19ebea84890bdc55400e02d8337b4097b1532e77fe5b7e1b3d9426ceb3417b0a2a481c1aa8c84692d34f2fa29c3c90cfd0bcb0fe227fc63fa8877e38ad2d8ac8a198c331c24c73de46c4b7f9fc157953b8c8964caedbd89305b443dc178aee57874b06ecc0b208eeeab632167047a105aa67471df64d17f6deddfc77781c6c1c9945a7125bee0eb19c50cd560311ebc0e62ae18eb197964e471dc09ca2fc4c135cd924b69b5006eb6ff0904cf064f64a54b94db3c72ba607554b74bbca4efb4fe42238eb4ffdf5fda2a1ab2675c3de0dd8da5f759c8648ed4e2ee68a1571290b7962b53f7710f3dbacd826971c1bc019f34b654e51aeb24f936dcf38ca7e87203a9ea57b21dc865b79d238092e49c156c5bc2e0abc2c47822546963ef3a77bbcf7ab70da0c27e209a1054160897af67042c326c055ec7a55dfe74a8d367a57a32ee3569e58c0674d58a95d8116d9082f463727987e5279d5fb27a54849feb1021f1649f55c56a7edd5017f6255ee7e2c309556992c127bd7ae270233b24f0c648cb499624e79184a7936da6108af26b47fa137cec35b5130b62039e3946ec427d9b34d9ebeabe0a95c518f06934a32c38ce2162e276757a2362cc5eb27a8c31be14c3b1d3d5611c752ff894944d3ea637a87eb2a286d8c7400b3c1a691a224e965ce2ad13ea95305c68e60691793c696887a74b8952e8434f510fdbb0ba7e0f3322a4da801db599a8210cf0a0a9ca1e296c25402f606fcbf45f06a22f2bfeb44c62a2680bce5c6e63ecd57bc4e3170111b00bd5fcf1d8feb5e21dbfd671d5826c9dfc7188689f99b05012629dd0d29fb291e25560729f017a2207949fa873d74d1a17251382a11feae73755614c53291674945312378fdc2b79d1078244f5ae4ee44f7a8e7f27d8b4ce1b1c19415cfa3d8a2c8b92041416da7556f27181d7583de84fd21129afeab0707dcce01e03cb3d69258edaf8c88535b828eb0651eba05dec330d3c2a68629c7498d47188238f3f216b4f848ed5e2c6c9cdef330ec2e58fdf89a4e2bcc3c114ab06d15541d9cac8947c9562ac5cfb2bd7ac56f4947b43f5f614aa409d84addcd325f696976caea9ff4b951e4c920c184cf4963c8cbb92e580fb78e41ec762e3f7f7bea9bb9488b93d524c55c4ca017c632ce12c381e73aaf9359346ee53c3cfd9922b41e5034031781f7b698c411e23d56e13327f316ac807c1d56c815915a56c3ad044c15070ff2c28ee2381fea84f36e70b039988ba7dc6cb55f698afc4859da08475197620a56c113f702e90f41f20708e853f0be81d5080ce7dd3683d3f1386e37c26e06161cf4500e5cc8bbd6f7e243e5733abdfb2e9554c22c5e16b4ecd6241e326e460765d874f578e7e720b00fb7f0ad725551bba2912e85d895bc705032c18bf3e8c6ad3587d39d2f00ae869a8da03afdb581d588af5eee8b69e1de6e1a5fda79946a05dc3bf9fcaae92b4b03b9d75bf6f61a6f35f1d3f4f293b2f0477d2e8dd90f1c51bba82beccd388d3f6a3cb6613ac1e4e8fb59a6d8844d1c15496d70e33a820ed5d9a027b2f3581d5e2b32ef3cd8eb229c728b138096811ad9b66868ec780fb03d4e6c9585329cf5635eca3fc5b7e4f6759b9b4278330280b6e940756153481fe",
"short_key": "cafb66ae19518dd63547f87adbf4d26a4f035480433cf7f9a2a19f846f152b8eabfc7673995f75ff3a2e90107432921ae92c06af87e549d1983684f89ec7964ca4d001671c483a93ced8b665e94310e375ec4933e04bce3c67bc895cdaa7c593d50a0c3b19f6efc5e3a88a0371904615899e71b481b6cf077f77f681d74fe2eadb666d3fdfda87e88d50ae94f2fc174958bf4e33954a685eba7a7c5d81816ebd47e56d6d8a8a246b0f0abc219bc3da5b790c12461475855d3fef3d3247b8c08d1d7326419c3e4df22f1138cbc39cb01da917cc8dacd97be1c2dd6bef4b626c9d8fafa25479735c02789006d1905f29d2c666114fc802abd19a095170e9e2c6eb"
},
"passwords": {
"user_password": "reference-user-password",
"key_password": "reference-key-password"
},
"key_material_properties": {
"long_key_length": 4096,
"short_key_length": 512,
"digit_mapping_size": 10,
"equal_mapping_size": 4,
"flip_pattern_length": 10,
"upper_mapping_is_bijection": true,
"lower_mapping_is_bijection": true
},
"cases": [
{
"id": "text_ascii_short",
"kind": "text",
"plaintext": "hello",
"ciphertext": "69CES385aeff1f4179a744c8fb0c5ae4702d325f6230d059f4251135c2536409dee93{\"alg\":\"chaoscrypt\",\"b64\":true,\"cache\":\"hash\",\"compact\":false,\"flip\":\"conditional\",\"flipbits\":10,\"kdf\":\"expand\",\"keybits\":16384,\"keyshort\":2048,\"kind\":\"ciphertext\",\"ksum\":\"8007e271aea2b261\",\"lib\":\"4.2.6\",\"mid\":\"hex\",\"mode\":\"fast\",\"order\":\"base64>subst>flip>reverse>xor>xor\",\"out\":\"hex\",\"subst\":\"bijective\",\"utf8\":true,\"v\":1,\"xor_layers\":2}2025ea4e4b4b93803f2ccadeaf318d1957ce42ff5409410f660348be96a4c0f272370655031311011c111f261365172716020b69"
},
{
"id": "text_ascii_long",
"kind": "text",
"plaintext": "The quick brown fox jumps over the lazy dog.",
"ciphertext": "69CES385aeff1f4179a744c8fb0c5ae4702d325f6230d059f4251135c2536409dee93{\"alg\":\"chaoscrypt\",\"b64\":true,\"cache\":\"hash\",\"compact\":false,\"flip\":\"conditional\",\"flipbits\":10,\"kdf\":\"expand\",\"keybits\":16384,\"keyshort\":2048,\"kind\":\"ciphertext\",\"ksum\":\"8007e271aea2b261\",\"lib\":\"4.2.6\",\"mid\":\"hex\",\"mode\":\"fast\",\"order\":\"base64>subst>flip>reverse>xor>xor\",\"out\":\"hex\",\"subst\":\"bijective\",\"utf8\":true,\"v\":1,\"xor_layers\":2}2025ea4e4b4b93803f2ccadeaf318d1957ce42ff5409410f660348be96a4c0f272620757011113021e151f26116d1377165244424335566654761112461771556c355415785650231457101775157e77517a025a53761c646866101570571471047562634110750b1246147e412617017552161472621350437112030331791f7d41524563721555011276167f5f7443172460066114177e1036286067"
},
{
"id": "text_unicode",
"kind": "text",
"plaintext": "ChaosCrypt 混沌加密世界",
"ciphertext": "69CES385aeff1f4179a744c8fb0c5ae4702d325f6230d059f4251135c2536409dee93{\"alg\":\"chaoscrypt\",\"b64\":true,\"cache\":\"hash\",\"compact\":false,\"flip\":\"conditional\",\"flipbits\":10,\"kdf\":\"expand\",\"keybits\":16384,\"keyshort\":2048,\"kind\":\"ciphertext\",\"ksum\":\"8007e271aea2b261\",\"lib\":\"4.2.6\",\"mid\":\"hex\",\"mode\":\"fast\",\"order\":\"base64>subst>flip>reverse>xor>xor\",\"out\":\"hex\",\"subst\":\"bijective\",\"utf8\":true,\"v\":1,\"xor_layers\":2}2025ea4e4b4b93803f2ccadeaf318d1957ce42ff5409410f660348be96a4c0f274370557031d120a1d151f2712611627175042144167573654701314441c70016f6c57477b0151271757154774157f27517c015453771c646f31131270561776042267644115745c104e13744075170b74065a6000"
},
{
"id": "text_single_char",
"kind": "text",
"plaintext": "a",
"ciphertext": "69CES385aeff1f4179a744c8fb0c5ae4702d325f6230d059f4251135c2536409dee93{\"alg\":\"chaoscrypt\",\"b64\":true,\"cache\":\"hash\",\"compact\":false,\"flip\":\"conditional\",\"flipbits\":10,\"kdf\":\"expand\",\"keybits\":16384,\"keyshort\":2048,\"kind\":\"ciphertext\",\"ksum\":\"8007e271aea2b261\",\"lib\":\"4.2.6\",\"mid\":\"hex\",\"mode\":\"fast\",\"order\":\"base64>subst>flip>reverse>xor>xor\",\"out\":\"hex\",\"subst\":\"bijective\",\"utf8\":true,\"v\":1,\"xor_layers\":2}2025ea4e4b4b93803f2ccadeaf318d1957ce42ff5409410f660348be96a4c0f274640757021c13505466"
},
{
"id": "text_repeated",
"kind": "text",
"plaintext": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"ciphertext": "69CES385aeff1f4179a744c8fb0c5ae4702d325f6230d059f4251135c2536409dee93{\"alg\":\"chaoscrypt\",\"b64\":true,\"cache\":\"hash\",\"compact\":false,\"flip\":\"conditional\",\"flipbits\":10,\"kdf\":\"expand\",\"keybits\":16384,\"keyshort\":2048,\"kind\":\"ciphertext\",\"ksum\":\"8007e271aea2b261\",\"lib\":\"4.2.6\",\"mid\":\"hex\",\"mode\":\"fast\",\"order\":\"base64>subst>flip>reverse>xor>xor\",\"out\":\"hex\",\"subst\":\"bijective\",\"utf8\":true,\"v\":1,\"xor_layers\":2}2025ea4e4b4b93803f2ccadeaf318d1957ce42ff5409410f660348be96a4c0f21274143211731f451f501214035306307221650654071643044e141c761263457215564216426104660774101143132651606652447c0155704451404374112c72007f065253704c636161101573574175527463614412750f17404676447742062551131572621c55127111030066291a2a1051176074465357117341795025111c716551601344724461631713734d437053420843404710141d321555157c7f160f061440712c435f735578130d4d136d177806666344430411461440504d434e6173062b6240115d7160546266070421735513437666164406070856630610527a40167463456f1e447457735231046c467403136a0b73431044640d611f4121521613155515435d111302137e525a716c03"
},
{
"id": "turbo_hex_default",
"kind": "text",
"mode": "turbo",
"out": "hex",
"mid": "bt",
"note": "turbo in its default form",
"plaintext": "mode coverage sample",
"ciphertext": "69CES385aeff1f4179a744c8fb0c5ae4702d325f6230d059f4251135c2536409dee93{\"alg\":\"chaoscrypt\",\"b64\":true,\"cache\":\"hash\",\"compact\":true,\"flip\":\"conditional\",\"flipbits\":10,\"kdf\":\"shake256\",\"keybits\":16384,\"keyshort\":2048,\"kind\":\"ciphertext\",\"ksum\":\"8007e271aea2b261\",\"lib\":\"4.2.6\",\"mid\":\"bt\",\"mode\":\"turbo\",\"order\":\"base64>subst>flip>reverse>xor>xor\",\"out\":\"hex\",\"subst\":\"bijective\",\"utf8\":true,\"v\":1,\"xor_layers\":2}2025ea4e4b4b93803f2ccadeaf318d1957ce42ff5409410f660348be96a4c0f2568d8a131c130eef3c78ac317ed0f40bb7da2bb3"
},
{
"id": "turbo_hex_mid",
"kind": "text",
"mode": "turbo",
"out": "hex",
"mid": "hex",
"note": "turbo with a hex intermediate",
"plaintext": "mode coverage sample",
"ciphertext": "69CES385aeff1f4179a744c8fb0c5ae4702d325f6230d059f4251135c2536409dee93{\"alg\":\"chaoscrypt\",\"b64\":true,\"cache\":\"hash\",\"compact\":true,\"flip\":\"conditional\",\"flipbits\":10,\"kdf\":\"shake256\",\"keybits\":16384,\"keyshort\":2048,\"kind\":\"ciphertext\",\"ksum\":\"8007e271aea2b261\",\"lib\":\"4.2.6\",\"mid\":\"hex\",\"mode\":\"turbo\",\"order\":\"base64>subst>flip>reverse>xor>xor\",\"out\":\"hex\",\"subst\":\"bijective\",\"utf8\":true,\"v\":1,\"xor_layers\":2}2025ea4e4b4b93803f2ccadeaf318d1957ce42ff5409410f660348be96a4c0f2d6d808fc5bca259bec4b164a17418bb8b3ca098e9207e8a3aaf218b05faa270bd512f58b92372a07415e5c035d86277a0d971666c504ff9aa31519dce9f3a38f3bfae3f4f4934fb1ae92a1c57c55a216"
},
{
"id": "turbo_base64_default",
"kind": "text",
"mode": "turbo",
"out": "base",
"mid": "bt",
"note": "turbo with base64 output",
"plaintext": "mode coverage sample",
"ciphertext": "69CES385aeff1f4179a744c8fb0c5ae4702d325f6230d059f4251135c2536409dee93{\"alg\":\"chaoscrypt\",\"b64\":true,\"cache\":\"hash\",\"compact\":true,\"flip\":\"conditional\",\"flipbits\":10,\"kdf\":\"shake256\",\"keybits\":16384,\"keyshort\":2048,\"kind\":\"ciphertext\",\"ksum\":\"8007e271aea2b261\",\"lib\":\"4.2.6\",\"mid\":\"bt\",\"mode\":\"turbo\",\"order\":\"base64>subst>flip>reverse>xor>xor\",\"out\":\"base\",\"subst\":\"bijective\",\"utf8\":true,\"v\":1,\"xor_layers\":2}2025ea4e4b4b93803f2ccadeaf318d1957ce42ff5409410f660348be96a4c0f2Vo2KExwTDu88eKwxftD0C7faK7M="
},
{
"id": "raw_hex_default",
"kind": "text",
"mode": "raw",
"out": "hex",
"mid": "bt",
"note": "raw in its default form",
"plaintext": "mode coverage sample",
"ciphertext": "69CES385aeff1f4179a744c8fb0c5ae4702d325f6230d059f4251135c2536409dee93{\"alg\":\"chaoscrypt\",\"b64\":true,\"cache\":\"hash\",\"compact\":true,\"flip\":\"conditional\",\"flipbits\":10,\"kdf\":\"shake256\",\"keybits\":16384,\"keyshort\":2048,\"kind\":\"ciphertext\",\"ksum\":\"8007e271aea2b261\",\"lib\":\"4.2.6\",\"mid\":\"bt\",\"mode\":\"raw\",\"order\":\"base64>subst>flip>reverse>xor>xor\",\"out\":\"hex\",\"subst\":\"bijective\",\"utf8\":true,\"v\":1,\"xor_layers\":2}2025ea4e4b4b93803f2ccadeaf318d1957ce42ff5409410f660348be96a4c0f2f694f4e8672f3fc16483d837efbb6d298fa015a3"
},
{
"id": "raw_hex_mid",
"kind": "text",
"mode": "raw",
"out": "hex",
"mid": "hex",
"note": "raw with a hex intermediate",
"plaintext": "mode coverage sample",
"ciphertext": "69CES385aeff1f4179a744c8fb0c5ae4702d325f6230d059f4251135c2536409dee93{\"alg\":\"chaoscrypt\",\"b64\":true,\"cache\":\"hash\",\"compact\":true,\"flip\":\"conditional\",\"flipbits\":10,\"kdf\":\"shake256\",\"keybits\":16384,\"keyshort\":2048,\"kind\":\"ciphertext\",\"ksum\":\"8007e271aea2b261\",\"lib\":\"4.2.6\",\"mid\":\"hex\",\"mode\":\"raw\",\"order\":\"base64>subst>flip>reverse>xor>xor\",\"out\":\"hex\",\"subst\":\"bijective\",\"utf8\":true,\"v\":1,\"xor_layers\":2}2025ea4e4b4b93803f2ccadeaf318d1957ce42ff5409410f660348be96a4c0f267847ae69097a7286bc9d3e865d9f336ab78f3810b03b12184d10e44474079beb9a471f1d1d3b13a91808e0f5c111cad9b738545f48d51545a3f25edce7570b95060bcb456fda92bddbf60242457696c"
},
{
"id": "raw_base64_default",
"kind": "text",
"mode": "raw",
"out": "base",
"mid": "bt",
"note": "raw with base64 output",
"plaintext": "mode coverage sample",
"ciphertext": "69CES385aeff1f4179a744c8fb0c5ae4702d325f6230d059f4251135c2536409dee93{\"alg\":\"chaoscrypt\",\"b64\":true,\"cache\":\"hash\",\"compact\":true,\"flip\":\"conditional\",\"flipbits\":10,\"kdf\":\"shake256\",\"keybits\":16384,\"keyshort\":2048,\"kind\":\"ciphertext\",\"ksum\":\"8007e271aea2b261\",\"lib\":\"4.2.6\",\"mid\":\"bt\",\"mode\":\"raw\",\"order\":\"base64>subst>flip>reverse>xor>xor\",\"out\":\"base\",\"subst\":\"bijective\",\"utf8\":true,\"v\":1,\"xor_layers\":2}2025ea4e4b4b93803f2ccadeaf318d1957ce42ff5409410f660348be96a4c0f29pT06GcvP8Fkg9g377ttKY+gFaM="
}
],
"error_cases": [
{
"id": "empty_plaintext_rejected",
"kind": "encrypt",
"plaintext": "",
"password": "reference-user-password",
"expect_code": "E008",
"note": "Empty plaintext raises ChaosCrypt_ERR_EmptyPlaintext_E008."
},
{
"id": "empty_password_rejected",
"kind": "encrypt",
"plaintext": "hello",
"password": "",
"expect_code": "E006",
"note": "Empty encryption password raises ChaosCrypt_ERR_EmptyPassword_E006."
},
{
"id": "headerless_input_rejected",
"kind": "decrypt",
"ciphertext": "72370655031311011c111f261365172716020b69",
"password": "reference-user-password",
"expect_code": "E017",
"note": "Input without the magic header is not a CES artefact. This is the deliberate break from pre-4.2.6 material."
},
{
"id": "malformed_header_rejected",
"kind": "decrypt",
"ciphertext": "69CES0000000000000000000000000000000000000000000000000000000000000000{}000000000000000000000000000000000000000000000000000000000000000000",
"password": "reference-user-password",
"expect_code": "E018",
"note": "A bad marker or unusable JSON raises ChaosCrypt_ERR_MalformedHeader_E018."
},
{
"id": "empty_ciphertext_rejected",
"kind": "decrypt",
"ciphertext": "",
"password": "reference-user-password",
"expect_code": "E009",
"note": "Empty ciphertext raises ChaosCrypt_ERR_EmptyCiphertext_E009."
}
],
"known_answer_tests": [
{
"id": "digit_mapping_encode",
"input": "0123456789",
"expected": "ABCDEFGHIJ",
"note": "_encode_digit maps each decimal digit through digit_mapping."
},
{
"id": "equal_mapping_values",
"expected": {
"0": "W",
"1": "X",
"2": "Z",
"3": "Y"
},
"note": "equal_mapping maps padding counts to these distinct characters."
}
]
}