Files
ChaosCrypt/chaoscrypt/_core.py
T
dvs 2529edac1d v2.1.6: Restructure as a distributable library
Restructure ChaosCrypt from a single-file script into a complete,
installable Python package with three interfaces: a typed Python API, an
argument-driven CLI, and a bilingual interactive TUI.

The algorithm itself is unchanged. Ciphertexts and key files remain fully
interoperable with the original implementation in both directions, which is
enforced by dedicated tests rather than merely documented.

Added
- Library API: ChaosCrypt facade plus ChaosCryptCore for the raw algorithm
- Unified error hierarchy: 16 named types, all ChaosCryptError subclasses,
  rendering as ChaosCrypt_ERR_<Detail>_<Code>
- CLI: keygen, encrypt, decrypt, file, info, chpwd, tui, with --json output,
  stdin/stdout piping, and three password sources per secret
- Bilingual TUI: English default, runtime switch to Chinese, getpass password
  entry with a non-TTY fallback that keeps it scriptable
- Binary and file support: encrypt_bytes/decrypt_bytes and
  encrypt_file/decrypt_file
- Key management: change_key_password rewraps without altering key material;
  export_key_text/load_from_text move a key without touching disk
- Documentation: SECURITY.md with the full design and threat analysis, plus
  docs/ covering the API, CLI, architecture and build process
- Test suite: 92 tests across round-trips, binary safety, key management,
  error types, CLI, TUI, i18n and legacy interoperability
- Packaging: pyproject.toml, setup.py compatibility shim, MANIFEST.in,
  py.typed, examples, MIT licence

Fixed
- Conflicting --pwd option between the -p and -P groups prevented the CLI
  from starting at all
- Wrong key file password reported as file corruption (E002); structural
  validation now distinguishes it from a damaged file (E003)
- export_key_text produced key material without loading it into the instance
- Non-hexadecimal input was accepted as ciphertext and silently decrypted
  into garbage, making corruption indistinguishable from success; malformed
  input now raises E010 before any processing
- TUI failed under piped input because getpass requires a TTY
- TUI kept reading the default key file name after generating a new one

Changed
- Source tree reorganised: the package lives at chaoscrypt/, with tests,
  examples and legacy alongside it; documentation and build artefacts at the
  repository root
- Code comments unified in English; public docstrings document parameters,
  return values and raised exceptions
- English is now the default UI language
- ChaosCryptChat removed from the repository
- Attribution updated to Dvs (DvsXT); project URLs point to Gitea
2026-09-27 17:03:05 +08:00

741 lines
29 KiB
Python

"""
ChaosCrypt algorithm core.
This module is the algorithm itself. It is a faithful, behaviour-preserving
port of the original single-file implementation: every substitution table,
bit operation, loop bound and character-level rule is reproduced exactly.
What changed relative to the original script is only the *plumbing*:
* ``print`` / ``input`` calls were removed, so the module is usable as a library;
* failure paths raise :class:`~chaoscrypt.errors.ChaosCryptError` instead of
returning sentinel strings such as ``"decryption failed"``.
As a result, ciphertexts and key files are fully interoperable in **both**
directions with the original implementation.
Security notice
---------------
ChaosCrypt has not been independently audited and is not a standardised
cryptographic construction. It is intended for obfuscation, personal use, and
study. See ``SECURITY.md`` for the full design and threat analysis.
"""
from __future__ import annotations
import base64
import json
import os
from datetime import datetime
from .errors import (
ChaosCryptError,
ChaosCrypt_ERR_KeyNotLoaded_E004,
ChaosCrypt_ERR_KeyFileCorrupted_E002,
ChaosCrypt_ERR_KeyPasswordIncorrect_E003,
ChaosCrypt_ERR_DecryptionFailed_E011,
ChaosCrypt_ERR_EmptyPassword_E006,
ChaosCrypt_ERR_EmptyPlaintext_E008,
ChaosCrypt_ERR_EmptyCiphertext_E009,
ChaosCrypt_ERR_MalformedCiphertext_E010,
)
__all__ = ["ChaosCryptCore", "KEYFILE_VERSION"]
#: Version of the on-disk key file format.
KEYFILE_VERSION = 1
#: Print-range used throughout the algorithm (printable ASCII, 0x20..0x7E).
_PRINT_MIN = 32
_PRINT_MAX = 126
_PRINT_SPAN = 95
#: Marker separating the payload from its metadata inside the intermediate form.
_SEP = "|"
class ChaosCryptCore:
"""The ChaosCrypt algorithm, free of any I/O or user interaction.
Responsibilities:
* generating the random system key material (substitution tables, long and
short keys, flip pattern);
* wrapping that material into a password-protected key file;
* encrypting and decrypting text and arbitrary binary data.
Every failure is reported as a :class:`~chaoscrypt.errors.ChaosCryptError`
subclass.
"""
def __init__(self) -> None:
# Character remapping used to keep the ciphertext inside Base64's
# alphabet while the '=' padding is handled out-of-band.
self.special_encrypt = {
'+': '.',
'/': "'",
'=': '',
}
self.special_decrypt = {
'.': '+',
"'": '/',
}
self.flip_pattern = None
self.keys_loaded = False
# Key material; populated by generate_keymaterial() or load_keys*().
self.upper_mapping = None
self.lower_mapping = None
self.digit_mapping = None
self.equal_mapping = None
self.long_key = None
self.short_key = None
self.digit_reverse = None
self.equal_reverse = None
self.upper_original = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
self.lower_original = "abcdefghijklmnopqrstuvwxyz"
self.encrypt_map = {}
self.decrypt_map = {}
# ======================================================================
# Random key material
# ======================================================================
def _generate_random_alphabet(self, lowercase: bool = False) -> str:
"""Return a uniformly random permutation of the A-Z or a-z alphabet."""
chars = list(
"abcdefghijklmnopqrstuvwxyz" if lowercase
else "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
)
n = len(chars)
for i in range(n - 1, 0, -1):
j = int.from_bytes(os.urandom(1), 'big') % (i + 1)
chars[i], chars[j] = chars[j], chars[i]
return ''.join(chars)
def _generate_random_digit_mapping(self) -> dict:
"""Map each digit 0-9 to a distinct alphanumeric character."""
digits = list("0123456789")
mapping_chars = list(
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
)
n = len(mapping_chars)
for i in range(n - 1, 0, -1):
j = int.from_bytes(os.urandom(1), 'big') % (i + 1)
mapping_chars[i], mapping_chars[j] = (
mapping_chars[j], mapping_chars[i]
)
mapping = {}
for i, d in enumerate(digits):
mapping[d] = mapping_chars[i]
return mapping
def _generate_random_equal_mapping(self) -> dict:
"""Map the Base64 padding counts 0-3 to distinct characters."""
chars = list("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")
n = len(chars)
for i in range(n - 1, 0, -1):
j = int.from_bytes(os.urandom(1), 'big') % (i + 1)
chars[i], chars[j] = chars[j], chars[i]
return {
'0': chars[0],
'1': chars[1],
'2': chars[2],
'3': chars[3],
}
def _generate_random_flip_pattern(self) -> list:
"""Return a random 10-bit case-flip pattern."""
pattern = []
for _ in range(10):
bit = int.from_bytes(os.urandom(1), 'big') % 2
pattern.append(bit)
return pattern
def _generate_long_key(self, length: int = 4096) -> str:
"""Return a random hex string of ``length`` characters."""
chars = "0123456789abcdef"
result = []
for _ in range(length):
idx = int.from_bytes(os.urandom(1), 'big') % 16
result.append(chars[idx])
return ''.join(result)
def _generate_short_key(self, length: int = 512) -> str:
"""Return a shorter random hex string used for key derivation."""
chars = "0123456789abcdef"
result = []
for _ in range(length):
idx = int.from_bytes(os.urandom(1), 'big') % 16
result.append(chars[idx])
return ''.join(result)
# ======================================================================
# Key file wrapping
# ======================================================================
def _obfuscate_keys(self, keys_data: dict) -> str:
"""Encode the key material into a Base64 payload.
This is a transport encoding for the key file, not a security
boundary; confidentiality of the key file comes from the caller's
password (see :meth:`_xor_encrypt_data`).
"""
json_str = json.dumps(keys_data)
b64 = base64.b64encode(json_str.encode()).decode()
reversed_b64 = b64[::-1]
shifted = ''.join([chr((ord(c) + 1) % 128) for c in reversed_b64])
return base64.b64encode(shifted.encode()).decode()
def _deobfuscate_keys(self, obfuscated_data: str) -> dict:
"""Reverse :meth:`_obfuscate_keys`."""
try:
shifted = base64.b64decode(obfuscated_data.encode()).decode()
reversed_b64 = ''.join([chr((ord(c) - 1) % 128) for c in shifted])
b64 = reversed_b64[::-1]
json_str = base64.b64decode(b64.encode()).decode()
return json.loads(json_str)
except Exception:
raise ChaosCrypt_ERR_KeyFileCorrupted_E002()
# ======================================================================
# Password-based key file encryption
# ======================================================================
def _xor_encrypt_data(self, data: str, password: str) -> str:
"""XOR ``data`` with the repeated password, returning hex."""
result = []
key_len = len(password)
for i, char in enumerate(data):
xor_result = ord(char) ^ ord(password[i % key_len])
result.append(f"{xor_result:02x}")
return ''.join(result)
def _xor_decrypt_data(self, hex_data: str, password: str) -> str | None:
"""Reverse :meth:`_xor_encrypt_data`; ``None`` if the input is not hex."""
try:
result = []
key_len = len(password)
for i in range(0, len(hex_data), 2):
if i + 1 < len(hex_data):
hex_byte = hex_data[i:i + 2]
xor_result = (
int(hex_byte, 16) ^ ord(password[(i // 2) % key_len])
)
result.append(chr(xor_result))
return ''.join(result)
except Exception:
return None
# ======================================================================
# Key generation / loading
# ======================================================================
def generate_keymaterial(self) -> dict:
"""Generate a complete set of random key material.
The instance is left in the *loaded* state and is immediately usable
for encryption and decryption.
Returns:
The key material as a JSON-serialisable dictionary.
"""
self.upper_mapping = self._generate_random_alphabet(lowercase=False)
self.lower_mapping = self._generate_random_alphabet(lowercase=True)
self.digit_mapping = self._generate_random_digit_mapping()
self.equal_mapping = self._generate_random_equal_mapping()
self.flip_pattern = self._generate_random_flip_pattern()
self.long_key = self._generate_long_key(4096)
self.short_key = self._generate_short_key(512)
self.digit_reverse = {v: k for k, v in self.digit_mapping.items()}
self.equal_reverse = {v: k for k, v in self.equal_mapping.items()}
keys_data = {
'upper_mapping': self.upper_mapping,
'lower_mapping': self.lower_mapping,
'digit_mapping': self.digit_mapping,
'equal_mapping': self.equal_mapping,
'flip_pattern': self.flip_pattern,
'long_key': self.long_key,
'short_key': self.short_key,
'generated_at': datetime.now().isoformat(),
}
self.keys_loaded = True
self._build_maps()
return keys_data
def serialize_keys(self, key_password: str, save_path: str) -> str:
"""Generate key material and write it to ``save_path``.
The on-disk format is identical to the original implementation.
Returns:
The path that was written.
"""
if not key_password:
raise ChaosCrypt_ERR_EmptyPassword_E006(
detail="EmptyKeyFilePassword", code="E006"
)
keys_data = self.generate_keymaterial()
obfuscated = self._obfuscate_keys(keys_data)
encrypted = self._xor_encrypt_data(obfuscated, key_password)
with open(save_path, 'w') as f:
f.write(encrypted)
return save_path
def _build_maps(self) -> None:
"""Derive the forward and inverse character substitution maps."""
self.upper_original = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
self.lower_original = "abcdefghijklmnopqrstuvwxyz"
self.encrypt_map = {}
self.decrypt_map = {}
for i in range(26):
self.encrypt_map[self.upper_original[i]] = self.upper_mapping[i]
self.encrypt_map[self.lower_original[i]] = self.lower_mapping[i]
self.decrypt_map[self.upper_mapping[i]] = self.upper_original[i]
self.decrypt_map[self.lower_mapping[i]] = self.lower_original[i]
def load_keys_from_text(self, encrypted_data: str, key_password: str) -> None:
"""Load key material from the *contents* of a key file.
Raises:
ChaosCrypt_ERR_EmptyPassword_E006: no password supplied.
ChaosCrypt_ERR_KeyFileCorrupted_E002: not a plausible key file.
ChaosCrypt_ERR_KeyPasswordIncorrect_E003: password does not match.
"""
if not key_password:
raise ChaosCrypt_ERR_EmptyPassword_E006(
detail="EmptyKeyFilePassword", code="E006"
)
raw = (encrypted_data or "").strip()
if not raw:
raise ChaosCrypt_ERR_KeyFileCorrupted_E002(
detail="EmptyKeyFile", code="E002"
)
# A key file is hex text. Anything else is a malformed file rather
# than a wrong password, so report the two cases distinctly.
try:
int(raw[:2], 16)
bytes.fromhex(raw)
except (ValueError, TypeError):
raise ChaosCrypt_ERR_KeyFileCorrupted_E002(
detail="KeyFileNotHexadecimal", code="E002"
)
decrypted = self._xor_decrypt_data(raw, key_password)
if decrypted is None:
raise ChaosCrypt_ERR_DecryptionFailed_E011()
# A wrong password yields a payload that fails to decode; that is a
# credential problem, not a damaged file.
try:
keys_data = self._deobfuscate_keys(decrypted)
except ChaosCrypt_ERR_KeyFileCorrupted_E002:
raise ChaosCrypt_ERR_KeyPasswordIncorrect_E003()
try:
self.upper_mapping = keys_data['upper_mapping']
self.lower_mapping = keys_data['lower_mapping']
self.digit_mapping = keys_data['digit_mapping']
self.equal_mapping = keys_data['equal_mapping']
self.flip_pattern = keys_data['flip_pattern']
self.long_key = keys_data['long_key']
self.short_key = keys_data['short_key']
except (KeyError, TypeError):
raise ChaosCrypt_ERR_KeyFileCorrupted_E002()
# Structural sanity check: a wrong password can occasionally decode
# into well-formed JSON that is nonetheless nonsense.
ok = (
isinstance(self.upper_mapping, str) and len(self.upper_mapping) == 26
and isinstance(self.lower_mapping, str) and len(self.lower_mapping) == 26
and isinstance(self.long_key, str) and len(self.long_key) > 0
and isinstance(self.short_key, str) and len(self.short_key) > 0
and isinstance(self.flip_pattern, list) and len(self.flip_pattern) > 0
and sorted(self.upper_mapping) == sorted("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
and sorted(self.lower_mapping) == sorted("abcdefghijklmnopqrstuvwxyz")
and isinstance(self.digit_mapping, dict) and len(self.digit_mapping) == 10
and isinstance(self.equal_mapping, dict) and len(self.equal_mapping) == 4
)
if not ok:
raise ChaosCrypt_ERR_KeyPasswordIncorrect_E003()
self.digit_reverse = {v: k for k, v in self.digit_mapping.items()}
self.equal_reverse = {v: k for k, v in self.equal_mapping.items()}
self._build_maps()
self.keys_loaded = True
def load_keys(self, key_file: str, key_password: str) -> None:
"""Read a key file from disk and load it."""
with open(key_file, 'r') as f:
encrypted_data = f.read()
self.load_keys_from_text(encrypted_data, key_password)
# ======================================================================
# Internal primitives
# ======================================================================
def _ensure_printable(self, text: str) -> str:
"""Fold any character into the printable ASCII range.
``|`` (0x7C) is preserved because it is used as the metadata
separator.
"""
result = []
for c in text:
val = ord(c)
if val == 124:
result.append('|')
elif val < _PRINT_MIN or val > _PRINT_MAX:
val = val % _PRINT_SPAN + _PRINT_MIN
result.append(chr(val))
else:
result.append(c)
return ''.join(result)
def _mix_keys(self, user_password: str, target_length: int) -> str:
"""Mix the user password with the short key into a printable stream."""
if not self.keys_loaded:
raise ChaosCrypt_ERR_KeyNotLoaded_E004()
mixed = []
max_len = max(len(user_password), len(self.short_key))
for i in range(max_len):
if i < len(user_password):
mixed.append(ord(user_password[i]))
if i < len(self.short_key):
mixed.append(ord(self.short_key[i]))
for i in range(len(mixed)):
if i % 3 == 0:
mixed[i] = (mixed[i] << 1) & 0xFF
elif i % 3 == 1:
mixed[i] = (mixed[i] >> 1) & 0xFF
else:
mixed[i] = mixed[i] ^ 0x5A
for i in range(0, len(mixed) - 3, 4):
mixed[i], mixed[i + 3] = mixed[i + 3], mixed[i]
mixed[i + 1], mixed[i + 2] = mixed[i + 2], mixed[i + 1]
mixed.reverse()
result = []
for x in mixed:
if x < _PRINT_MIN or x > _PRINT_MAX:
x = x % _PRINT_SPAN + _PRINT_MIN
result.append(chr(x))
result_str = ''.join(result)
if len(result_str) < target_length:
base_key = result_str
final_key = base_key
iteration = 0
while len(final_key) < target_length:
if iteration % 3 == 0:
next_chunk = base_key[::-1]
elif iteration % 3 == 1:
next_chunk = base_key[::-1]
next_chunk = ''.join(
[chr((ord(c) + iteration) % _PRINT_SPAN + _PRINT_MIN)
for c in next_chunk]
)
else:
next_chunk = base_key[::-1]
next_chunk = ''.join(
[chr((ord(c) ^ iteration) % _PRINT_SPAN + _PRINT_MIN)
for c in next_chunk]
)
final_key += next_chunk
iteration += 1
result_str = final_key[:target_length]
return self._ensure_printable(result_str)
def _derive_final_key(self, user_password: str, text_length: int) -> str:
"""Derive a keystream of exactly ``text_length`` printable characters."""
mixed_key = self._mix_keys(user_password, text_length * 2)
hex_key = ''.join([f"{ord(c):02x}" for c in mixed_key])
reversed_hex = hex_key[::-1]
final_key = []
for i in range(0, len(reversed_hex), 2):
if i + 1 < len(reversed_hex):
hex_byte = reversed_hex[i:i + 2]
try:
val = int(hex_byte, 16)
if val < _PRINT_MIN or val > _PRINT_MAX:
val = val % _PRINT_SPAN + _PRINT_MIN
final_key.append(chr(val))
except ValueError:
final_key.append('x')
final_key_str = ''.join(final_key)
if len(final_key_str) < text_length:
base_key = final_key_str
iteration = 0
while len(final_key_str) < text_length:
if iteration % 3 == 0:
next_chunk = base_key[::-1]
elif iteration % 3 == 1:
next_chunk = base_key[::-1]
next_chunk = ''.join(
[chr((ord(c) + iteration) % _PRINT_SPAN + _PRINT_MIN)
for c in next_chunk]
)
else:
next_chunk = base_key[::-1]
next_chunk = ''.join(
[chr((ord(c) ^ iteration) % _PRINT_SPAN + _PRINT_MIN)
for c in next_chunk]
)
final_key_str += next_chunk
iteration += 1
final_key_str = final_key_str[:text_length]
return self._ensure_printable(final_key_str)
def _apply_flip(self, text: str) -> str:
"""Swap the case of letters at positions selected by the flip pattern."""
if self.flip_pattern is None:
return text
result = []
for i, ch in enumerate(text):
idx = i % len(self.flip_pattern)
if ch.isalpha() and self.flip_pattern[idx] == 1:
result.append(ch.swapcase())
else:
result.append(ch)
return ''.join(result)
def _xor_encrypt_with_final_key(self, text: str, user_password: str) -> str:
"""XOR with the password-derived keystream, returning hex."""
final_key = self._derive_final_key(user_password, len(text))
key_len = len(final_key)
result = []
for i, char in enumerate(text):
xor_result = ord(char) ^ ord(final_key[i % key_len])
result.append(f"{xor_result:02x}")
return ''.join(result)
def _xor_decrypt_with_final_key(
self, hex_text: str, user_password: str
) -> str | None:
"""Reverse :meth:`_xor_encrypt_with_final_key`."""
try:
text_length = len(hex_text) // 2
final_key = self._derive_final_key(user_password, text_length)
key_len = len(final_key)
result = []
for i in range(0, len(hex_text), 2):
if i + 1 < len(hex_text):
hex_byte = hex_text[i:i + 2]
try:
xor_result = (
int(hex_byte, 16)
^ ord(final_key[(i // 2) % key_len])
)
if xor_result < _PRINT_MIN or xor_result > _PRINT_MAX:
xor_result = xor_result % _PRINT_SPAN + _PRINT_MIN
result.append(chr(xor_result))
except ValueError:
result.append('?')
return ''.join(result)
except Exception:
return None
def _substitute_letters(self, text: str, mapping: dict) -> str:
"""Apply a single-character substitution table."""
return ''.join(mapping.get(char, char) for char in text)
def _encode_digit(self, num_str: str) -> str:
"""Encode a decimal string through the digit substitution table."""
return ''.join(self.digit_mapping.get(char, char) for char in num_str)
def _decode_digit(self, encoded_str: str) -> str:
"""Reverse :meth:`_encode_digit`."""
return ''.join(
self.digit_reverse.get(char, char) for char in encoded_str
)
def _get_dynamic_key(self, text_length: int) -> str:
"""Return the long key, repeated to cover ``text_length`` characters."""
key = self.long_key
while len(key) < text_length:
key += self.long_key
return key[:text_length]
def _xor_encrypt_with_key(self, text: str, key: str) -> str:
"""XOR with an explicit key, returning hex."""
key_len = len(key)
result = []
for i, char in enumerate(text):
xor_result = ord(char) ^ ord(key[i % key_len])
result.append(f"{xor_result:02x}")
return ''.join(result)
def _xor_decrypt_with_key(self, hex_text: str, key: str) -> str | None:
"""Reverse :meth:`_xor_encrypt_with_key`."""
try:
key_len = len(key)
result = []
for i in range(0, len(hex_text), 2):
if i + 1 < len(hex_text):
hex_byte = hex_text[i:i + 2]
try:
xor_result = (
int(hex_byte, 16) ^ ord(key[(i // 2) % key_len])
)
if xor_result < _PRINT_MIN or xor_result > _PRINT_MAX:
xor_result = xor_result % _PRINT_SPAN + _PRINT_MIN
result.append(chr(xor_result))
except ValueError:
result.append('?')
return ''.join(result)
except Exception:
return None
# ======================================================================
# Public: encrypt / decrypt
# ======================================================================
def encrypt_text(self, plaintext: str, user_password: str) -> str:
"""Encrypt a string and return the ciphertext as a hex string."""
if not self.keys_loaded:
raise ChaosCrypt_ERR_KeyNotLoaded_E004()
if not user_password:
raise ChaosCrypt_ERR_EmptyPassword_E006()
if plaintext is None or plaintext == "":
raise ChaosCrypt_ERR_EmptyPlaintext_E008()
# Stage 1 - Base64 lifts arbitrary bytes into printable ASCII.
b64 = base64.b64encode(plaintext.encode('utf-8')).decode('utf-8')
equal_count = b64.count('=')
# Stage 2 - remap the characters Base64 may emit.
processed = b64
for old, new in self.special_encrypt.items():
processed = processed.replace(old, new)
processed = processed.rstrip('=')
# Stage 3 - substitution, case flipping, reversal.
sub = self._substitute_letters(processed, self.encrypt_map)
flipped = self._apply_flip(sub)
reversed_text = flipped[::-1]
# Stage 4 - keep the padding count so decryption can restore it.
equal_char = self.equal_mapping[str(equal_count)]
with_equal = f"{reversed_text}{_SEP}{equal_char}"
key_length_str = str(len(with_equal))
key_length_encoded = self._encode_digit(key_length_str)
# Stage 5 - XOR with the long key, then with the password keystream.
dynamic_key = self._get_dynamic_key(len(with_equal))
encrypted_by_dynamic = self._xor_encrypt_with_key(with_equal, dynamic_key)
combined = f"{encrypted_by_dynamic}{_SEP}{key_length_encoded}"
return self._xor_encrypt_with_final_key(combined, user_password)
def decrypt_text(self, ciphertext: str, user_password: str) -> str:
"""Decrypt a hex ciphertext back into the original string."""
if not self.keys_loaded:
raise ChaosCrypt_ERR_KeyNotLoaded_E004()
if not user_password:
raise ChaosCrypt_ERR_EmptyPassword_E006()
if ciphertext is None or ciphertext == "":
raise ChaosCrypt_ERR_EmptyCiphertext_E009()
stripped = ciphertext.strip()
# Reject anything that is not well-formed hex up front: silently
# "decrypting" garbage would otherwise be indistinguishable from
# success.
if len(stripped) % 2 != 0:
raise ChaosCrypt_ERR_MalformedCiphertext_E010(
detail="OddLengthCiphertext", code="E010"
)
try:
int(stripped, 16)
except ValueError:
raise ChaosCrypt_ERR_MalformedCiphertext_E010(
detail="NonHexadecimalCiphertext", code="E010"
)
try:
combined = self._xor_decrypt_with_final_key(stripped, user_password)
if combined is None:
raise ChaosCrypt_ERR_DecryptionFailed_E011()
if _SEP in combined:
parts = combined.split(_SEP)
if len(parts) >= 2:
hex_data, key_length_encoded = parts[0], parts[1]
else:
hex_data, key_length_encoded = parts[0], 'g'
else:
hex_data, key_length_encoded = combined, 'g'
key_length_str = self._decode_digit(key_length_encoded)
try:
key_length = int(key_length_str)
except ValueError:
key_length = 16
dynamic_key = self._get_dynamic_key(key_length)
xor_decrypted = self._xor_decrypt_with_key(hex_data, dynamic_key)
if xor_decrypted is None:
raise ChaosCrypt_ERR_DecryptionFailed_E011()
if _SEP in xor_decrypted:
main_part, equal_char = xor_decrypted.split(_SEP)
equal_count = int(self.equal_reverse.get(equal_char, '0'))
else:
main_part, equal_count = xor_decrypted, 0
reversed_text = main_part[::-1]
flipped = self._apply_flip(reversed_text)
sub = self._substitute_letters(flipped, self.decrypt_map)
for old, new in self.special_decrypt.items():
sub = sub.replace(old, new)
b64_with_equal = sub + '=' * equal_count
if len(b64_with_equal) % 4 != 0:
raise ChaosCrypt_ERR_DecryptionFailed_E011()
raw = base64.b64decode(b64_with_equal.encode('utf-8'), validate=True)
return raw.decode('utf-8')
except ChaosCryptError:
raise
except Exception:
raise ChaosCrypt_ERR_DecryptionFailed_E011()
# ======================================================================
# Public: binary
# ======================================================================
def encrypt_bytes(self, data: bytes, user_password: str) -> str:
"""Encrypt arbitrary binary data, returning a hex ciphertext."""
if data is None or len(data) == 0:
raise ChaosCrypt_ERR_EmptyPlaintext_E008()
return self.encrypt_text(
base64.b64encode(data).decode('ascii'), user_password
)
def decrypt_bytes(self, ciphertext: str, user_password: str) -> bytes:
"""Decrypt a hex ciphertext back into the original binary data."""
text = self.decrypt_text(ciphertext, user_password)
try:
return base64.b64decode(text.encode('ascii'))
except Exception:
raise ChaosCrypt_ERR_DecryptionFailed_E011()