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

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

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

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

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

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

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

713 lines
26 KiB
Python

"""
ChaosCrypt test suite.
Covers round-trip integrity, binary safety, key management, the unified error
types, CLI behaviour, i18n, and bidirectional compatibility with the original
single-file implementation.
"""
import base64
import json
import os
import subprocess
import sys
import pytest
from chaoscrypt import (
DEFAULT_KEY_FILE,
ChaosCrypt,
ChaosCryptCore,
ChaosCryptError,
ChaosCrypt_ERR_KeyFileNotFound_E001,
ChaosCrypt_ERR_KeyFileExists_E005,
ChaosCrypt_ERR_KeyNotLoaded_E004,
ChaosCrypt_ERR_EmptyPassword_E006,
ChaosCrypt_ERR_EmptyPlaintext_E008,
ChaosCrypt_ERR_DecryptionFailed_E011,
)
from chaoscrypt.i18n import LANG_NAMES, t
KEY_PWD = "key-file-password"
USER_PWD = "user-encryption-password"
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
@pytest.fixture
def keyfile(tmp_path):
"""Create a key file and return ``(ChaosCrypt, path)``."""
path = str(tmp_path / "test.key")
cc = ChaosCrypt()
cc.create_key(KEY_PWD, path)
return cc, path
@pytest.fixture
def loaded(keyfile):
"""Return an instance with key material already loaded."""
_, path = keyfile
n = ChaosCrypt()
n.load(path, KEY_PWD)
return n
# ---------------------------------------------------------------------------
# Round-trip
# ---------------------------------------------------------------------------
class TestRoundTrip:
SAMPLES = [
"hello",
"hello 世界",
"emoji test 🎉",
"a",
"x" * 1000,
"Mixed mixed 123!@#$%^&*()_+-=[]{}|;':\",./<>?",
"line1\nline2\ttabbed",
" leading and trailing ",
]
@pytest.mark.parametrize("text", SAMPLES)
def test_text_roundtrip(self, loaded, text):
ct = loaded.encrypt(text, USER_PWD)
assert loaded.decrypt(ct, USER_PWD) == text
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):
with pytest.raises(ChaosCryptError) as ei:
loaded.encrypt("", USER_PWD)
assert ei.value.code == "E008"
def test_empty_password_rejected(self, loaded):
with pytest.raises(ChaosCryptError) as ei:
loaded.encrypt("data", "")
assert ei.value.code == "E006"
def test_wrong_password_fails(self, loaded):
ct = loaded.encrypt("secret", USER_PWD)
with pytest.raises(ChaosCryptError) as ei:
loaded.decrypt(ct, "wrong-password")
assert ei.value.code == "E011"
def test_ciphertext_differs_per_password(self, loaded):
a = loaded.encrypt("same", "pwd-A")
b = loaded.encrypt("same", "pwd-B")
assert a != b
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 == "E017"
def test_headerless_odd_length_rejected(self, loaded):
with pytest.raises(ChaosCryptError) as ei:
loaded.decrypt("abc", USER_PWD)
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
# ---------------------------------------------------------------------------
class TestBinary:
@pytest.mark.parametrize("size", [1, 2, 255, 256, 4096, 100_000])
def test_binary_roundtrip(self, loaded, size):
raw = os.urandom(size)
ct = loaded.encrypt_bytes(raw, USER_PWD)
assert loaded.decrypt_bytes(ct, USER_PWD) == raw
def test_empty_binary_rejected(self, loaded):
with pytest.raises(ChaosCryptError):
loaded.encrypt_bytes(b"", USER_PWD)
def test_null_bytes_preserved(self, loaded):
raw = b"\x00\x01\x02\xff\xfe" * 100
ct = loaded.encrypt_bytes(raw, USER_PWD)
assert loaded.decrypt_bytes(ct, USER_PWD) == raw
# ---------------------------------------------------------------------------
# Key management
# ---------------------------------------------------------------------------
class TestKeyManagement:
def test_generate_and_load(self, tmp_path):
path = str(tmp_path / "k.key")
cc = ChaosCrypt()
assert cc.create_key(KEY_PWD, path) == path
assert os.path.exists(path)
n = ChaosCrypt()
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)
with pytest.raises(ChaosCryptError) as ei:
ChaosCrypt().create_key(KEY_PWD, path)
assert ei.value.code == "E005"
def test_keygen_force_overwrite(self, tmp_path):
path = str(tmp_path / "k.key")
cc = ChaosCrypt()
cc.create_key(KEY_PWD, path)
first_upper = cc.core.upper_mapping
cc.create_key(KEY_PWD, path, overwrite=True)
assert cc.core.upper_mapping != first_upper
def test_load_missing_file(self):
with pytest.raises(ChaosCryptError) as ei:
ChaosCrypt().load("/definitely/not/here.key", KEY_PWD)
assert ei.value.code == "E001"
def test_load_wrong_key_password(self, keyfile):
_, path = keyfile
with pytest.raises(ChaosCryptError) as ei:
ChaosCrypt().load(path, "bad-password")
assert ei.value.code == "E003"
def test_load_corrupted_file(self, tmp_path):
path = tmp_path / "bad.key"
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 == "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 in ("E002", "E017")
def test_encrypt_without_key_raises(self):
cc = ChaosCrypt()
with pytest.raises(ChaosCryptError) as ei:
cc.encrypt("data", USER_PWD)
assert ei.value.code == "E004"
def test_change_key_password(self, keyfile):
cc, path = keyfile
cc.change_key_password(KEY_PWD, "new-key-password", path)
ok = ChaosCrypt()
ok.load(path, "new-key-password")
assert ok.loaded
with pytest.raises(ChaosCryptError) as ei:
ChaosCrypt().load(path, KEY_PWD)
assert ei.value.code == "E003"
def test_change_password_preserves_data(self, keyfile):
cc, path = keyfile
ct = cc.encrypt("preserve me", USER_PWD)
cc.change_key_password(KEY_PWD, "brand-new-pwd", path)
n = ChaosCrypt()
n.load(path, "brand-new-pwd")
assert n.decrypt(ct, USER_PWD) == "preserve me"
def test_info_reports_key_sizes(self, loaded):
info = loaded.info()
assert info["long_key_length"] == 4096
assert info["short_key_length"] == 512
assert len(info["upper_mapping"]) == 26
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)
ct = n.encrypt("via text", USER_PWD)
assert cc.decrypt(ct, USER_PWD) == "via text"
def test_load_from_text_wrong_password(self):
cc = ChaosCrypt()
text = cc.export_key_text(KEY_PWD)
with pytest.raises(ChaosCryptError) as ei:
ChaosCrypt().load_from_text(text, "not-the-password")
assert ei.value.code == "E003"
# ---------------------------------------------------------------------------
# Key isolation
# ---------------------------------------------------------------------------
class TestKeyIsolation:
def test_two_keys_produce_different_ciphertext(self, tmp_path):
a = ChaosCrypt()
a.create_key(KEY_PWD, str(tmp_path / "a.key"))
b = ChaosCrypt()
b.create_key(KEY_PWD, str(tmp_path / "b.key"))
assert a.encrypt("same text", USER_PWD) != b.encrypt("same text", USER_PWD)
def test_cross_key_decryption_fails(self, tmp_path):
a = ChaosCrypt()
a.create_key(KEY_PWD, str(tmp_path / "a.key"))
b = ChaosCrypt()
b.create_key(KEY_PWD, str(tmp_path / "b.key"))
ct = a.encrypt("cross-key test", USER_PWD)
try:
got = b.decrypt(ct, USER_PWD)
except ChaosCryptError:
got = None
assert got != "cross-key test"
# ---------------------------------------------------------------------------
# File API
# ---------------------------------------------------------------------------
class TestFileAPI:
def test_encrypt_decrypt_file(self, loaded, tmp_path):
src = tmp_path / "data.bin"
payload = os.urandom(2048)
src.write_bytes(payload)
cc_file = str(tmp_path / "data.bin.cc")
out = loaded.encrypt_file(str(src), USER_PWD, cc_file)
assert os.path.exists(out)
dst = str(tmp_path / "restored.bin")
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")
out = loaded.encrypt_file(str(src), USER_PWD)
assert out.endswith(".cc")
back = loaded.decrypt_file(out, USER_PWD)
assert open(back, encoding="utf-8").read() == "hello file"
def test_missing_source_raises(self, loaded):
with pytest.raises(ChaosCryptError) as ei:
loaded.encrypt_file("/no/such/file.bin", USER_PWD)
assert ei.value.code == "E014"
# ---------------------------------------------------------------------------
# Unified error types
# ---------------------------------------------------------------------------
class TestErrorClass:
def test_message_format(self):
from chaoscrypt import ChaosCrypt_ERR_DecryptionFailed_E011
e = ChaosCrypt_ERR_DecryptionFailed_E011()
assert str(e).startswith("ChaosCrypt_ERR_")
assert str(e).endswith("_E011")
def test_code_and_detail_attributes(self):
e = ChaosCrypt_ERR_EmptyPlaintext_E008()
assert e.code == "E008"
assert e.detail == "EmptyPlaintext"
assert e.message == "ChaosCrypt_ERR_EmptyPlaintext_E008"
def test_all_errors_share_base(self):
from chaoscrypt import errors
for name in errors.__all__:
obj = getattr(errors, name)
if name == "ChaosCryptError":
continue
assert issubclass(obj, ChaosCryptError)
assert issubclass(obj, Exception)
def test_codes_are_unique(self):
from chaoscrypt import errors
codes = []
for name in errors.__all__:
obj = getattr(errors, name)
if name == "ChaosCryptError":
continue
codes.append(obj.CODE)
assert len(codes) == len(set(codes)), "duplicate error codes"
def test_custom_detail(self):
e = ChaosCrypt_ERR_KeyFileNotFound_E001(
detail="CustomDetail", code="E001"
)
assert e.detail == "CustomDetail"
assert e.code == "E001"
def test_catchable_as_generic_exception(self):
from chaoscrypt import ChaosCrypt_ERR_DecryptionFailed_E011
with pytest.raises(Exception):
raise ChaosCrypt_ERR_DecryptionFailed_E011()
# ---------------------------------------------------------------------------
# Algorithm compatibility
# ---------------------------------------------------------------------------
class TestLegacyCompatibility:
def test_format_matches_original_chain(self, loaded):
"""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 = strip_header(loaded.encrypt(text, USER_PWD))
core = loaded.core
combined = core._xor_decrypt_with_final_key(ct, USER_PWD)
hex_data, key_len_enc = combined.split("|")
key_len = int(core._decode_digit(key_len_enc))
x = core._xor_decrypt_with_key(hex_data, core._get_dynamic_key(key_len))
main, eq_char = x.split("|")
eq_count = int(core.equal_reverse[eq_char])
sub = core._substitute_letters(
core._apply_flip(main[::-1]), core.decrypt_map
)
for o, n in core.special_decrypt.items():
sub = sub.replace(o, n)
assert base64.b64decode((sub + "=" * eq_count).encode()).decode() == text
def test_keyfile_readable_by_original_scheme(self, keyfile):
"""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 = strip_header(f.read())
decrypted = core._xor_decrypt_data(enc, KEY_PWD)
assert decrypted is not None
data = core._deobfuscate_keys(decrypted)
assert set(data) >= {
"upper_mapping", "lower_mapping", "digit_mapping",
"equal_mapping", "flip_pattern", "long_key", "short_key",
}
assert len(data["long_key"]) == 4096
assert len(data["short_key"]) == 512
def test_reference_vector_stable(self):
"""Fixed key material must always produce the same ciphertext."""
core = ChaosCryptCore()
core.upper_mapping = "BCDEFGHIJKLMNOPQRSTUVWXYZA"
core.lower_mapping = "bcdefghijklmnopqrstuvwxyza"
core.digit_mapping = {
str(i): c for i, c in enumerate("ABCDEFGHIJ")
}
core.equal_mapping = {"0": "X", "1": "Y", "2": "Z", "3": "W"}
core.flip_pattern = [1, 0, 1, 0, 0, 1, 0, 0, 1, 0]
core.long_key = "0123456789abcdef" * 256
core.short_key = "fedcba9876543210" * 32
core.digit_reverse = {v: k for k, v in core.digit_mapping.items()}
core.equal_reverse = {v: k for k, v in core.equal_mapping.items()}
core._build_maps()
core.keys_loaded = True
plaintext = "reference vector"
ct1 = core.encrypt_text(plaintext, USER_PWD)
ct2 = core.encrypt_text(plaintext, USER_PWD)
assert ct1 == ct2
assert core.decrypt_text(ct1, USER_PWD) == plaintext
# ---------------------------------------------------------------------------
# i18n
# ---------------------------------------------------------------------------
class TestI18n:
def test_english_is_default(self):
import chaoscrypt.i18n as i18n
assert i18n.DEFAULT_LANG == "en"
def test_langs_available(self):
assert "en" in LANG_NAMES
assert "zh" in LANG_NAMES
def test_t_returns_both_languages(self):
en = t("app_title", "en")
zh = t("app_title", "zh")
assert en != zh
assert "ChaosCrypt" in en
def test_t_default_is_english(self):
assert t("app_title") == t("app_title", "en")
def test_t_fallback_for_unknown_key(self):
assert t("nonexistent_key_xyz", "en") == "nonexistent_key_xyz"
def test_missing_language_falls_back(self):
assert t("app_title", "fr") == t("app_title", "en")
def test_every_key_has_both_languages(self):
from chaoscrypt.i18n import TEXTS
for key, entry in TEXTS.items():
assert "en" in entry, f"{key} missing English"
assert "zh" in entry, f"{key} missing Chinese"
def test_tui_defaults_to_english(self):
from chaoscrypt.tui import TUI
tui = TUI()
assert tui.lang == "en"
assert tui._tr("menu_encrypt") == "Encrypt text"
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
class TestCLI:
@staticmethod
def _run(args, **kw):
return subprocess.run(
[sys.executable, "-m", "chaoscrypt"] + args,
capture_output=True, text=True, **kw,
)
def test_version(self):
from chaoscrypt import __version__
r = self._run(["--version"])
assert r.returncode == 0
assert __version__ in r.stdout
def test_help_mentions_scope(self):
r = self._run(["--help"])
assert r.returncode == 0
assert "unaudited" in r.stdout.lower()
def test_keygen_and_encrypt_decrypt(self, tmp_path):
kf = str(tmp_path / "cli.key")
r = self._run(["keygen", "-k", kf, "-P", KEY_PWD])
assert r.returncode == 0, r.stderr
assert os.path.exists(kf)
r = self._run(["encrypt", "cli round trip", "-p", USER_PWD,
"-k", kf, "-P", KEY_PWD])
assert r.returncode == 0, r.stderr
ct = r.stdout.strip()
r = self._run(["decrypt", ct, "-p", USER_PWD, "-k", kf, "-P", KEY_PWD])
assert r.returncode == 0, r.stderr
assert r.stdout.strip() == "cli round trip"
def test_json_output(self, tmp_path):
kf = str(tmp_path / "j.key")
self._run(["keygen", "-k", kf, "-P", KEY_PWD])
r = self._run(["--json", "encrypt", "json test", "-p", USER_PWD,
"-k", kf, "-P", KEY_PWD])
payload = json.loads(r.stdout)
assert payload["ok"] is True
assert payload["mode"] == "encrypt"
assert payload["ciphertext"]
def test_info_json_redacts_maps(self, tmp_path):
kf = str(tmp_path / "i.key")
self._run(["keygen", "-k", kf, "-P", KEY_PWD])
r = self._run(["--json", "info", "-k", kf, "-P", KEY_PWD])
payload = json.loads(r.stdout)
assert payload["long_key_length"] == 4096
assert "hidden" in payload["upper_mapping"]
def test_error_exit_code(self, tmp_path):
r = self._run(["decrypt", "zzzz", "-p", USER_PWD,
"-k", str(tmp_path / "nope.key"), "-P", KEY_PWD])
assert r.returncode == 1
assert "ChaosCrypt_ERR_" in r.stderr
def test_password_from_env(self, tmp_path):
kf = str(tmp_path / "env.key")
env = dict(os.environ, CC_KP=KEY_PWD, CC_UP=USER_PWD)
r = self._run(["keygen", "-k", kf, "--key-pwd-env", "CC_KP"], env=env)
assert r.returncode == 0, r.stderr
r = self._run(["encrypt", "env test", "--pwd-env", "CC_UP",
"-k", kf, "-P", KEY_PWD], env=env)
assert r.returncode == 0, r.stderr
def test_password_from_file(self, tmp_path):
kf = str(tmp_path / "f.key")
pwd_file = tmp_path / ".pwd"
pwd_file.write_text(KEY_PWD + "\n", encoding="utf-8")
r = self._run(["keygen", "-k", kf, "--key-pwd-file", str(pwd_file)])
assert r.returncode == 0, r.stderr
def test_file_encrypt_decrypt(self, tmp_path):
kf = str(tmp_path / "f.key")
src = tmp_path / "in.txt"
src.write_text("file cli test", encoding="utf-8")
self._run(["keygen", "-k", kf, "-P", KEY_PWD])
r = self._run(["file", "encrypt", str(src), "-p", USER_PWD,
"-k", kf, "-P", KEY_PWD])
assert r.returncode == 0, r.stderr
cc_file = str(src) + ".cc"
assert os.path.exists(cc_file)
dst = str(tmp_path / "out.txt")
r = self._run(["file", "decrypt", cc_file, "-o", dst, "-p", USER_PWD,
"-k", kf, "-P", KEY_PWD])
assert r.returncode == 0, r.stderr
assert open(dst, encoding="utf-8").read() == "file cli test"
def test_json_flag_accepted_before_and_after_subcommand(self, tmp_path):
"""--json must work in either position, not only before the subcommand."""
kf = str(tmp_path / "pos.key")
self._run(["keygen", "-k", kf, "-P", KEY_PWD])
for args in (
["--json", "info", "-k", kf, "-P", KEY_PWD],
["info", "-k", kf, "-P", KEY_PWD, "--json"],
):
r = self._run(args)
assert r.returncode == 0, r.stderr
assert json.loads(r.stdout)["ok"] is True, args
def test_quiet_flag_accepted_before_and_after_subcommand(self, tmp_path):
kf = str(tmp_path / "q.key")
self._run(["keygen", "-k", kf, "-P", KEY_PWD])
for args in (
["--quiet", "encrypt", "x", "-p", USER_PWD, "-k", kf, "-P", KEY_PWD],
["encrypt", "x", "-p", USER_PWD, "-k", kf, "-P", KEY_PWD, "--quiet"],
):
r = self._run(args)
assert r.returncode == 0, r.stderr
assert r.stdout.strip() == "", args
def test_plain_output_is_bare_ciphertext(self, tmp_path):
"""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
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")
self._run(["keygen", "-k", kf, "-P", KEY_PWD])
r = self._run(["chpwd", "-k", kf, "-P", KEY_PWD,
"--new-pwd", "brand-new"])
assert r.returncode == 0, r.stderr
r = self._run(["info", "-k", kf, "-P", "brand-new"])
assert r.returncode == 0, r.stderr
# ---------------------------------------------------------------------------
# Core used directly
# ---------------------------------------------------------------------------
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"
# 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"
def test_key_material_sizes(self):
c = ChaosCryptCore()
c.generate_keymaterial()
assert len(c.upper_mapping) == 26
assert len(c.lower_mapping) == 26
assert len(c.digit_mapping) == 10
assert len(c.equal_mapping) == 4
assert len(c.flip_pattern) == 10
assert len(c.long_key) == 4096
assert len(c.short_key) == 512
def test_mappings_are_bijections(self):
c = ChaosCryptCore()
c.generate_keymaterial()
assert sorted(c.upper_mapping) == sorted("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
assert sorted(c.lower_mapping) == sorted("abcdefghijklmnopqrstuvwxyz")
assert len(set(c.digit_mapping.values())) == 10
assert len(set(c.equal_mapping.values())) == 4
def test_key_material_is_random_between_instances(self):
a = ChaosCryptCore()
a.generate_keymaterial()
b = ChaosCryptCore()
b.generate_keymaterial()
assert a.long_key != b.long_key
assert a.short_key != b.short_key
assert a.upper_mapping != b.upper_mapping