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

555 lines
18 KiB
Python

"""
ChaosCrypt - a chaos-based obfuscation cipher.
==============================================
Security notice
---------------
ChaosCrypt has **not** been independently audited and is **not** a
standardised cryptographic construction. It is designed for three purposes:
1. **Obfuscation** - making data unreadable to casual inspection;
2. **Personal use** - protecting your own notes, journals and backups;
3. **Research and teaching** - studying how layered obfuscation behaves.
Do not deploy it in production or in any safety-, privacy- or
compliance-critical system. If you need standardised cryptography, use a
vetted library such as ``cryptography`` (AES-GCM, ChaCha20-Poly1305).
The underlying construction is nonetheless substantially stronger than its
lack of audit might suggest: see ``SECURITY.md`` for the full design and
threat analysis, including the key-space derivation and the reasoning
behind each design decision.
Distributed under the MIT licence, provided as-is, without warranty.
Quick start
-----------
Library::
from chaoscrypt import ChaosCrypt
cc = ChaosCrypt()
cc.create_key("key-file-password", "my.key") # once, then keep it safe
token = cc.encrypt("hello world", "encryption-password")
assert cc.decrypt(token, "encryption-password") == "hello world"
Command line::
chaoscrypt # no arguments -> interactive TUI
chaoscrypt --help # arguments -> scriptable CLI
"""
from __future__ import annotations
import os
from typing import Optional
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,
ChaosCrypt_ERR_KeyFileCorrupted_E002,
ChaosCrypt_ERR_KeyPasswordIncorrect_E003,
ChaosCrypt_ERR_KeyNotLoaded_E004,
ChaosCrypt_ERR_KeyFileExists_E005,
ChaosCrypt_ERR_EmptyPassword_E006,
ChaosCrypt_ERR_PasswordMismatch_E007,
ChaosCrypt_ERR_EmptyPlaintext_E008,
ChaosCrypt_ERR_EmptyCiphertext_E009,
ChaosCrypt_ERR_MalformedCiphertext_E010,
ChaosCrypt_ERR_DecryptionFailed_E011,
ChaosCrypt_ERR_EncodingFailed_E012,
ChaosCrypt_ERR_InvalidArgument_E013,
ChaosCrypt_ERR_FileReadFailed_E014,
ChaosCrypt_ERR_FileWriteFailed_E015,
ChaosCrypt_ERR_UnsupportedKeyVersion_E016,
)
__version__ = "4.2.6"
__author__ = "Dvs (DvsXT)"
__license__ = "MIT"
__all__ = [
"__version__",
"__author__",
"__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",
"ChaosCrypt_ERR_KeyFileNotFound_E001",
"ChaosCrypt_ERR_KeyFileCorrupted_E002",
"ChaosCrypt_ERR_KeyPasswordIncorrect_E003",
"ChaosCrypt_ERR_KeyNotLoaded_E004",
"ChaosCrypt_ERR_KeyFileExists_E005",
"ChaosCrypt_ERR_EmptyPassword_E006",
"ChaosCrypt_ERR_PasswordMismatch_E007",
"ChaosCrypt_ERR_EmptyPlaintext_E008",
"ChaosCrypt_ERR_EmptyCiphertext_E009",
"ChaosCrypt_ERR_MalformedCiphertext_E010",
"ChaosCrypt_ERR_DecryptionFailed_E011",
"ChaosCrypt_ERR_EncodingFailed_E012",
"ChaosCrypt_ERR_InvalidArgument_E013",
"ChaosCrypt_ERR_FileReadFailed_E014",
"ChaosCrypt_ERR_FileWriteFailed_E015",
"ChaosCrypt_ERR_UnsupportedKeyVersion_E016",
]
#: Default key file name, matching the original implementation.
DEFAULT_KEY_FILE = "encryption.key"
class ChaosCrypt:
"""High-level facade over :class:`~chaoscrypt.ChaosCryptCore`.
Manages a key file and exposes convenient encryption/decryption helpers.
For the raw algorithm with no file handling at all, use
:class:`~chaoscrypt.ChaosCryptCore` directly.
Args:
key_file: Path to a key file. ``None`` loads nothing.
key_password: Password protecting that key file.
auto_load: When ``True``, load the key file during construction.
default_key_file: File name used when ``key_file`` is not given.
Raises:
ChaosCrypt_ERR_KeyFileNotFound_E001: ``key_file`` does not exist.
ChaosCrypt_ERR_KeyPasswordIncorrect_E003: wrong key file password.
ChaosCrypt_ERR_KeyFileCorrupted_E002: key file cannot be parsed.
"""
def __init__(
self,
key_file: Optional[str] = None,
key_password: Optional[str] = None,
*,
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(mode, encoding=encoding, mid=mid)
self.key_file = key_file
self.key_password = key_password
self.default_key_file = default_key_file
if auto_load:
self.load(key_file=key_file, key_password=key_password)
# ==================================================================
# State
# ==================================================================
@property
def loaded(self) -> bool:
"""Whether usable key material is currently held in memory."""
return self.core.keys_loaded
def is_loaded(self) -> bool:
"""Whether key material is loaded (method form)."""
return self.core.keys_loaded
def __repr__(self) -> str: # pragma: no cover - debugging aid
state = "loaded" if self.core.keys_loaded else "unloaded"
return f"<ChaosCrypt {state} key_file={self.key_file!r}>"
# ==================================================================
# Key management
# ==================================================================
def create_key(
self,
key_password: str,
key_file: Optional[str] = None,
*,
overwrite: bool = False,
) -> str:
"""Generate a fresh key file.
Args:
key_password: Password that will protect the key file.
key_file: Destination path; defaults to the configured file name.
overwrite: Replace an existing file rather than refusing.
Returns:
The path that was written.
Raises:
ChaosCrypt_ERR_EmptyPassword_E006: empty password.
ChaosCrypt_ERR_KeyFileExists_E005: file exists and not overwriting.
"""
if not key_password:
raise ChaosCrypt_ERR_EmptyPassword_E006(
detail="EmptyKeyFilePassword", code="E006"
)
target = key_file or self.key_file or self.default_key_file
if os.path.exists(target) and not overwrite:
raise ChaosCrypt_ERR_KeyFileExists_E005(
detail=f"KeyFileExists:{target}", code="E005"
)
try:
self.core.serialize_keys(key_password, target)
except ChaosCryptError:
raise
except OSError as exc:
raise ChaosCrypt_ERR_FileWriteFailed_E015(
detail=f"KeyFileWriteFailed:{exc}", code="E015"
)
self.key_file = target
self.key_password = key_password
return target
# Aliases kept for readability at call sites.
generate_keys = create_key
create_key_file = create_key
def load(
self,
key_file: Optional[str] = None,
key_password: Optional[str] = None,
) -> "ChaosCrypt":
"""Load a key file from disk.
Falls back to the instance attributes, then to the default file name.
Raises:
ChaosCrypt_ERR_KeyFileNotFound_E001: file is missing.
ChaosCrypt_ERR_KeyPasswordIncorrect_E003: wrong password.
ChaosCrypt_ERR_KeyFileCorrupted_E002: file is malformed.
"""
target = key_file or self.key_file or self.default_key_file
password = key_password if key_password is not None else self.key_password
if not os.path.exists(target):
raise ChaosCrypt_ERR_KeyFileNotFound_E001(
detail=f"KeyFileNotFound:{target}", code="E001"
)
if password is None:
raise ChaosCrypt_ERR_EmptyPassword_E006(
detail="NoKeyFilePassword", code="E006"
)
try:
self.core.load_keys(target, password)
except ChaosCryptError:
raise
except OSError as exc:
raise ChaosCrypt_ERR_FileReadFailed_E014(
detail=f"KeyFileReadFailed:{exc}", code="E014"
)
self.key_file = target
self.key_password = password
return self
def load_from_text(self, key_text: str, key_password: str) -> "ChaosCrypt":
"""Load key material straight from a key file's contents."""
self.core.load_keys_from_text(key_text, key_password)
return self
def export_key_text(self, key_password: str) -> str:
"""Generate key material and return it as text, without touching disk.
The instance becomes loaded and immediately usable. Useful for
storing a key in a password manager or transferring it over a
channel you already trust.
Args:
key_password: Password protecting the returned blob.
Returns:
Text identical to what would have been written to a key file.
"""
if not key_password:
raise ChaosCrypt_ERR_EmptyPassword_E006(
detail="EmptyKeyFilePassword", code="E006"
)
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 document
def info(self) -> dict:
"""Return a summary of the loaded key material.
Includes the substitution tables because they describe the key file's
structure. Treat the result as sensitive.
Raises:
ChaosCrypt_ERR_KeyNotLoaded_E004: nothing is loaded.
"""
if not self.core.keys_loaded:
raise ChaosCrypt_ERR_KeyNotLoaded_E004()
c = self.core
return {
"key_file": self.key_file,
"version": KEYFILE_VERSION,
"upper_mapping": c.upper_mapping,
"lower_mapping": c.lower_mapping,
"digit_mapping": c.digit_mapping,
"equal_mapping": c.equal_mapping,
"flip_pattern": c.flip_pattern,
"long_key_length": len(c.long_key),
"short_key_length": len(c.short_key),
"loaded": True,
}
def change_key_password(
self,
old_password: str,
new_password: str,
key_file: Optional[str] = None,
) -> str:
"""Re-wrap an existing key file under a new password.
The key material itself is unchanged, so data encrypted before the
change remains readable.
Returns:
The key file path.
"""
if not new_password:
raise ChaosCrypt_ERR_EmptyPassword_E006(
detail="EmptyNewPassword", code="E006"
)
target = key_file or self.key_file or self.default_key_file
if not os.path.exists(target):
raise ChaosCrypt_ERR_KeyFileNotFound_E001(
detail=f"KeyFileNotFound:{target}", code="E001"
)
# Verifies old_password before we overwrite anything.
self.load(target, old_password)
keys_data = {
'upper_mapping': self.core.upper_mapping,
'lower_mapping': self.core.lower_mapping,
'digit_mapping': self.core.digit_mapping,
'equal_mapping': self.core.equal_mapping,
'flip_pattern': self.core.flip_pattern,
'long_key': self.core.long_key,
'short_key': self.core.short_key,
'generated_at': __import__("datetime").datetime.now().isoformat(),
}
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(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
# ==================================================================
def _ensure_ready(self) -> None:
if not self.core.keys_loaded:
raise ChaosCrypt_ERR_KeyNotLoaded_E004()
def encrypt(self, plaintext: str, password: str) -> str:
"""Encrypt a string.
Args:
plaintext: Data to encrypt.
password: Encryption password, independent of the key file password.
Returns:
Ciphertext as a hexadecimal string.
"""
self._ensure_ready()
return self.core.encrypt_text(plaintext, password)
def decrypt(self, ciphertext: str, password: str) -> str:
"""Decrypt a hexadecimal ciphertext back into a string."""
self._ensure_ready()
return self.core.decrypt_text(ciphertext.strip(), password)
def encrypt_bytes(self, data: bytes, password: str) -> str:
"""Encrypt arbitrary binary data, returning a hex ciphertext."""
self._ensure_ready()
return self.core.encrypt_bytes(data, password)
def decrypt_bytes(self, ciphertext: str, password: str) -> bytes:
"""Decrypt a hex ciphertext back into binary data."""
self._ensure_ready()
return self.core.decrypt_bytes(ciphertext.strip(), password)
# ------------------------------------------------------------------
# File helpers
# ------------------------------------------------------------------
def encrypt_file(
self,
src: str,
password: str,
dst: Optional[str] = None,
) -> str:
"""Encrypt a file, writing UTF-8 hex ciphertext. Returns the output path."""
self._ensure_ready()
target = dst or (src + ".cc")
try:
with open(src, "rb") as f:
raw = f.read()
except OSError as exc:
raise ChaosCrypt_ERR_FileReadFailed_E014(
detail=f"FileReadFailed:{exc}", code="E014"
)
ct = self.encrypt_bytes(raw, password)
try:
with open(target, "w", encoding="utf-8") as f:
f.write(ct)
except OSError as exc:
raise ChaosCrypt_ERR_FileWriteFailed_E015(
detail=f"FileWriteFailed:{exc}", code="E015"
)
return target
def decrypt_file(
self,
src: str,
password: str,
dst: Optional[str] = None,
) -> str:
"""Decrypt a ``.cc`` ciphertext file back to its original bytes."""
self._ensure_ready()
target = dst or (src[:-3] if src.endswith(".cc") else src + ".out")
try:
with open(src, "r", encoding="utf-8") as f:
ct = f.read()
except OSError as exc:
raise ChaosCrypt_ERR_FileReadFailed_E014(
detail=f"FileReadFailed:{exc}", code="E014"
)
raw = self.decrypt_bytes(ct, password)
try:
with open(target, "wb") as f:
f.write(raw)
except OSError as exc:
raise ChaosCrypt_ERR_FileWriteFailed_E015(
detail=f"FileWriteFailed:{exc}", code="E015"
)
return target
# ======================================================================
# Module-level conveniences for one-off use
# ======================================================================
def encrypt(
plaintext: str,
password: str,
key_file: str = DEFAULT_KEY_FILE,
key_password: Optional[str] = None,
) -> str:
"""Load a key file and encrypt in one call.
When ``key_password`` is omitted it falls back to ``password``, which
suits setups where the same secret guards both layers.
"""
cc = ChaosCrypt()
cc.load(key_file, key_password if key_password is not None else password)
return cc.encrypt(plaintext, password)
def decrypt(
ciphertext: str,
password: str,
key_file: str = DEFAULT_KEY_FILE,
key_password: Optional[str] = None,
) -> str:
"""Load a key file and decrypt in one call."""
cc = ChaosCrypt()
cc.load(key_file, key_password if key_password is not None else password)
return cc.decrypt(ciphertext, password)
def create_key(
key_password: str,
key_file: str = DEFAULT_KEY_FILE,
*,
overwrite: bool = False,
) -> str:
"""Generate a key file in one call. Returns the path written."""
return ChaosCrypt().create_key(key_password, key_file, overwrite=overwrite)