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
+85 -5
View File
@@ -45,7 +45,24 @@ from __future__ import annotations
import os
from typing import Optional
from ._core import ChaosCryptCore, KEYFILE_VERSION
from ._core import (
ChaosCryptCore,
KEYFILE_VERSION,
ENCODINGS,
ENC_HEX,
ENC_BASE64,
DEFAULT_ENCODING,
MIDS,
MID_BYTES,
MID_HEX,
DEFAULT_MID,
MODE_REFERENCE,
MODE_FAST,
MODE_TURBO,
MODE_RAW,
MODES,
DEFAULT_MODE,
)
from .errors import (
ChaosCryptError,
ChaosCrypt_ERR_KeyFileNotFound_E001,
@@ -66,7 +83,7 @@ from .errors import (
ChaosCrypt_ERR_UnsupportedKeyVersion_E016,
)
__version__ = "2.1.6"
__version__ = "4.2.6"
__author__ = "Dvs (DvsXT)"
__license__ = "MIT"
__all__ = [
@@ -75,6 +92,20 @@ __all__ = [
"__license__",
"DEFAULT_KEY_FILE",
"KEYFILE_VERSION",
"MODE_REFERENCE",
"MODE_FAST",
"MODE_TURBO",
"MODE_RAW",
"MODES",
"ENCODINGS",
"ENC_HEX",
"ENC_BASE64",
"DEFAULT_ENCODING",
"MIDS",
"MID_BYTES",
"MID_HEX",
"DEFAULT_MID",
"DEFAULT_MODE",
"ChaosCryptCore",
"ChaosCrypt",
"ChaosCryptError",
@@ -126,8 +157,11 @@ class ChaosCrypt:
*,
auto_load: bool = False,
default_key_file: str = DEFAULT_KEY_FILE,
mode: str = DEFAULT_MODE,
encoding: str = DEFAULT_ENCODING,
mid: str = DEFAULT_MID,
) -> None:
self.core = ChaosCryptCore()
self.core = ChaosCryptCore(mode, encoding=encoding, mid=mid)
self.key_file = key_file
self.key_password = key_password
self.default_key_file = default_key_file
@@ -269,8 +303,12 @@ class ChaosCrypt:
keys_data = self.core.generate_keymaterial()
obfuscated = self.core._obfuscate_keys(keys_data)
text = self.core._xor_encrypt_data(obfuscated, key_password)
# The returned text is exactly what would have been written to a key
# file, so it carries the header too.
document = self.core._emit(text, "key")
self.key_password = key_password
return text
return document
def info(self) -> dict:
"""Return a summary of the loaded key material.
@@ -336,12 +374,54 @@ class ChaosCrypt:
}
obfuscated = self.core._obfuscate_keys(keys_data)
encrypted = self.core._xor_encrypt_data(obfuscated, new_password)
# Every artefact carries a header, key files included. Writing the bare
# payload here would produce a file this library then refuses to load.
document = self.core._emit(encrypted, "key")
with open(target, 'w') as f:
f.write(encrypted)
f.write(document)
self.key_password = new_password
return target
# ==================================================================
# Performance settings
# ==================================================================
@property
def mode(self) -> str:
"""The active performance mode."""
return self.core.mode
@property
def encoding(self) -> str:
"""The active output encoding (used by turbo and raw)."""
return self.core.encoding
@property
def mid(self) -> str:
"""The active intermediate representation (used by turbo and raw)."""
return self.core.mid
def set_mid(self, mid: str) -> "ChaosCrypt":
"""Change the intermediate representation in place.
Only affects ``turbo`` and ``raw``; ``reference`` and ``fast`` are
character pipelines and always report ``hex``.
"""
self.core.mid = mid
return self
def set_encoding(self, encoding: str) -> "ChaosCrypt":
"""Change the output encoding in place.
Only affects ``turbo`` and ``raw``; ``reference`` and ``fast`` always
emit hex. Output decoded with the wrong encoding will fail rather than
silently produce garbage, so a ciphertext and its encoding must be kept
together.
"""
self.core.encoding = encoding
return self
# ==================================================================
# Encryption / decryption
# ==================================================================
+1366 -207
View File
File diff suppressed because it is too large Load Diff
+348
View File
@@ -0,0 +1,348 @@
"""
ChaosCrypt self-describing header.
Every key file and every ciphertext produced by this system begins with a
header that states exactly how the payload was produced. Nothing is inferred
from context, and nothing is accepted without a header.
Layout
------
b"69CES" magic bytes (hex 3639434553)
<BEGIN_MARKER> fixed hex marker (64 bytes)
{"kind": ..., ...} UTF-8 JSON configuration
<END_MARKER> fixed hex marker (64 bytes)
<payload> the key material or the ciphertext
The configuration JSON is complete on its own: it records the kind of payload,
the performance mode, whether the intermediate representation was bytes or hex,
the output encoding, the algorithm version, and the parameters needed to
reproduce the decryption path. A payload whose header is missing, truncated or
self-inconsistent is rejected rather than guessed at.
Rationale
---------
Earlier releases relied on the caller to remember which mode and encoding had
been used. That is a silent-corruption hazard: a ciphertext decrypted with the
wrong mode produces garbage that is indistinguishable from a wrong password.
Recording the parameters next to the ciphertext removes the ambiguity, and
rejecting headerless input removes the guesswork.
"""
from __future__ import annotations
import json
from typing import Any, Dict, Optional
from .errors import (
ChaosCrypt_ERR_MissingMagicHeader_E017,
ChaosCrypt_ERR_MalformedHeader_E018,
)
__all__ = [
"ENCODING_TO_OUT",
"OUT_TO_ENCODING",
"DEFAULT_MID",
"FIELD_IS_OLD",
"FIELD_OLD_IS_KEY",
"build_legacy_header",
"is_legacy",
"MAGIC",
"MAGIC_HEX",
"MAGIC_LIST",
"BEGIN_MARKER",
"END_MARKER",
"HEADER_VERSION",
"build_header",
"read_header",
"strip_header",
"has_magic",
]
# ---------------------------------------------------------------------------
# Fixed values
# ---------------------------------------------------------------------------
#: Magic bytes at the very start of every ChaosCrypt artefact.
MAGIC = b"69CES"
#: The same magic as hex text and as a list of byte values, for callers that
#: find one of those representations more convenient.
MAGIC_HEX = "3639434553"
MAGIC_LIST = [54, 57, 67, 69, 83]
#: Marker that opens the configuration block. Fixed, recorded verbatim.
BEGIN_MARKER = (
"385aeff1f4179a744c8fb0c5ae4702d325f6230d059f4251135c2536409dee93"
)
#: Marker that closes the configuration block.
END_MARKER = (
"2025ea4e4b4b93803f2ccadeaf318d1957ce42ff5409410f660348be96a4c0f2"
)
#: Version of the header format itself, independent of the algorithm version.
HEADER_VERSION = 1
#: Values accepted for the ``kind`` field.
KIND_CIPHERTEXT = "ciphertext"
KIND_KEY = "key"
KINDS = (KIND_CIPHERTEXT, KIND_KEY)
#: Values accepted for the ``mid`` (intermediate representation) field.
MID_BYTES = "bt"
MID_HEX = "hex"
MIDS = (MID_BYTES, MID_HEX)
#: Default intermediate representation for the byte-pipeline modes.
DEFAULT_MID = MID_BYTES
#: Values accepted for the ``out`` (output encoding) field.
OUT_HEX = "hex"
OUT_BASE = "base"
OUTS = (OUT_HEX, OUT_BASE)
#: Mapping from the constructor's encoding names to the header's vocabulary.
#: The constructor accepts ENC_HEX/ENC_BASE64; the header records OUT_HEX/OUT_BASE.
ENCODING_TO_OUT = {
"hex": OUT_HEX,
"base64": OUT_BASE,
}
#: And the reverse, for reading a header back into a constructor value.
OUT_TO_ENCODING = {v: k for k, v in ENCODING_TO_OUT.items()}
#: Required fields in every configuration block. Missing any one of these makes
#: the header invalid; the header is never partially trusted.
#: Field marking an artefact as produced by the pre-header implementation.
#: When present and true, **every other configuration field is ignored**; the
#: artefact is decrypted by the legacy path (see ``_core``). It is optional: a
#: normal artefact does not carry it at all.
FIELD_IS_OLD = "is_old"
#: Field naming what a legacy artefact is: true for a key file, false for a
#: ciphertext. Only meaningful alongside ``is_old``. Optional.
FIELD_OLD_IS_KEY = "old_is_key"
REQUIRED_FIELDS = (
"kind",
"v",
"mode",
"mid",
"out",
"alg",
"kdf",
"keybits",
"ksum",
)
# ---------------------------------------------------------------------------
# Building
# ---------------------------------------------------------------------------
def build_header(config: Dict[str, Any]) -> str:
"""Render a full header for ``config``.
Args:
config: The configuration dictionary. It must contain every name in
:data:`REQUIRED_FIELDS`.
Returns:
The header as text, ready to be prefixed to a payload.
Raises:
ChaosCrypt_ERR_MalformedHeader_E018: a required field is absent, or a
field holds a value outside its permitted set.
"""
# Legacy records carry only is_old and old_is_key; the strict field checks
# below do not apply to them.
legacy = bool(config.get(FIELD_IS_OLD))
if not legacy:
missing = [f for f in REQUIRED_FIELDS if f not in config]
if missing:
raise ChaosCrypt_ERR_MalformedHeader_E018(
detail="MissingConfigFields:" + ",".join(missing), code="E018"
)
if legacy:
body = json.dumps(config, ensure_ascii=False, sort_keys=True,
separators=(",", ":"))
return (MAGIC.decode("ascii") + BEGIN_MARKER + body + END_MARKER)
if config["kind"] not in KINDS:
raise ChaosCrypt_ERR_MalformedHeader_E018(
detail="BadKind:" + str(config["kind"]), code="E018"
)
if config["mid"] not in MIDS:
raise ChaosCrypt_ERR_MalformedHeader_E018(
detail="BadMid:" + str(config["mid"]), code="E018"
)
if config["out"] not in OUTS:
raise ChaosCrypt_ERR_MalformedHeader_E018(
detail="BadOut:" + str(config["out"]), code="E018"
)
# Deterministic key order so identical configurations render identically.
body = json.dumps(config, ensure_ascii=False, sort_keys=True,
separators=(",", ":"))
return (
MAGIC.decode("ascii")
+ BEGIN_MARKER
+ body
+ END_MARKER
)
def build_legacy_header(is_key: bool = False) -> str:
"""Render the minimal header used to wrap a pre-header artefact.
A legacy artefact has no header of its own, so one is synthesised before it
enters the normal decryption path. The synthesised header carries only the
two fields that matter -- ``is_old`` and ``old_is_key`` -- because once
``is_old`` is true every other field is ignored.
This keeps a single code path: the library always decrypts something that
has a header. Legacy support is a wrapper around that path, not a second
implementation of it.
Args:
is_key: Whether the artefact is a key file rather than a ciphertext.
Returns:
A complete header, ready to be prefixed to a legacy payload.
"""
body = json.dumps(
{FIELD_IS_OLD: True, FIELD_OLD_IS_KEY: bool(is_key)},
ensure_ascii=False, sort_keys=True, separators=(",", ":"),
)
return MAGIC.decode("ascii") + BEGIN_MARKER + body + END_MARKER
def is_legacy(text: str) -> bool:
"""Whether ``text`` is a headed legacy artefact.
Returns ``False`` for anything that is not a parseable header, so callers
can use this as a test rather than a validator.
"""
try:
cfg = read_header(text)
except Exception:
return False
return bool(cfg.get(FIELD_IS_OLD))
# ---------------------------------------------------------------------------
# Parsing
# ---------------------------------------------------------------------------
def has_magic(text: str) -> bool:
"""Whether ``text`` begins with the ChaosCrypt magic bytes."""
return text.startswith(MAGIC.decode("ascii"))
def read_header(text: str) -> Dict[str, Any]:
"""Parse the header from ``text`` and return its configuration.
Raises:
ChaosCrypt_ERR_MissingMagicHeader_E017: ``text`` does not start with the
magic. Callers must not attempt to guess the format.
ChaosCrypt_ERR_MalformedHeader_E018: a marker is missing or the JSON is
invalid or incomplete.
"""
if not text:
raise ChaosCrypt_ERR_MissingMagicHeader_E017(
detail="EmptyInput", code="E017"
)
magic = MAGIC.decode("ascii")
if not text.startswith(magic):
raise ChaosCrypt_ERR_MissingMagicHeader_E017()
body_at = len(magic)
if not text.startswith(BEGIN_MARKER, body_at):
raise ChaosCrypt_ERR_MalformedHeader_E018(
detail="MissingBeginMarker", code="E018"
)
body_at += len(BEGIN_MARKER)
end_at = text.find(END_MARKER, body_at)
if end_at < 0:
raise ChaosCrypt_ERR_MalformedHeader_E018(
detail="MissingEndMarker", code="E018"
)
body = text[body_at:end_at]
try:
config = json.loads(body)
except Exception:
raise ChaosCrypt_ERR_MalformedHeader_E018(
detail="InvalidHeaderJson", code="E018"
)
if not isinstance(config, dict):
raise ChaosCrypt_ERR_MalformedHeader_E018(
detail="HeaderJsonNotObject", code="E018"
)
# A legacy artefact carries only is_old and old_is_key. Everything else is
# meaningless for it, so the required-field check is skipped entirely --
# requiring kind/mode/... here would reject the very artefacts this branch
# exists to read.
if config.get(FIELD_IS_OLD):
if FIELD_OLD_IS_KEY in config and not isinstance(
config[FIELD_OLD_IS_KEY], bool
):
raise ChaosCrypt_ERR_MalformedHeader_E018(
detail="OldIsKeyNotBoolean", code="E018"
)
return config
missing = [f for f in REQUIRED_FIELDS if f not in config]
if missing:
raise ChaosCrypt_ERR_MalformedHeader_E018(
detail="MissingConfigFields:" + ",".join(missing), code="E018"
)
return config
def _payload_offset(text: str) -> int:
"""Index at which the payload begins, or ``-1`` if the header is unusable.
Markers are located by index so no intermediate copy of the payload is
made. The payload can be tens of megabytes; slicing the whole string three
times, as an earlier version did, costs three full copies per call and shows
up directly in throughput.
"""
magic = MAGIC.decode("ascii")
if not text.startswith(magic):
return -1
body_at = len(magic)
if not text.startswith(BEGIN_MARKER, body_at):
return -1
body_at += len(BEGIN_MARKER)
end_at = text.find(END_MARKER, body_at)
if end_at < 0:
return -1
return end_at + len(END_MARKER)
def strip_header(text: str) -> str:
"""Return the payload that follows the header.
The header is validated on the way through, so a malformed header raises
rather than yielding a payload.
Raises:
ChaosCrypt_ERR_MissingMagicHeader_E017: no magic present.
ChaosCrypt_ERR_MalformedHeader_E018: header could not be parsed.
"""
if not has_magic(text):
raise ChaosCrypt_ERR_MissingMagicHeader_E017()
read_header(text) # validate the record itself
offset = _payload_offset(text)
if offset < 0:
raise ChaosCrypt_ERR_MalformedHeader_E018(
detail="MissingEndMarker", code="E018"
)
return text[offset:] # a single slice
+55 -6
View File
@@ -22,7 +22,8 @@ import os
import sys
from typing import List, Optional
from . import DEFAULT_KEY_FILE, __version__
from . import (DEFAULT_KEY_FILE, __version__, MODES, DEFAULT_MODE,
ENCODINGS, DEFAULT_ENCODING, MIDS, DEFAULT_MID)
from .errors import ChaosCryptError, ChaosCrypt_ERR_InvalidArgument_E013
__all__ = ["build_parser", "main", "cli_main"]
@@ -102,6 +103,18 @@ def _add_global_flags(parser: argparse.ArgumentParser) -> None:
dest="quiet_local",
help="suppress non-essential human-readable output",
)
parser.add_argument(
"--mode", choices=MODES, default=None, dest="mode_local", metavar="MODE",
help="performance mode: reference / fast / turbo / raw",
)
parser.add_argument(
"--encoding", choices=ENCODINGS, default=None, dest="encoding_local",
metavar="ENC", help="output encoding for turbo/raw: hex / base64",
)
parser.add_argument(
"--mid", choices=MIDS, default=None, dest="mid_local", metavar="MID",
help="intermediate representation for turbo/raw: bt / hex",
)
def _add_password_opts(
@@ -179,6 +192,33 @@ def build_parser() -> argparse.ArgumentParser:
"-q", "--quiet", action="store_true",
help="suppress non-essential human-readable output",
)
parser.add_argument(
"--mid", choices=MIDS, default=None, metavar="MID",
help=(
"intermediate representation for turbo/raw: 'bt' (bytes, default, "
"2.00x expansion) or 'hex' (hexadecimal text, ~4x). Ignored by "
"reference/fast."
),
)
parser.add_argument(
"--encoding", choices=ENCODINGS, default=None, metavar="ENC",
help=(
"output encoding for turbo/raw: 'hex' (2.00x expansion) or "
"'base64' (1.33x). Ignored by reference/fast, which always emit "
f"hex. Default: {DEFAULT_ENCODING}"
),
)
parser.add_argument(
"--mode", choices=MODES, default=None, metavar="MODE",
help=(
"performance mode. "
"'reference' is the original algorithm (slowest, baseline); "
"'fast' is bit-for-bit identical to it but uses C-level bulk "
"operations; 'turbo' derives the keystream with SHAKE256 and is "
"far faster, but its ciphertexts are not interchangeable with the "
f"other two. Default: {DEFAULT_MODE}"
),
)
sub = parser.add_subparsers(dest="command", metavar="<command>")
@@ -400,7 +440,7 @@ def _cmd_keygen(args: argparse.Namespace) -> int:
args,
)
cc = ChaosCrypt()
cc = ChaosCrypt(mode=args.mode, encoding=args.encoding, mid=args.mid)
path = cc.create_key(pwd, args.key_file, overwrite=args.force)
_emit(
{"ok": True, "key_file": os.path.abspath(path)},
@@ -434,7 +474,7 @@ def _cmd_text(args: argparse.Namespace, mode: str) -> int:
args.text, args.in_file, "plaintext" if mode == "encrypt" else "ciphertext"
)
cc = ChaosCrypt()
cc = ChaosCrypt(mode=args.mode, encoding=args.encoding, mid=args.mid)
cc.load(args.key_file, key_pwd)
if mode == "encrypt":
@@ -483,7 +523,7 @@ def _cmd_file(args: argparse.Namespace, mode: str) -> int:
args,
)
cc = ChaosCrypt()
cc = ChaosCrypt(mode=args.mode, encoding=args.encoding, mid=args.mid)
cc.load(args.key_file, key_pwd)
if mode == "encrypt":
@@ -520,7 +560,7 @@ def _cmd_info(args: argparse.Namespace) -> int:
args,
)
cc = ChaosCrypt()
cc = ChaosCrypt(mode=args.mode, encoding=args.encoding, mid=args.mid)
cc.load(args.key_file, key_pwd)
info = cc.info()
@@ -560,7 +600,7 @@ def _cmd_chpwd(args: argparse.Namespace) -> int:
args,
)
cc = ChaosCrypt()
cc = ChaosCrypt(mode=args.mode, encoding=args.encoding, mid=args.mid)
path = cc.change_key_password(old, new, args.key_file)
_emit(
{"ok": True, "key_file": os.path.abspath(path)},
@@ -596,6 +636,15 @@ def main(argv: Optional[List[str]] = None) -> int:
or getattr(args, "json_local", False))
args.quiet = bool(getattr(args, "quiet", False)
or getattr(args, "quiet_local", False))
args.mode = (getattr(args, "mode", None)
or getattr(args, "mode_local", None)
or DEFAULT_MODE)
args.encoding = (getattr(args, "encoding", None)
or getattr(args, "encoding_local", None)
or DEFAULT_ENCODING)
args.mid = (getattr(args, "mid", None)
or getattr(args, "mid_local", None)
or DEFAULT_MID)
if args.command is None or args.command == "tui":
from .tui import run_tui
+14
View File
@@ -34,6 +34,8 @@ __all__ = [
"ChaosCrypt_ERR_FileReadFailed_E014",
"ChaosCrypt_ERR_FileWriteFailed_E015",
"ChaosCrypt_ERR_UnsupportedKeyVersion_E016",
"ChaosCrypt_ERR_MissingMagicHeader_E017",
"ChaosCrypt_ERR_MalformedHeader_E018",
]
@@ -143,3 +145,15 @@ ChaosCrypt_ERR_UnsupportedKeyVersion_E016 = _define(
"ChaosCrypt_ERR_UnsupportedKeyVersion_E016", "UnsupportedKeyVersion", "E016",
"The key file declares a format version this build cannot read.",
)
ChaosCrypt_ERR_MissingMagicHeader_E017 = _define(
"ChaosCrypt_ERR_MissingMagicHeader_E017", "MissingMagicHeader", "E017",
"The input does not begin with the ChaosCrypt magic header. Every key file "
"and ciphertext produced by this system carries a self-describing header; "
"input without one is rejected outright.",
)
ChaosCrypt_ERR_MalformedHeader_E018 = _define(
"ChaosCrypt_ERR_MalformedHeader_E018", "MalformedHeader", "E018",
"The ChaosCrypt header is present but could not be parsed: a marker is "
"missing, the JSON is invalid, or a required field is absent.",
)
+39
View File
@@ -71,6 +71,45 @@ TEXTS: Dict[str, Dict[str, str]] = {
"menu_keyinfo": {"en": "Show key information", "zh": "查看当前密钥信息"},
"menu_chpwd": {"en": "Change key file password", "zh": "修改密钥文件密码"},
"menu_lang": {"en": "Switch language", "zh": "切换语言"},
"menu_mode": {"en": "Performance mode", "zh": "性能模式"},
"menu_encoding": {"en": "Output encoding", "zh": "输出编码"},
"info_encoding": {"en": "Output encoding", "zh": "输出编码"},
"encoding_prompt": {"en": "Select output encoding", "zh": "请选择输出编码"},
"encoding_hex_desc": {
"en": "hex - 2 characters per byte, 2.00x expansion",
"zh": "hex - 每字节 2 字符,膨胀 2.00 倍",
},
"encoding_base64_desc": {
"en": "base64 - 4 characters per 3 bytes, 1.33x expansion",
"zh": "base64 - 每 3 字节 4 字符,膨胀 1.33 倍",
},
"encoding_changed": {"en": "Encoding set to", "zh": "输出编码已设为"},
"encoding_note": {
"en": "(only affects turbo and raw; reference and fast always emit hex)",
"zh": "(仅影响 turbo 与 raw;reference 与 fast 恒为 hex)",
},
"info_mode": {"en": "Performance mode", "zh": "性能模式"},
"mode_prompt": {
"en": "Select performance mode",
"zh": "请选择性能模式",
},
"mode_reference_desc": {
"en": "reference - original algorithm, slowest, ciphertext compatible",
"zh": "reference - 原版算法,最慢,密文兼容",
},
"mode_fast_desc": {
"en": "fast - identical ciphertext, C-level bulk operations",
"zh": "fast - 密文相同,C 级批量运算",
},
"mode_turbo_desc": {
"en": "turbo - SHAKE256 keystream, much faster, own ciphertext format",
"zh": "turbo - SHAKE256 密钥流,极快,独立密文格式",
},
"mode_raw_desc": {
"en": "raw - bytes throughout, fastest, smallest output, weakest",
"zh": "raw - 全程字节,最快,输出最小,强度最低",
},
"mode_changed": {"en": "Mode set to", "zh": "模式已设为"},
"menu_about": {"en": "About / security notice", "zh": "关于 / 安全声明"},
"menu_quit": {"en": "Quit", "zh": "退出"},
"menu_prompt": {"en": "Enter option", "zh": "请输入选项编号"},
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."
}
]
}
+80 -4
View File
@@ -15,7 +15,8 @@ import os
import sys
from typing import Optional
from . import DEFAULT_KEY_FILE, __version__, ChaosCrypt
from . import (DEFAULT_KEY_FILE, __version__, ChaosCrypt, MODES,
DEFAULT_MODE, ENCODINGS, DEFAULT_ENCODING)
from .errors import ChaosCryptError
from .i18n import DEFAULT_LANG, LANG_NAMES, t
@@ -135,10 +136,14 @@ class TUI:
"""Menu-driven bilingual interface over :class:`~chaoscrypt.ChaosCrypt`."""
def __init__(self, lang: str = DEFAULT_LANG,
key_file: str = DEFAULT_KEY_FILE) -> None:
key_file: str = DEFAULT_KEY_FILE,
mode: str = DEFAULT_MODE,
encoding: str = DEFAULT_ENCODING) -> None:
self.lang = lang if lang in LANG_NAMES else DEFAULT_LANG
self.key_file = key_file
self.cc = ChaosCrypt()
self.mode = mode if mode in MODES else DEFAULT_MODE
self.encoding = encoding if encoding in ENCODINGS else DEFAULT_ENCODING
self.cc = ChaosCrypt(mode=self.mode, encoding=self.encoding)
self.key_password: Optional[str] = None
# ------------------------------------------------------------------ view
@@ -162,7 +167,7 @@ class TUI:
if self.cc.loaded
else c("[ ] " + self._tr("no_key_loaded"), "red")
)
print(f"\n{state} {c(shown, 'dim')}")
print(f"\n{state} {c(shown, 'dim')} {c('[' + self.mode + ']', 'yellow')}")
def _print_error(self, exc: Exception) -> None:
"""Render a unified error, with a hint where one applies."""
@@ -190,6 +195,8 @@ class TUI:
("7", "menu_keyinfo"),
("8", "menu_chpwd"),
("9", "menu_lang"),
("m", "menu_mode"),
("e", "menu_encoding"),
("a", "menu_about"),
("q", "menu_quit"),
]
@@ -361,6 +368,8 @@ class TUI:
("info_short_key",
f"{info['short_key_length']} {self._tr('characters')}"),
("info_loaded", self._tr("yes")),
("info_mode", self.mode),
("info_encoding", self.encoding),
]
print()
print(c(_rule(), "dim"))
@@ -405,6 +414,69 @@ class TUI:
self.lang = choice
print(c(f" -> {LANG_NAMES[self.lang]}", "green"))
def action_mode(self) -> None:
"""Switch the performance mode of the active core."""
print()
for i, name in enumerate(MODES, 1):
mark = "*" if name == self.mode else " "
desc = self._tr(f"mode_{name}_desc")
print(f" {c('[' + str(i) + ']', 'cyan')} {mark} {desc}")
default_index = str(MODES.index(self.mode) + 1)
choice = _ask(self._tr("mode_prompt"), default_index)
try:
idx = int(choice) - 1
if 0 <= idx < len(MODES):
self.mode = MODES[idx]
except ValueError:
if choice in MODES:
self.mode = choice
# Rebuild the core so the new mode takes effect, then reload the key
# if one was already loaded so the user does not have to re-enter the
# password.
was_loaded = self.cc.loaded
path = self.cc.key_file or self.key_file
pwd = self.key_password
self.cc = ChaosCrypt(mode=self.mode, encoding=self.encoding)
if was_loaded and path and pwd:
try:
self.cc.load(path, pwd)
except ChaosCryptError:
pass
print(c(f" -> {self._tr('mode_changed')} {self.mode}", "green"))
def action_encoding(self) -> None:
"""Switch the output encoding (turbo and raw only)."""
print()
for i, name in enumerate(ENCODINGS, 1):
mark = "*" if name == self.encoding else " "
desc = self._tr(f"encoding_{name}_desc")
print(f" {c('[' + str(i) + ']', 'cyan')} {mark} {desc}")
print(c(" " + self._tr("encoding_note"), "dim"))
default_index = str(ENCODINGS.index(self.encoding) + 1)
choice = _ask(self._tr("encoding_prompt"), default_index)
try:
idx = int(choice) - 1
if 0 <= idx < len(ENCODINGS):
self.encoding = ENCODINGS[idx]
except ValueError:
if choice in ENCODINGS:
self.encoding = choice
# Rebuild so the new encoding applies, then restore the loaded key.
was_loaded = self.cc.loaded
path = self.cc.key_file or self.key_file
pwd = self.key_password
self.cc = ChaosCrypt(mode=self.mode, encoding=self.encoding)
if was_loaded and path and pwd:
try:
self.cc.load(path, pwd)
except ChaosCryptError:
pass
print(c(f" -> {self._tr('encoding_changed')} {self.encoding}", "green"))
def action_about(self) -> None:
print()
print(c(self._tr("about_body"), "cyan"))
@@ -439,6 +511,10 @@ class TUI:
self.action_chpwd()
elif choice == "9":
self.action_lang()
elif choice in ("m", "mode"):
self.action_mode()
elif choice in ("e", "encoding"):
self.action_encoding()
elif choice in ("a", "about"):
self.action_about()
elif choice in ("q", "quit", "exit"):