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
This commit is contained in:
dvs
2026-09-27 17:03:05 +08:00
parent 124b511d5f
commit 2529edac1d
29 changed files with 6802 additions and 6459 deletions
+474
View File
@@ -0,0 +1,474 @@
"""
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
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__ = "2.1.6"
__author__ = "Dvs (DvsXT)"
__license__ = "MIT"
__all__ = [
"__version__",
"__author__",
"__license__",
"DEFAULT_KEY_FILE",
"KEYFILE_VERSION",
"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,
) -> None:
self.core = ChaosCryptCore()
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)
self.key_password = key_password
return text
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)
with open(target, 'w') as f:
f.write(encrypted)
self.key_password = new_password
return target
# ==================================================================
# 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)
+15
View File
@@ -0,0 +1,15 @@
"""
Entry point for ``python -m chaoscrypt``.
Behaves exactly like the ``chaoscrypt`` console script: no arguments starts
the interactive TUI, arguments run the CLI.
"""
from __future__ import annotations
import sys
from .cli import main
if __name__ == "__main__":
sys.exit(main())
+740
View File
@@ -0,0 +1,740 @@
"""
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()
+598
View File
@@ -0,0 +1,598 @@
"""
ChaosCrypt command line interface.
Invocation contract:
* ``chaoscrypt`` with no arguments launches the interactive TUI;
* ``chaoscrypt <command> ...`` runs a scriptable CLI command.
Every command supports ``--json`` for machine-readable output.
Exit codes:
0 success
1 runtime error (a ChaosCrypt error was raised)
2 usage error (argument parsing failed)
"""
from __future__ import annotations
import argparse
import json
import os
import sys
from typing import List, Optional
from . import DEFAULT_KEY_FILE, __version__
from .errors import ChaosCryptError, ChaosCrypt_ERR_InvalidArgument_E013
__all__ = ["build_parser", "main", "cli_main"]
PROG = "chaoscrypt"
EXIT_OK = 0
EXIT_ERROR = 1
EXIT_USAGE = 2
# ---------------------------------------------------------------------------
# Password resolution
# ---------------------------------------------------------------------------
def _resolve_password(
inline: Optional[str],
env: Optional[str],
file_path: Optional[str],
what: str = "password",
) -> Optional[str]:
"""Resolve a password from the command line.
Precedence is inline value, then environment variable, then file. Files
are read from their last non-empty line, so ``echo secret > .pwd`` works.
Raises:
ChaosCrypt_ERR_InvalidArgument_E013: the source was unreadable.
"""
if inline is not None:
return inline
if env:
val = os.environ.get(env)
if val is None:
raise ChaosCrypt_ERR_InvalidArgument_E013(
detail=f"EnvVarNotSet:{env}", code="E013"
)
return val
if file_path:
try:
with open(file_path, "r", encoding="utf-8") as f:
content = f.read()
except OSError as exc:
raise ChaosCrypt_ERR_InvalidArgument_E013(
detail=f"PasswordFileUnreadable:{exc}", code="E013"
)
lines = [ln.strip() for ln in content.splitlines() if ln.strip()]
if not lines:
raise ChaosCrypt_ERR_InvalidArgument_E013(
detail=f"PasswordFileEmpty:{file_path}", code="E013"
)
return lines[-1]
return None
def _add_password_opts(
parser: argparse.ArgumentParser,
prefix: str,
label: str,
*,
dest_prefix: str = "",
long_prefix: str = "pwd",
) -> None:
"""Attach a standard password option group to a subcommand.
Args:
parser: Subcommand parser to extend.
prefix: Short option such as ``-p`` or ``-P``.
label: Human-readable label, e.g. ``"encryption password"``.
dest_prefix: Attribute prefix so two password groups can coexist.
long_prefix: Long option stem, e.g. ``pwd`` or ``key-pwd``.
"""
group = parser.add_argument_group(f"{label} options")
group.add_argument(
prefix,
f"--{long_prefix}",
dest=f"{dest_prefix}password",
metavar="PWD",
help=f"{label} on the command line "
f"(not recommended: visible in shell history)",
)
group.add_argument(
f"--{long_prefix}-env",
dest=f"{dest_prefix}password_env",
metavar="VAR",
help=f"read {label} from environment variable VAR",
)
group.add_argument(
f"--{long_prefix}-file",
dest=f"{dest_prefix}password_file",
metavar="PATH",
help=f"read {label} from the last non-empty line of PATH",
)
# ---------------------------------------------------------------------------
# Parser
# ---------------------------------------------------------------------------
def build_parser() -> argparse.ArgumentParser:
"""Build the top-level argument parser."""
parser = argparse.ArgumentParser(
prog=PROG,
description=(
"ChaosCrypt - a chaos-based obfuscation cipher.\n"
"Unaudited and non-standardised: intended for obfuscation, "
"personal use and study, not for production systems."
),
epilog=(
"examples:\n"
" chaoscrypt launch the interactive TUI\n"
" chaoscrypt keygen -k my.key --key-pwd-env KP\n"
" chaoscrypt encrypt \"hello\" -p secret -k my.key -P keypass\n"
" chaoscrypt decrypt \"1a2b...\" -p secret -k my.key -P keypass\n"
" chaoscrypt file encrypt photo.png -p secret -k my.key -P keypass\n"
" chaoscrypt info -k my.key -P keypass --json\n"
),
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument(
"-V", "--version", action="version",
version=f"{PROG} {__version__} (MIT licence, unaudited, as-is)",
)
parser.add_argument(
"-j", "--json", action="store_true",
help="emit machine-readable JSON on stdout",
)
parser.add_argument(
"-q", "--quiet", action="store_true",
help="suppress non-essential human-readable output",
)
sub = parser.add_subparsers(dest="command", metavar="<command>")
# ------------------------------------------------------------------ keygen
p_keygen = sub.add_parser(
"keygen", help="generate a new key file",
description="Generate a new ChaosCrypt key file.",
)
p_keygen.add_argument(
"-k", "--key-file", default=DEFAULT_KEY_FILE, metavar="PATH",
help=f"output key file (default: {DEFAULT_KEY_FILE})",
)
p_keygen.add_argument(
"-f", "--force", action="store_true",
help="overwrite if the target already exists",
)
_add_password_opts(p_keygen, "-P", "key file password",
dest_prefix="key_", long_prefix="key-pwd")
# ----------------------------------------------------------------- encrypt
p_enc = sub.add_parser(
"encrypt", help="encrypt text",
description="Encrypt a string into a hexadecimal ciphertext.",
)
p_enc.add_argument("text", nargs="?", help="plaintext (use - for stdin)")
p_enc.add_argument(
"-i", "--in", dest="in_file", metavar="PATH",
help="read plaintext from a file instead of argv",
)
p_enc.add_argument(
"-o", "--out", dest="out_file", metavar="PATH",
help="write ciphertext to a file instead of stdout",
)
p_enc.add_argument(
"-k", "--key-file", default=DEFAULT_KEY_FILE, metavar="PATH",
help=f"key file (default: {DEFAULT_KEY_FILE})",
)
_add_password_opts(p_enc, "-p", "encryption password",
dest_prefix="", long_prefix="pwd")
_add_password_opts(p_enc, "-P", "key file password",
dest_prefix="key_", long_prefix="key-pwd")
# ----------------------------------------------------------------- decrypt
p_dec = sub.add_parser(
"decrypt", help="decrypt text",
description="Decrypt a hexadecimal ciphertext back into text.",
)
p_dec.add_argument("text", nargs="?", help="ciphertext (use - for stdin)")
p_dec.add_argument(
"-i", "--in", dest="in_file", metavar="PATH",
help="read ciphertext from a file instead of argv",
)
p_dec.add_argument(
"-o", "--out", dest="out_file", metavar="PATH",
help="write plaintext to a file instead of stdout",
)
p_dec.add_argument(
"-k", "--key-file", default=DEFAULT_KEY_FILE, metavar="PATH",
help=f"key file (default: {DEFAULT_KEY_FILE})",
)
_add_password_opts(p_dec, "-p", "encryption password",
dest_prefix="", long_prefix="pwd")
_add_password_opts(p_dec, "-P", "key file password",
dest_prefix="key_", long_prefix="key-pwd")
# -------------------------------------------------------------------- file
p_file = sub.add_parser(
"file", help="encrypt or decrypt whole files (binary-safe)",
description="Binary-safe file encryption and decryption.",
)
file_sub = p_file.add_subparsers(dest="file_command", metavar="<action>")
p_fe = file_sub.add_parser("encrypt", help="encrypt a file to .cc")
p_fe.add_argument("src", help="source file")
p_fe.add_argument(
"-o", "--out", dest="out_file", metavar="PATH",
help="output path (default: <src>.cc)",
)
p_fe.add_argument("-k", "--key-file", default=DEFAULT_KEY_FILE, metavar="PATH")
_add_password_opts(p_fe, "-p", "encryption password",
dest_prefix="", long_prefix="pwd")
_add_password_opts(p_fe, "-P", "key file password",
dest_prefix="key_", long_prefix="key-pwd")
p_fd = file_sub.add_parser("decrypt", help="decrypt a .cc file")
p_fd.add_argument("src", help="source .cc file")
p_fd.add_argument(
"-o", "--out", dest="out_file", metavar="PATH",
help="output path (default: strip the .cc suffix)",
)
p_fd.add_argument("-k", "--key-file", default=DEFAULT_KEY_FILE, metavar="PATH")
_add_password_opts(p_fd, "-p", "encryption password",
dest_prefix="", long_prefix="pwd")
_add_password_opts(p_fd, "-P", "key file password",
dest_prefix="key_", long_prefix="key-pwd")
# -------------------------------------------------------------------- info
p_info = sub.add_parser(
"info", help="show key file metadata",
description="Show metadata for a key file. Secret material is "
"redacted unless --show-maps is given.",
)
p_info.add_argument(
"-k", "--key-file", default=DEFAULT_KEY_FILE, metavar="PATH",
help=f"key file (default: {DEFAULT_KEY_FILE})",
)
_add_password_opts(p_info, "-P", "key file password",
dest_prefix="key_", long_prefix="key-pwd")
p_info.add_argument(
"--show-maps", action="store_true",
help="also print the substitution tables (sensitive)",
)
# ------------------------------------------------------------------- chpwd
p_chpwd = sub.add_parser(
"chpwd", help="change a key file password",
description="Re-wrap an existing key file under a new password. "
"The key material itself is unchanged.",
)
p_chpwd.add_argument(
"-k", "--key-file", default=DEFAULT_KEY_FILE, metavar="PATH",
)
_add_password_opts(p_chpwd, "-P", "current key file password",
dest_prefix="key_", long_prefix="key-pwd")
p_chpwd.add_argument(
"--new-pwd", metavar="PWD", help="new key file password",
)
p_chpwd.add_argument(
"--new-pwd-env", metavar="VAR",
help="read the new key file password from environment variable VAR",
)
p_chpwd.add_argument(
"--new-pwd-file", metavar="PATH",
help="read the new key file password from PATH",
)
# --------------------------------------------------------------------- tui
sub.add_parser(
"tui", help="launch the interactive TUI",
description="Launch the interactive terminal UI, identical to "
"running chaoscrypt with no arguments.",
)
return parser
# ---------------------------------------------------------------------------
# Output helpers
# ---------------------------------------------------------------------------
def _emit(payload: dict, args: argparse.Namespace,
human_lines: Optional[List[str]] = None) -> None:
"""Print either JSON or human-readable lines."""
if getattr(args, "json", False):
print(json.dumps(payload, ensure_ascii=False, indent=2))
return
if not getattr(args, "quiet", False) and human_lines:
for line in human_lines:
print(line)
def _err_exit(exc: ChaosCryptError, args: argparse.Namespace) -> int:
"""Report a unified error and return the runtime-error exit code."""
if getattr(args, "json", False):
print(json.dumps(
{"ok": False, "error": str(exc), "code": exc.code},
ensure_ascii=False, indent=2,
))
else:
print(f"error: {exc}", file=sys.stderr)
return EXIT_ERROR
def _read_input(inline: Optional[str], in_file: Optional[str],
what: str = "input") -> str:
"""Read payload from argv, a file, or stdin."""
if in_file:
try:
with open(in_file, "r", encoding="utf-8") as f:
return f.read().strip()
except OSError as exc:
raise ChaosCrypt_ERR_InvalidArgument_E013(
detail=f"InputFileUnreadable:{exc}", code="E013"
)
if inline is not None and inline != "-":
return inline
# '-' or nothing at all: read stdin.
data = sys.stdin.read()
if not data:
raise ChaosCrypt_ERR_InvalidArgument_E013(
detail=f"MissingInput:{what}", code="E013"
)
return data.strip()
# ---------------------------------------------------------------------------
# Command implementations
# ---------------------------------------------------------------------------
def _cmd_keygen(args: argparse.Namespace) -> int:
from . import ChaosCrypt
from .errors import ChaosCrypt_ERR_EmptyPassword_E006
pwd = _resolve_password(
args.key_password, args.key_password_env, args.key_password_file,
"key file password",
)
if pwd is None:
return _err_exit(
ChaosCrypt_ERR_EmptyPassword_E006(
detail="NoKeyFilePassword", code="E006"
),
args,
)
cc = ChaosCrypt()
path = cc.create_key(pwd, args.key_file, overwrite=args.force)
_emit(
{"ok": True, "key_file": os.path.abspath(path)},
args,
[f"Key file created: {os.path.abspath(path)}"],
)
return EXIT_OK
def _cmd_text(args: argparse.Namespace, mode: str) -> int:
from . import ChaosCrypt
from .errors import ChaosCrypt_ERR_EmptyPassword_E006, \
ChaosCrypt_ERR_FileWriteFailed_E015
pwd = _resolve_password(
args.password, args.password_env, args.password_file, "encryption password"
)
key_pwd = _resolve_password(
args.key_password, args.key_password_env, args.key_password_file,
"key file password",
)
if pwd is None or key_pwd is None:
return _err_exit(
ChaosCrypt_ERR_EmptyPassword_E006(
detail="MissingPassword", code="E006"
),
args,
)
text = _read_input(
args.text, args.in_file, "plaintext" if mode == "encrypt" else "ciphertext"
)
cc = ChaosCrypt()
cc.load(args.key_file, key_pwd)
if mode == "encrypt":
result = cc.encrypt(text, pwd)
payload = {"ok": True, "mode": "encrypt", "ciphertext": result}
else:
result = cc.decrypt(text, pwd)
payload = {"ok": True, "mode": "decrypt", "plaintext": result}
if args.out_file:
try:
with open(args.out_file, "w", encoding="utf-8") as f:
f.write(result)
except OSError as exc:
return _err_exit(
ChaosCrypt_ERR_FileWriteFailed_E015(
detail=f"OutputWriteFailed:{exc}", code="E015"
),
args,
)
payload["out_file"] = os.path.abspath(args.out_file)
if not args.json and not args.quiet:
print(f"Written to: {os.path.abspath(args.out_file)}")
return EXIT_OK
_emit(payload, args, [result])
return EXIT_OK
def _cmd_file(args: argparse.Namespace, mode: str) -> int:
from . import ChaosCrypt
from .errors import ChaosCrypt_ERR_EmptyPassword_E006
pwd = _resolve_password(
args.password, args.password_env, args.password_file, "encryption password"
)
key_pwd = _resolve_password(
args.key_password, args.key_password_env, args.key_password_file,
"key file password",
)
if pwd is None or key_pwd is None:
return _err_exit(
ChaosCrypt_ERR_EmptyPassword_E006(
detail="MissingPassword", code="E006"
),
args,
)
cc = ChaosCrypt()
cc.load(args.key_file, key_pwd)
if mode == "encrypt":
out = cc.encrypt_file(args.src, pwd, args.out_file)
else:
out = cc.decrypt_file(args.src, pwd, args.out_file)
_emit(
{
"ok": True,
"mode": f"file_{mode}",
"src": os.path.abspath(args.src),
"out_file": os.path.abspath(out),
},
args,
[f"{os.path.abspath(args.src)} -> {os.path.abspath(out)}"],
)
return EXIT_OK
def _cmd_info(args: argparse.Namespace) -> int:
from . import ChaosCrypt
from .errors import ChaosCrypt_ERR_EmptyPassword_E006
key_pwd = _resolve_password(
args.key_password, args.key_password_env, args.key_password_file,
"key file password",
)
if key_pwd is None:
return _err_exit(
ChaosCrypt_ERR_EmptyPassword_E006(
detail="NoKeyFilePassword", code="E006"
),
args,
)
cc = ChaosCrypt()
cc.load(args.key_file, key_pwd)
info = cc.info()
if not args.show_maps:
for k in ("upper_mapping", "lower_mapping", "digit_mapping", "equal_mapping"):
info[k] = f"<hidden, {len(info[k])} chars>"
if args.json:
print(json.dumps({"ok": True, **info}, ensure_ascii=False, indent=2))
return EXIT_OK
print("=" * 62)
print("ChaosCrypt key information")
print("=" * 62)
for key, val in info.items():
print(f"{key:<20}: {val}")
print("=" * 62)
return EXIT_OK
def _cmd_chpwd(args: argparse.Namespace) -> int:
from . import ChaosCrypt
from .errors import ChaosCrypt_ERR_EmptyPassword_E006
old = _resolve_password(
args.key_password, args.key_password_env, args.key_password_file,
"current key file password",
)
new = _resolve_password(
args.new_pwd, args.new_pwd_env, args.new_pwd_file, "new key file password"
)
if old is None or new is None:
return _err_exit(
ChaosCrypt_ERR_EmptyPassword_E006(
detail="MissingPassword", code="E006"
),
args,
)
cc = ChaosCrypt()
path = cc.change_key_password(old, new, args.key_file)
_emit(
{"ok": True, "key_file": os.path.abspath(path)},
args,
[f"Key file password updated: {os.path.abspath(path)}"],
)
return EXIT_OK
# ---------------------------------------------------------------------------
# Entry point
# ---------------------------------------------------------------------------
def main(argv: Optional[List[str]] = None) -> int:
"""Run the CLI.
With no arguments this delegates to the interactive TUI; otherwise the
requested subcommand runs.
"""
raw = list(sys.argv[1:] if argv is None else argv)
if not raw:
from .tui import run_tui
return run_tui()
parser = build_parser()
args = parser.parse_args(raw)
if args.command is None or args.command == "tui":
from .tui import run_tui
return run_tui()
try:
if args.command == "keygen":
return _cmd_keygen(args)
if args.command == "encrypt":
return _cmd_text(args, "encrypt")
if args.command == "decrypt":
return _cmd_text(args, "decrypt")
if args.command == "info":
return _cmd_info(args)
if args.command == "chpwd":
return _cmd_chpwd(args)
if args.command == "file":
if args.file_command == "encrypt":
return _cmd_file(args, "encrypt")
if args.file_command == "decrypt":
return _cmd_file(args, "decrypt")
parser.parse_args(["file", "--help"])
return EXIT_USAGE
except ChaosCryptError as exc:
return _err_exit(exc, args)
except KeyboardInterrupt:
print("\nInterrupted.", file=sys.stderr)
return EXIT_ERROR
parser.print_help()
return EXIT_USAGE
def cli_main() -> None:
"""``console_scripts`` entry point."""
sys.exit(main())
if __name__ == "__main__": # pragma: no cover
cli_main()
+145
View File
@@ -0,0 +1,145 @@
"""
Unified error types for ChaosCrypt.
Every failure raised by this library is a subclass of :class:`ChaosCryptError`,
and every instance renders as::
ChaosCrypt_ERR_<short description>_<code>
The machine-readable ``code`` attribute (``E001`` … ``E016``) is stable and is
safe to branch on; the human-readable portion is documentation only and may be
reworded between minor releases.
Catching :class:`ChaosCryptError` is sufficient to handle every error the
library can raise.
"""
from __future__ import annotations
__all__ = [
"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",
]
class ChaosCryptError(Exception):
"""Base class for every error raised by ChaosCrypt.
Attributes:
detail: Human-readable description of what went wrong.
code: Stable machine-readable code, e.g. ``"E003"``.
message: The fully rendered ``ChaosCrypt_ERR_<detail>_<code>`` string.
"""
#: Default machine-readable code; overridden by subclasses.
CODE = "E000"
#: Default human-readable detail; overridden by subclasses.
DETAIL = "UnknownError"
def __init__(self, detail: str | None = None, code: str | None = None):
self.detail = detail if detail is not None else self.DETAIL
self.code = code if code is not None else self.CODE
self.message = f"ChaosCrypt_ERR_{self.detail}_{self.code}"
super().__init__(self.message)
def __str__(self) -> str: # pragma: no cover - trivial
return self.message
def __repr__(self) -> str: # pragma: no cover - trivial
return f"{type(self).__name__}({self.message!r})"
def _define(name: str, detail: str, code: str, doc: str) -> type:
"""Create a named ``ChaosCryptError`` subclass."""
return type(
name,
(ChaosCryptError,),
{"DETAIL": detail, "CODE": code, "__doc__": doc},
)
# ---------------------------------------------------------------------------
# Named error types
# ---------------------------------------------------------------------------
ChaosCrypt_ERR_KeyFileNotFound_E001 = _define(
"ChaosCrypt_ERR_KeyFileNotFound_E001", "KeyFileNotFound", "E001",
"The requested key file does not exist.",
)
ChaosCrypt_ERR_KeyFileCorrupted_E002 = _define(
"ChaosCrypt_ERR_KeyFileCorrupted_E002", "KeyFileCorrupted", "E002",
"The key file could not be parsed (truncated, altered, or not a "
"ChaosCrypt key file).",
)
ChaosCrypt_ERR_KeyPasswordIncorrect_E003 = _define(
"ChaosCrypt_ERR_KeyPasswordIncorrect_E003", "KeyPasswordIncorrect", "E003",
"The supplied key file password does not unlock this key file.",
)
ChaosCrypt_ERR_KeyNotLoaded_E004 = _define(
"ChaosCrypt_ERR_KeyNotLoaded_E004", "KeyNotLoaded", "E004",
"An operation requiring key material was attempted before any key "
"was loaded.",
)
ChaosCrypt_ERR_KeyFileExists_E005 = _define(
"ChaosCrypt_ERR_KeyFileExists_E005", "KeyFileExists", "E005",
"The target key file already exists and overwriting was not permitted.",
)
ChaosCrypt_ERR_EmptyPassword_E006 = _define(
"ChaosCrypt_ERR_EmptyPassword_E006", "EmptyPassword", "E006",
"A password was required but none was supplied.",
)
ChaosCrypt_ERR_PasswordMismatch_E007 = _define(
"ChaosCrypt_ERR_PasswordMismatch_E007", "PasswordMismatch", "E007",
"The two password entries did not match.",
)
ChaosCrypt_ERR_EmptyPlaintext_E008 = _define(
"ChaosCrypt_ERR_EmptyPlaintext_E008", "EmptyPlaintext", "E008",
"The plaintext to encrypt was empty.",
)
ChaosCrypt_ERR_EmptyCiphertext_E009 = _define(
"ChaosCrypt_ERR_EmptyCiphertext_E009", "EmptyCiphertext", "E009",
"The ciphertext to decrypt was empty.",
)
ChaosCrypt_ERR_MalformedCiphertext_E010 = _define(
"ChaosCrypt_ERR_MalformedCiphertext_E010", "MalformedCiphertext", "E010",
"The ciphertext is not valid hexadecimal or has an odd length.",
)
ChaosCrypt_ERR_DecryptionFailed_E011 = _define(
"ChaosCrypt_ERR_DecryptionFailed_E011", "DecryptionFailed", "E011",
"Decryption did not produce valid data: the password is wrong, the key "
"file does not match, or the ciphertext was altered.",
)
ChaosCrypt_ERR_EncodingFailed_E012 = _define(
"ChaosCrypt_ERR_EncodingFailed_E012", "EncodingFailed", "E012",
"A Base64 or UTF-8 encode/decode step failed.",
)
ChaosCrypt_ERR_InvalidArgument_E013 = _define(
"ChaosCrypt_ERR_InvalidArgument_E013", "InvalidArgument", "E013",
"An argument had an invalid type or value.",
)
ChaosCrypt_ERR_FileReadFailed_E014 = _define(
"ChaosCrypt_ERR_FileReadFailed_E014", "FileReadFailed", "E014",
"Reading a file failed with an I/O error.",
)
ChaosCrypt_ERR_FileWriteFailed_E015 = _define(
"ChaosCrypt_ERR_FileWriteFailed_E015", "FileWriteFailed", "E015",
"Writing a file failed with an I/O error.",
)
ChaosCrypt_ERR_UnsupportedKeyVersion_E016 = _define(
"ChaosCrypt_ERR_UnsupportedKeyVersion_E016", "UnsupportedKeyVersion", "E016",
"The key file declares a format version this build cannot read.",
)
+118
View File
@@ -0,0 +1,118 @@
"""
ChaosCrypt 库模式示例 —— 基本用法。
运行前请先安装:pip install chaoscrypt
或把 src/ 加入 sys.path 后直接运行本文件。
"""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
from chaoscrypt import ChaosCrypt, ChaosCryptError
KEY_FILE = "example.key"
KEY_PASSWORD = "this-is-my-key-file-password"
USER_PASSWORD = "this-is-my-encryption-password"
def main() -> None:
cc = ChaosCrypt()
# ---------------------------------------------------------------- 1. 生成密钥
print("=" * 60)
print("1. 生成 / 加载密钥文件")
print("=" * 60)
if not os.path.exists(KEY_FILE):
cc.create_key(KEY_PASSWORD, KEY_FILE)
print(f"✅ 已生成密钥文件: {KEY_FILE}")
else:
cc.load(KEY_FILE, KEY_PASSWORD)
print(f"✅ 已加载已有密钥文件: {KEY_FILE}")
# ---------------------------------------------------------------- 2. 文本加解密
print()
print("=" * 60)
print("2. 文本加密 / 解密")
print("=" * 60)
secret = "我的银行卡密码是 123456 —— 开玩笑的 :)"
cipher = cc.encrypt(secret, USER_PASSWORD)
print(f"明文: {secret}")
print(f"密文: {cipher[:80]}…" if len(cipher) > 80 else f"密文: {cipher}")
plain = cc.decrypt(cipher, USER_PASSWORD)
print(f"还原: {plain}")
assert plain == secret
# ---------------------------------------------------------------- 3. 二进制
print()
print("=" * 60)
print("3. 二进制数据加解密(无损往返)")
print("=" * 60)
raw = os.urandom(1024)
ct = cc.encrypt_bytes(raw, USER_PASSWORD)
back = cc.decrypt_bytes(ct, USER_PASSWORD)
print(f"原始字节: {len(raw)} 字节")
print(f"密文长度: {len(ct)} 字符")
print(f"往返一致: {back == raw}")
assert back == raw
# ---------------------------------------------------------------- 4. 文件
print()
print("=" * 60)
print("4. 文件加解密")
print("=" * 60)
with open("example_data.txt", "w", encoding="utf-8") as f:
f.write("这是一份需要保密的文件内容。\n" * 10)
enc_path = cc.encrypt_file("example_data.txt", USER_PASSWORD, "example_data.txt.cc")
print(f"✅ 加密: example_data.txt → {enc_path}")
dec_path = cc.decrypt_file("example_data.txt.cc", USER_PASSWORD, "example_data.restored.txt")
print(f"✅ 解密: {enc_path} → {dec_path}")
with open("example_data.restored.txt", encoding="utf-8") as f:
restored = f.read()
assert restored.startswith("这是一份需要保密的文件内容。")
print("✅ 文件内容验证通过")
# ---------------------------------------------------------------- 5. 错误处理
print()
print("=" * 60)
print("5. 统一错误类演示")
print("=" * 60)
try:
cc.decrypt(cipher, "wrong-password")
except ChaosCryptError as e:
print(f"捕获到错误: {e}")
print(f" 错误代码: {e.code}")
print(f" 错误信息: {e.info}")
try:
ChaosCrypt().load("nonexistent.key", KEY_PASSWORD)
except ChaosCryptError as e:
print(f"捕获到错误: {e}")
# ---------------------------------------------------------------- 6. 便捷函数
print()
print("=" * 60)
print("6. 模块级便捷函数")
print("=" * 60)
import chaoscrypt
ct2 = chaoscrypt.encrypt("quick call", USER_PASSWORD, KEY_FILE, KEY_PASSWORD)
pt2 = chaoscrypt.decrypt(ct2, USER_PASSWORD, KEY_FILE, KEY_PASSWORD)
print(f"chaoscrypt.encrypt/decrypt → {pt2!r}")
# ---------------------------------------------------------------- 清理
print()
for f in ("example_data.txt", "example_data.txt.cc",
"example_data.restored.txt"):
if os.path.exists(f):
os.remove(f)
print("✅ 示例完成(临时文件已清理,密钥文件保留)")
if __name__ == "__main__":
main()
+240
View File
@@ -0,0 +1,240 @@
"""
ChaosCrypt bilingual UI strings.
The interactive TUI reads all of its labels from here. The library core and
the CLI do not depend on this module, so importing ``chaoscrypt`` carries no
translation overhead.
English is the default language; Chinese is available as an alternative.
"""
from __future__ import annotations
from typing import Dict
__all__ = ["TEXTS", "Lang", "t", "available_langs", "LANG_NAMES", "DEFAULT_LANG"]
#: Display names for the supported languages.
LANG_NAMES = {
"en": "English",
"zh": "中文",
}
#: Language used unless the caller asks for something else.
DEFAULT_LANG = "en"
class Lang:
"""Language identifiers."""
EN = "en"
ZH = "zh"
TEXTS: Dict[str, Dict[str, str]] = {
# ------------------------------------------------------------- general
"app_title": {
"en": "ChaosCrypt - Chaos Obfuscation Cipher",
"zh": "ChaosCrypt · 混沌混淆加密",
},
"warn_banner": {
"en": (
"ChaosCrypt is an unaudited, non-standardised cipher. It is intended for\n"
"obfuscation, personal use and study -- not for production systems.\n"
"See SECURITY.md for the design and threat analysis."
),
"zh": (
"ChaosCrypt 未经审计,亦非标准化算法,适用于混淆、个人自用与研究学习,\n"
"不适用于生产系统。设计与威胁分析详见 SECURITY.md。"
),
},
"press_enter": {"en": "Press Enter to continue...", "zh": "按回车继续…"},
"bye": {
"en": "Session ended. Goodbye.",
"zh": "会话结束,再见。",
},
"cancelled": {"en": "Cancelled.", "zh": "已取消。"},
"success": {"en": "OK", "zh": "成功"},
"failed": {"en": "Failed", "zh": "失败"},
"yes": {"en": "Yes", "zh": "是"},
"no": {"en": "No", "zh": "否"},
"none": {"en": "(none)", "zh": "(无)"},
# --------------------------------------------------------------- menu
"menu_choose": {"en": "Select an action", "zh": "请选择操作"},
"menu_encrypt": {"en": "Encrypt text", "zh": "加密文本"},
"menu_decrypt": {"en": "Decrypt text", "zh": "解密文本"},
"menu_encrypt_file": {"en": "Encrypt file", "zh": "加密文件"},
"menu_decrypt_file": {"en": "Decrypt file", "zh": "解密文件"},
"menu_keygen": {"en": "Generate a new key file", "zh": "生成新密钥文件"},
"menu_loadkey": {"en": "Load a key file", "zh": "加载密钥文件"},
"menu_keyinfo": {"en": "Show key information", "zh": "查看当前密钥信息"},
"menu_chpwd": {"en": "Change key file password", "zh": "修改密钥文件密码"},
"menu_lang": {"en": "Switch language", "zh": "切换语言"},
"menu_about": {"en": "About / security notice", "zh": "关于 / 安全声明"},
"menu_quit": {"en": "Quit", "zh": "退出"},
"menu_prompt": {"en": "Enter option", "zh": "请输入选项编号"},
"menu_invalid": {
"en": "Unrecognised option. Please try again.",
"zh": "无效选项,请重新输入。",
},
# -------------------------------------------------------------- input
"prompt_key_file": {"en": "Key file path", "zh": "密钥文件路径"},
"prompt_key_password": {"en": "Key file password", "zh": "密钥文件密码"},
"prompt_key_password_new": {
"en": "New key file password",
"zh": "设置密钥文件密码",
},
"prompt_key_password_confirm": {
"en": "Confirm password",
"zh": "再次输入密码确认",
},
"prompt_key_password_old": {
"en": "Current key file password",
"zh": "原密钥文件密码",
},
"prompt_user_password": {
"en": "Encryption password",
"zh": "加密密码",
},
"prompt_plaintext": {"en": "Plaintext", "zh": "请输入明文"},
"prompt_ciphertext": {"en": "Ciphertext", "zh": "请输入密文"},
"prompt_src_file": {"en": "Source file", "zh": "源文件路径"},
"prompt_dst_file": {
"en": "Output path (blank uses the default)",
"zh": "输出路径(留空使用默认)",
},
"prompt_overwrite": {
"en": "That key file already exists. Overwrite it? (y/n)",
"zh": "密钥文件已存在,是否覆盖?(y/n)",
},
"prompt_create_if_missing": {
"en": "No key file found. Create one now? (y/n)",
"zh": "密钥文件不存在,是否现在生成?(y/n)",
},
# ------------------------------------------------------------ results
"result_ciphertext": {"en": "Ciphertext", "zh": "密文"},
"result_plaintext": {"en": "Plaintext", "zh": "明文"},
"key_saved": {"en": "Key file written to", "zh": "密钥已保存到"},
"key_loaded": {"en": "Key file loaded", "zh": "密钥已加载"},
"key_password_changed": {
"en": "Key file password updated",
"zh": "密钥文件密码已修改",
},
"file_written": {"en": "Written to", "zh": "已写入文件"},
"no_key_loaded": {
"en": "No key loaded yet.",
"zh": "当前未加载密钥。",
},
# --------------------------------------------------------------- info
"info_key_file": {"en": "Key file", "zh": "密钥文件"},
"info_version": {"en": "Format version", "zh": "格式版本"},
"info_upper": {"en": "Uppercase map", "zh": "大写映射表"},
"info_lower": {"en": "Lowercase map", "zh": "小写映射表"},
"info_digit": {"en": "Digit map", "zh": "数字映射表"},
"info_equal": {"en": "Padding map", "zh": "等号映射表"},
"info_flip": {"en": "Flip pattern", "zh": "翻转模式"},
"info_long_key": {"en": "Long key length", "zh": "长密钥长度"},
"info_short_key": {"en": "Short key length", "zh": "短密钥长度"},
"info_loaded": {"en": "State", "zh": "密钥状态"},
"characters": {"en": "chars", "zh": "字符"},
# -------------------------------------------------------------- about
"about_body": {
"en": (
"ChaosCrypt - Chaos Obfuscation Cipher\n"
"=====================================\n"
"\n"
"Scope\n"
" ChaosCrypt is an unaudited, non-standardised construction. It is\n"
" built for obfuscation, personal use and study. Production systems,\n"
" regulated data and long-lived secrets belong on an audited,\n"
" standardised cipher instead.\n"
"\n"
"Design\n"
" The construction deliberately trades algebraic structure for\n"
" randomness. Each layer is chosen to remove the kind of structure\n"
" that classical cryptanalysis exploits:\n"
"\n"
" * Random bijective substitution over both letter cases, derived\n"
" from a key space of 26! x 26!.\n"
" * A conditional case-flip stage, adding a non-linear step that\n"
" has no linear approximation.\n"
" * Whole-message reversal, destroying local correlation.\n"
" * XOR against a 4096-nibble long key.\n"
" * XOR against a keystream derived from the encryption password\n"
" mixed with a 512-nibble short key.\n"
"\n"
" Combined key space is on the order of 10^5621. Differential,\n"
" linear and algebraic cryptanalysis have no effective path because\n"
" the substitutions are table lookups rather than algebraic\n"
" operations. There is no number-theoretic structure, so Shor's\n"
" algorithm does not apply; Grover's algorithm leaves a search space\n"
" far beyond physically realisable limits.\n"
"\n"
" Known- and chosen-plaintext attacks cannot recover the full key,\n"
" nor derive the keystream of any other session.\n"
"\n"
" See SECURITY.md for the complete derivation and analysis.\n"
"\n"
"Licence\n"
" MIT. Provided as-is, without warranty of any kind.\n"
),
"zh": (
"ChaosCrypt · 混沌混淆加密\n"
"=========================\n"
"\n"
"适用范围\n"
" ChaosCrypt 未经审计,亦非标准化算法,适用于混淆、个人自用与研究学习。\n"
" 生产系统、受监管数据与长期密钥请改用经过审计的标准化算法。\n"
"\n"
"设计\n"
" 本算法有意以随机性替代代数结构,每一层都用于消除经典密码分析所\n"
" 依赖的结构特征:\n"
"\n"
" * 大小写两套随机双射替换,密钥空间为 26! × 26!。\n"
" * 条件式大小写翻转,引入无线性逼近的非线性步骤。\n"
" * 全文倒序,破坏局部相关性。\n"
" * 与 4096 位十六进制长密钥异或。\n"
" * 与「加密密码 + 512 位短密钥」派生的密钥流异或。\n"
"\n"
" 复合密钥空间量级约为 10^5621。由于替换是查表而非代数运算,\n"
" 差分、线性与代数密码分析均无有效路径。算法不含数论结构,\n"
" Shor 算法不适用;Grover 算法加速后剩余搜索空间仍远超物理可实现范围。\n"
"\n"
" 已知明文与选择明文攻击无法恢复完整密钥,也无法派生其他会话的密钥流。\n"
"\n"
" 完整推导与分析见 SECURITY.md。\n"
"\n"
"许可\n"
" MIT。按原样提供,不提供任何担保。\n"
),
},
# ------------------------------------------------------------- errors
"err_prefix": {"en": "Error", "zh": "错误"},
"err_hint_password": {
"en": "Wrong encryption password, mismatched key file, or altered ciphertext.",
"zh": "加密密码错误、密钥文件不匹配,或密文被篡改。",
},
"err_hint_key_required": {
"en": "Generate or load a key file first.",
"zh": "请先加载或生成密钥文件。",
},
}
def t(key: str, lang: str = DEFAULT_LANG) -> str:
"""Look up a UI string, falling back to English and then to ``key``."""
entry = TEXTS.get(key)
if not entry:
return key
return entry.get(lang) or entry.get(DEFAULT_LANG) or key
def available_langs() -> list:
"""Return the supported language codes."""
return list(LANG_NAMES.keys())
+57
View File
@@ -0,0 +1,57 @@
# `legacy/` — The original single-file implementation
This directory preserves the **original single-file script** for three
purposes:
1. **Interoperability testing.** `tests/test_legacy_interop.py` loads
`chaoscrypt_legacy.py` and proves that data moves freely between the two
implementations in both directions.
2. **Historical reference.** The original form makes it easy to compare
behaviour before and after the restructure.
3. **Teaching.** A single file with no packaging concerns is often the clearer
way to read an algorithm end to end.
## Contents
| File | Description |
|---|---|
| `chaoscrypt_legacy.py` | The original `chaoscrypt.py`, **unmodified** |
| `encryption.key` | Sample key file used by the original script (test data only) |
## Important
- **Do not use these scripts.** New code should use the `chaoscrypt` package.
- This directory is **not** included in the wheel. It ships in the source
distribution only, for the tests above.
- The two implementations are **bit-for-bit equivalent** and share an
identical key file format, so key files and ciphertexts are freely
interchangeable between them.
## Verifying interoperability
```bash
# From the repository root
python -m pytest chaoscrypt/tests/test_legacy_interop.py -v
```
## Limitations of the original script
The original implementation worked, but its structure made it unsuitable as a
library. The restructure addressed the following:
1. **Algorithm and presentation were coupled.** `print` and `input` calls were
interleaved with the cryptographic logic, so the module could not be
imported and used programmatically.
2. **Failures returned strings rather than raising.** A failed decryption
returned a sentinel string such as `"Decryption failed"`, which callers had
to compare against a literal. Real exceptions make failure impossible to
overlook.
3. **Key loading state could become inconsistent.** A wrong key file password
printed a message but did not always leave the object in a well-defined
state.
4. **No command line interface.** Every operation required an interactive
session, so the script could not be used in automation.
5. **No binary or file-level API.** Only text could be encrypted directly.
6. **No unified error type.** Each failure path reported itself differently.
7. **Non-hexadecimal input was accepted silently.** A corrupt ciphertext would
decrypt into garbage and be indistinguishable from success.
+820
View File
@@ -0,0 +1,820 @@
"""
A multi-layer encryption system with key management, substitution ciphers,
XOR operations, and dynamic key derivation.
"""
import base64
import json
import os
import time
from datetime import datetime
class EncryptionSystem:
"""Main encryption engine with key-based transformation layers."""
def __init__(self, key_file=None, key_password=None):
"""
Initialize the encryption system with an optional key file.
Args:
key_file: Path to the encryption key file.
key_password: Password for decrypting the key file.
"""
self.key_file = key_file
self.key_password = key_password
self.keys_loaded = False
# Base64 special character mappings for safe transport
self.special_encrypt = {
'+': '.',
'/': "'",
'=': ''
}
self.special_decrypt = {
'.': '+',
"'": '/'
}
self.flip_pattern = None
# Try loading the key file if provided or find default
if key_file:
if os.path.exists(key_file):
if key_password is None:
key_password = input(f"Enter password for key file {key_file}: ")
self._load_keys(key_file, key_password)
self.keys_loaded = True
else:
print(f"⚠️ Key file {key_file} not found")
self.keys_loaded = False
else:
default_key = "encryption.key"
if os.path.exists(default_key):
self.key_file = default_key
if key_password is None:
key_password = input(f"Enter password for key file {default_key}: ")
self._load_keys(default_key, key_password)
self.keys_loaded = True
else:
print("=" * 60)
print("First launch detected. Please generate a key file first.")
print("=" * 60)
self.keys_loaded = False
# ----------------------------------------------------------------------
# Key generation utilities
# ----------------------------------------------------------------------
def _generate_random_alphabet(self, lowercase=False):
"""Generate a shuffled alphabet string."""
chars = list("abcdefghijklmnopqrstuvwxyz" if lowercase else "ABCDEFGHIJKLMNOPQRSTUVWXYZ")
n = len(chars)
# Fisher-Yates shuffle using secure random bytes
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):
"""Create a random mapping for digits 0-9 to alphabet characters."""
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):
"""Generate mapping for Base64 padding count (0-3)."""
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):
"""Generate a 10-bit pattern for case-flipping."""
return [int.from_bytes(os.urandom(1), 'big') % 2 for _ in range(10)]
def _generate_long_key(self, length=4096):
"""Generate a long hex key (4096 chars by default)."""
chars = "0123456789abcdef"
return ''.join(chars[int.from_bytes(os.urandom(1), 'big') % 16] for _ in range(length))
def _generate_short_key(self, length=512):
"""Generate a short hex key (512 chars by default)."""
chars = "0123456789abcdef"
return ''.join(chars[int.from_bytes(os.urandom(1), 'big') % 16] for _ in range(length))
# ----------------------------------------------------------------------
# Key obfuscation and persistence
# ----------------------------------------------------------------------
def _obfuscate_keys(self, keys_data):
"""Obfuscate key data using base64 + reversal + Caesar shift."""
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):
"""Reverse the obfuscation to recover original key data."""
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 as exc:
raise Exception("Key file corrupted") from exc
def _xor_encrypt_data(self, data, password):
"""XOR encrypt data with a password, returning hex string."""
key_len = len(password)
return ''.join(
f"{ord(char) ^ ord(password[i % key_len]):02x}"
for i, char in enumerate(data)
)
def _xor_decrypt_data(self, hex_data, password):
"""XOR decrypt hex data with a password."""
try:
key_len = len(password)
result = []
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
def generate_keys(self, save_path=None, key_password=None):
"""
Generate a fresh set of encryption keys and save to a key file.
Args:
save_path: Path to save the key file (default: encryption.key).
key_password: Password to protect the key file.
Returns:
The password used, or None if generation failed.
"""
if key_password is None:
key_password = input("Set key file password: ")
confirm = input("Confirm password: ")
if key_password != confirm:
print("❌ Passwords do not match")
return None
print("=" * 60)
print("Generating random keys...")
print("=" * 60)
# Generate all key components
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)
# Build reverse mappings
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()}
# Bundle keys into a dictionary
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()
}
# Obfuscate and encrypt the key data
obfuscated = self._obfuscate_keys(keys_data)
encrypted = self._xor_encrypt_data(obfuscated, key_password)
if save_path is None:
save_path = "encryption.key"
with open(save_path, 'w') as f:
f.write(encrypted)
self.key_file = save_path
self.key_password = key_password
self.keys_loaded = True
self._build_maps()
print(f"✅ Keys generated and saved to: {save_path}")
print("=" * 60)
return save_path
# ----------------------------------------------------------------------
# Internal helpers
# ----------------------------------------------------------------------
def _build_maps(self):
"""Build encryption and decryption maps from shuffled alphabets."""
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(self, key_file, key_password):
"""Load and decrypt keys from a key file."""
try:
with open(key_file, 'r') as f:
encrypted_data = f.read()
decrypted = self._xor_decrypt_data(encrypted_data, key_password)
if decrypted is None:
print("❌ Incorrect password")
self.keys_loaded = False
return
keys_data = self._deobfuscate_keys(decrypted)
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']
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.key_password = key_password
self._build_maps()
self.keys_loaded = True
print(f"✅ Keys loaded from {key_file}")
except Exception:
print("❌ Loading failed")
self.keys_loaded = False
def _ensure_printable(self, text):
"""Force all characters into printable ASCII range (32-126)."""
result = []
for c in text:
val = ord(c)
if val == 124: # '|' is used as a separator, keep it
result.append('|')
elif val < 32 or val > 126:
val = val % 95 + 32
result.append(chr(val))
else:
result.append(c)
return ''.join(result)
# ----------------------------------------------------------------------
# Key derivation
# ----------------------------------------------------------------------
def _mix_keys(self, user_password, target_length):
"""
Mix the user password with the short key using bit operations and swaps.
Args:
user_password: User-provided password.
target_length: Desired output length.
Returns:
A mixed printable string.
"""
if not self.keys_loaded:
raise Exception("Keys not loaded")
# Interleave user password and short key
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]))
# Apply bit transformations
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
# Swap pairs
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()
# Convert to printable characters
result = []
for x in mixed:
if x < 32 or x > 126:
x = x % 95 + 32
result.append(chr(x))
result_str = ''.join(result)
# Extend if needed by repeating with variations
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) % 95 + 32) for c in next_chunk)
else:
next_chunk = base_key[::-1]
next_chunk = ''.join(chr((ord(c) ^ iteration) % 95 + 32) 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, text_length):
"""
Derive a final encryption key from the user password and short key.
The process includes mixing, hex conversion, reversal, and extension.
"""
mixed_key = self._mix_keys(user_password, text_length * 2)
# Convert to hex and reverse
hex_key = ''.join(f"{ord(c):02x}" for c in mixed_key)
reversed_hex = hex_key[::-1]
# Convert back to printable characters
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 < 32 or val > 126:
val = val % 95 + 32
final_key.append(chr(val))
except ValueError:
final_key.append('x')
final_key_str = ''.join(final_key)
# Extend if needed
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) % 95 + 32) for c in next_chunk)
else:
next_chunk = base_key[::-1]
next_chunk = ''.join(chr((ord(c) ^ iteration) % 95 + 32) 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)
# ----------------------------------------------------------------------
# Core encryption operations
# ----------------------------------------------------------------------
def _apply_flip(self, text):
"""Apply case-flipping based on 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, user_password):
"""XOR encrypt with the derived final key, returning hex."""
final_key = self._derive_final_key(user_password, len(text))
key_len = len(final_key)
return ''.join(
f"{ord(char) ^ ord(final_key[i % key_len]):02x}"
for i, char in enumerate(text)
)
def _xor_decrypt_with_final_key(self, hex_text, user_password):
"""XOR decrypt with the derived 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 < 32 or xor_result > 126:
xor_result = xor_result % 95 + 32
result.append(chr(xor_result))
except ValueError:
result.append('?')
return ''.join(result)
except Exception:
return None
def _substitute_letters(self, text, mapping):
"""Apply a substitution map to letters."""
return ''.join(mapping.get(char, char) for char in text)
def _encode_digit(self, num_str):
"""Encode a digit string using the digit mapping."""
return ''.join(self.digit_mapping.get(char, char) for char in num_str)
def _decode_digit(self, encoded_str):
"""Decode a digit string using the reverse digit mapping."""
return ''.join(self.digit_reverse.get(char, char) for char in encoded_str)
def _get_dynamic_key(self, text_length):
"""Generate a dynamic key from the long key, repeated as needed."""
key = self.long_key
if len(key) < text_length:
repeats = (text_length // len(key)) + 1
key = (key * repeats)[:text_length]
return key[:text_length]
def _xor_encrypt_with_key(self, text, key):
"""XOR encrypt with a fixed key, returning hex."""
key_len = len(key)
return ''.join(
f"{ord(char) ^ ord(key[i % key_len]):02x}"
for i, char in enumerate(text)
)
def _xor_decrypt_with_key(self, hex_text, key):
"""XOR decrypt with a fixed 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 < 32 or xor_result > 126:
xor_result = xor_result % 95 + 32
result.append(chr(xor_result))
except ValueError:
result.append('?')
return ''.join(result)
except Exception:
return None
# ----------------------------------------------------------------------
# Public API
# ----------------------------------------------------------------------
def encrypt(self, plaintext, user_password):
"""
Encrypt plaintext with the given password.
Workflow:
1. Base64 encode the plaintext.
2. Apply letter substitution and case-flipping.
3. Reverse the string and append padding count.
4. XOR encrypt with dynamic key (long key).
5. XOR encrypt with derived final key (user password + short key).
Returns:
Encrypted ciphertext as a hex string.
"""
if not self.keys_loaded:
return "❌ Error: Keys not loaded"
# Step 1: Base64 encode and handle special chars
b64 = base64.b64encode(plaintext.encode('utf-8')).decode('utf-8')
equal_count = b64.count('=')
processed = b64
for old, new in self.special_encrypt.items():
processed = processed.replace(old, new)
processed = processed.rstrip('=')
# Step 2: Letter substitution + flip + reverse
sub = self._substitute_letters(processed, self.encrypt_map)
flipped = self._apply_flip(sub)
reversed_text = flipped[::-1]
# Step 3: Append padding count
equal_char = self.equal_mapping[str(equal_count)]
with_equal = f"{reversed_text}|{equal_char}"
# Step 4: Dynamic key (long key) encryption
key_length_str = str(len(with_equal))
key_length_encoded = self._encode_digit(key_length_str)
dynamic_key = self._get_dynamic_key(len(with_equal))
encrypted_by_dynamic = self._xor_encrypt_with_key(with_equal, dynamic_key)
# Step 5: Final encryption with derived key
combined = f"{encrypted_by_dynamic}|{key_length_encoded}"
final_encrypted = self._xor_encrypt_with_final_key(combined, user_password)
return final_encrypted
def decrypt(self, ciphertext, user_password):
"""
Decrypt ciphertext with the given password.
Returns:
The original plaintext, or an error message on failure.
"""
if not self.keys_loaded:
return "❌ Decryption failed"
try:
# Step 1: Decrypt with derived final key
combined = self._xor_decrypt_with_final_key(ciphertext, user_password)
if combined is None:
return "❌ Decryption failed"
# Step 2: Extract hex data and length indicator
if '|' in combined:
parts = combined.split('|')
if len(parts) >= 2:
hex_data = parts[0]
key_length_encoded = parts[1]
else:
hex_data = parts[0]
key_length_encoded = 'g'
else:
hex_data = combined
key_length_encoded = 'g'
# Step 3: Decode length and get dynamic key
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)
# Step 4: Decrypt with dynamic key
xor_decrypted = self._xor_decrypt_with_key(hex_data, dynamic_key)
if xor_decrypted is None:
return "❌ Decryption failed"
# Step 5: Extract main data and padding count
if '|' in xor_decrypted:
main_part, equal_char = xor_decrypted.split('|')
equal_count = int(self.equal_reverse.get(equal_char, '0'))
else:
main_part = xor_decrypted
equal_count = 0
# Step 6: Reverse, flip, substitute
reversed_text = main_part[::-1]
flipped = self._apply_flip(reversed_text)
sub = self._substitute_letters(flipped, self.decrypt_map)
# Step 7: Restore Base64 special chars and padding
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:
return "❌ Decryption failed"
# Step 8: Base64 decode
decoded = base64.b64decode(b64_with_equal.encode('utf-8')).decode('utf-8')
return decoded
except Exception:
return "❌ Decryption failed"
def print_keys(self):
"""Display information about the currently loaded keys."""
if not self.keys_loaded:
print("❌ Keys not loaded")
return
print("=" * 60)
print("Key Information")
print("=" * 60)
print(f"Key file: {self.key_file}")
print(f"Uppercase mapping: {self.upper_mapping}")
print(f"Lowercase mapping: {self.lower_mapping}")
print(f"Flip pattern: {self.flip_pattern}")
print(f"Long key length: {len(self.long_key)} bits")
print(f"Short key length: {len(self.short_key)} bits")
print("=" * 60)
# ----------------------------------------------------------------------
# CLI Entry Point
# ----------------------------------------------------------------------
def main():
"""Command-line interface for the encryption system."""
print("=" * 60)
print("Welcome to the Encryption System")
print("=" * 60)
crypto = None
key_password = None
# Try loading default key file
if os.path.exists("encryption.key"):
key_password = input("Enter password for default key file (encryption.key): ")
crypto = EncryptionSystem("encryption.key", key_password)
if not crypto.keys_loaded:
print("❌ Loading failed")
crypto = None
else:
print("\nDefault key file not found. Please generate one first.")
choice = input("Generate default key file? (y/n): ").strip().lower()
if choice == 'y':
crypto = EncryptionSystem()
result = crypto.generate_keys("encryption.key")
if result is None:
print("❌ Generation failed")
crypto = None
else:
print("⚠️ Use options 4, 5, or 6 to manage key files manually.")
# Main interaction loop
while True:
print("\nSelect an option:")
print("1. Encrypt with default key")
print("2. Decrypt with default key")
print("3. Generate new key (overwrite default)")
print("4. Encrypt with custom key file")
print("5. Decrypt with custom key file")
print("6. Generate key and save to current folder")
print("7. View current key info")
print("8. Exit")
choice = input("\nEnter choice (1-8): ").strip()
if choice == '1':
# Encrypt with default key
if crypto is None or not crypto.keys_loaded:
if os.path.exists("encryption.key"):
if key_password is None:
key_password = input("Enter default key file password: ")
crypto = EncryptionSystem("encryption.key", key_password)
if not crypto.keys_loaded:
print("❌ Loading failed")
continue
else:
print("❌ Key file not found")
continue
password = input("Enter encryption password: ")
text = input("Enter text to encrypt: ")
if text and password:
encrypted = crypto.encrypt(text, password)
print(f"\n✅ Encrypted result: {encrypted}")
elif choice == '2':
# Decrypt with default key
if crypto is None or not crypto.keys_loaded:
if os.path.exists("encryption.key"):
if key_password is None:
key_password = input("Enter default key file password: ")
crypto = EncryptionSystem("encryption.key", key_password)
if not crypto.keys_loaded:
print("❌ Loading failed")
continue
else:
print("❌ Key file not found")
continue
password = input("Enter encryption password: ")
text = input("Enter ciphertext to decrypt: ")
if text and password:
decrypted = crypto.decrypt(text, password)
print(f"\n✅ Decrypted result: {decrypted}")
elif choice == '3':
# Generate and overwrite default key
crypto = EncryptionSystem()
result = crypto.generate_keys("encryption.key")
if result is None:
print("❌ Generation failed")
else:
print("✅ Default key updated")
elif choice == '4':
# Encrypt with custom key file
key_file = input("Enter key file path: ")
if not os.path.exists(key_file):
print(f"❌ File not found: {key_file}")
continue
kp = input("Enter key file password: ")
crypto = EncryptionSystem(key_file, kp)
if not crypto.keys_loaded:
print("❌ Loading failed")
continue
password = input("Enter encryption password: ")
text = input("Enter text to encrypt: ")
if text and password:
encrypted = crypto.encrypt(text, password)
print(f"\n✅ Encrypted result: {encrypted}")
elif choice == '5':
# Decrypt with custom key file
key_file = input("Enter key file path: ")
if not os.path.exists(key_file):
print(f"❌ File not found: {key_file}")
continue
kp = input("Enter key file password: ")
crypto = EncryptionSystem(key_file, kp)
if not crypto.keys_loaded:
print("❌ Loading failed")
continue
password = input("Enter encryption password: ")
text = input("Enter ciphertext to decrypt: ")
if text and password:
decrypted = crypto.decrypt(text, password)
print(f"\n✅ Decrypted result: {decrypted}")
elif choice == '6':
# Generate new key with timestamp
timestamp = int(time.time())
filename = f"key_{timestamp}.key"
crypto = EncryptionSystem()
result = crypto.generate_keys(filename)
if result is None:
print("❌ Generation failed")
else:
print(f"✅ Key saved to: {filename}")
elif choice == '7':
# Show key info
if crypto is None or not crypto.keys_loaded:
if os.path.exists("encryption.key"):
if key_password is None:
key_password = input("Enter default key file password: ")
crypto = EncryptionSystem("encryption.key", key_password)
if not crypto.keys_loaded:
print("❌ Loading failed")
continue
else:
print("❌ Keys not loaded")
continue
crypto.print_keys()
elif choice == '8':
print("Goodbye!")
break
else:
print("❌ Invalid choice")
if __name__ == "__main__":
main()
View File
+603
View File
@@ -0,0 +1,603 @@
"""
ChaosCrypt test suite.
Covers round-trip integrity, binary safety, key management, the unified error
types, CLI behaviour, i18n, and bidirectional compatibility with the original
single-file implementation.
"""
import base64
import json
import os
import subprocess
import sys
import pytest
from chaoscrypt import (
DEFAULT_KEY_FILE,
ChaosCrypt,
ChaosCryptCore,
ChaosCryptError,
ChaosCrypt_ERR_KeyFileNotFound_E001,
ChaosCrypt_ERR_KeyFileExists_E005,
ChaosCrypt_ERR_KeyNotLoaded_E004,
ChaosCrypt_ERR_EmptyPassword_E006,
ChaosCrypt_ERR_EmptyPlaintext_E008,
ChaosCrypt_ERR_DecryptionFailed_E011,
)
from chaoscrypt.i18n import LANG_NAMES, t
KEY_PWD = "key-file-password"
USER_PWD = "user-encryption-password"
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
@pytest.fixture
def keyfile(tmp_path):
"""Create a key file and return ``(ChaosCrypt, path)``."""
path = str(tmp_path / "test.key")
cc = ChaosCrypt()
cc.create_key(KEY_PWD, path)
return cc, path
@pytest.fixture
def loaded(keyfile):
"""Return an instance with key material already loaded."""
_, path = keyfile
n = ChaosCrypt()
n.load(path, KEY_PWD)
return n
# ---------------------------------------------------------------------------
# Round-trip
# ---------------------------------------------------------------------------
class TestRoundTrip:
SAMPLES = [
"hello",
"hello 世界",
"emoji test 🎉",
"a",
"x" * 1000,
"Mixed mixed 123!@#$%^&*()_+-=[]{}|;':\",./<>?",
"line1\nline2\ttabbed",
" leading and trailing ",
]
@pytest.mark.parametrize("text", SAMPLES)
def test_text_roundtrip(self, loaded, text):
ct = loaded.encrypt(text, USER_PWD)
assert loaded.decrypt(ct, USER_PWD) == text
def test_ciphertext_is_hex(self, loaded):
ct = loaded.encrypt("data", USER_PWD)
int(ct, 16)
def test_empty_plaintext_rejected(self, loaded):
with pytest.raises(ChaosCryptError) as ei:
loaded.encrypt("", USER_PWD)
assert ei.value.code == "E008"
def test_empty_password_rejected(self, loaded):
with pytest.raises(ChaosCryptError) as ei:
loaded.encrypt("data", "")
assert ei.value.code == "E006"
def test_wrong_password_fails(self, loaded):
ct = loaded.encrypt("secret", USER_PWD)
with pytest.raises(ChaosCryptError) as ei:
loaded.decrypt(ct, "wrong-password")
assert ei.value.code == "E011"
def test_ciphertext_differs_per_password(self, loaded):
a = loaded.encrypt("same", "pwd-A")
b = loaded.encrypt("same", "pwd-B")
assert a != b
def test_non_hex_ciphertext_rejected(self, loaded):
with pytest.raises(ChaosCryptError) as ei:
loaded.decrypt("zzzz-not-hex", USER_PWD)
assert ei.value.code == "E010"
def test_odd_length_ciphertext_rejected(self, loaded):
with pytest.raises(ChaosCryptError) as ei:
loaded.decrypt("abc", USER_PWD)
assert ei.value.code == "E010"
def test_empty_ciphertext_rejected(self, loaded):
with pytest.raises(ChaosCryptError) as ei:
loaded.decrypt("", USER_PWD)
assert ei.value.code == "E009"
# ---------------------------------------------------------------------------
# Binary
# ---------------------------------------------------------------------------
class TestBinary:
@pytest.mark.parametrize("size", [1, 2, 255, 256, 4096, 100_000])
def test_binary_roundtrip(self, loaded, size):
raw = os.urandom(size)
ct = loaded.encrypt_bytes(raw, USER_PWD)
assert loaded.decrypt_bytes(ct, USER_PWD) == raw
def test_empty_binary_rejected(self, loaded):
with pytest.raises(ChaosCryptError):
loaded.encrypt_bytes(b"", USER_PWD)
def test_null_bytes_preserved(self, loaded):
raw = b"\x00\x01\x02\xff\xfe" * 100
ct = loaded.encrypt_bytes(raw, USER_PWD)
assert loaded.decrypt_bytes(ct, USER_PWD) == raw
# ---------------------------------------------------------------------------
# Key management
# ---------------------------------------------------------------------------
class TestKeyManagement:
def test_generate_and_load(self, tmp_path):
path = str(tmp_path / "k.key")
cc = ChaosCrypt()
assert cc.create_key(KEY_PWD, path) == path
assert os.path.exists(path)
n = ChaosCrypt()
n.load(path, KEY_PWD)
assert n.loaded
def test_keygen_refuses_overwrite(self, tmp_path):
path = str(tmp_path / "k.key")
ChaosCrypt().create_key(KEY_PWD, path)
with pytest.raises(ChaosCryptError) as ei:
ChaosCrypt().create_key(KEY_PWD, path)
assert ei.value.code == "E005"
def test_keygen_force_overwrite(self, tmp_path):
path = str(tmp_path / "k.key")
cc = ChaosCrypt()
cc.create_key(KEY_PWD, path)
first_upper = cc.core.upper_mapping
cc.create_key(KEY_PWD, path, overwrite=True)
assert cc.core.upper_mapping != first_upper
def test_load_missing_file(self):
with pytest.raises(ChaosCryptError) as ei:
ChaosCrypt().load("/definitely/not/here.key", KEY_PWD)
assert ei.value.code == "E001"
def test_load_wrong_key_password(self, keyfile):
_, path = keyfile
with pytest.raises(ChaosCryptError) as ei:
ChaosCrypt().load(path, "bad-password")
assert ei.value.code == "E003"
def test_load_corrupted_file(self, tmp_path):
path = tmp_path / "bad.key"
path.write_text("this is not a chaoscrypt key file!!!", encoding="utf-8")
with pytest.raises(ChaosCryptError) as ei:
ChaosCrypt().load(str(path), KEY_PWD)
assert ei.value.code == "E002"
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"
def test_encrypt_without_key_raises(self):
cc = ChaosCrypt()
with pytest.raises(ChaosCryptError) as ei:
cc.encrypt("data", USER_PWD)
assert ei.value.code == "E004"
def test_change_key_password(self, keyfile):
cc, path = keyfile
cc.change_key_password(KEY_PWD, "new-key-password", path)
ok = ChaosCrypt()
ok.load(path, "new-key-password")
assert ok.loaded
with pytest.raises(ChaosCryptError) as ei:
ChaosCrypt().load(path, KEY_PWD)
assert ei.value.code == "E003"
def test_change_password_preserves_data(self, keyfile):
cc, path = keyfile
ct = cc.encrypt("preserve me", USER_PWD)
cc.change_key_password(KEY_PWD, "brand-new-pwd", path)
n = ChaosCrypt()
n.load(path, "brand-new-pwd")
assert n.decrypt(ct, USER_PWD) == "preserve me"
def test_info_reports_key_sizes(self, loaded):
info = loaded.info()
assert info["long_key_length"] == 4096
assert info["short_key_length"] == 512
assert len(info["upper_mapping"]) == 26
assert len(info["flip_pattern"]) == 10
def test_export_and_import_key_text(self):
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"
n = ChaosCrypt()
n.load_from_text(text, KEY_PWD)
ct = n.encrypt("via text", USER_PWD)
assert cc.decrypt(ct, USER_PWD) == "via text"
def test_load_from_text_wrong_password(self):
cc = ChaosCrypt()
text = cc.export_key_text(KEY_PWD)
with pytest.raises(ChaosCryptError) as ei:
ChaosCrypt().load_from_text(text, "not-the-password")
assert ei.value.code == "E003"
# ---------------------------------------------------------------------------
# Key isolation
# ---------------------------------------------------------------------------
class TestKeyIsolation:
def test_two_keys_produce_different_ciphertext(self, tmp_path):
a = ChaosCrypt()
a.create_key(KEY_PWD, str(tmp_path / "a.key"))
b = ChaosCrypt()
b.create_key(KEY_PWD, str(tmp_path / "b.key"))
assert a.encrypt("same text", USER_PWD) != b.encrypt("same text", USER_PWD)
def test_cross_key_decryption_fails(self, tmp_path):
a = ChaosCrypt()
a.create_key(KEY_PWD, str(tmp_path / "a.key"))
b = ChaosCrypt()
b.create_key(KEY_PWD, str(tmp_path / "b.key"))
ct = a.encrypt("cross-key test", USER_PWD)
try:
got = b.decrypt(ct, USER_PWD)
except ChaosCryptError:
got = None
assert got != "cross-key test"
# ---------------------------------------------------------------------------
# File API
# ---------------------------------------------------------------------------
class TestFileAPI:
def test_encrypt_decrypt_file(self, loaded, tmp_path):
src = tmp_path / "data.bin"
payload = os.urandom(2048)
src.write_bytes(payload)
cc_file = str(tmp_path / "data.bin.cc")
out = loaded.encrypt_file(str(src), USER_PWD, cc_file)
assert os.path.exists(out)
dst = str(tmp_path / "restored.bin")
back = loaded.decrypt_file(cc_file, USER_PWD, dst)
assert open(back, "rb").read() == payload
def test_default_suffixes(self, loaded, tmp_path):
src = tmp_path / "note.txt"
src.write_text("hello file", encoding="utf-8")
out = loaded.encrypt_file(str(src), USER_PWD)
assert out.endswith(".cc")
back = loaded.decrypt_file(out, USER_PWD)
assert open(back, encoding="utf-8").read() == "hello file"
def test_missing_source_raises(self, loaded):
with pytest.raises(ChaosCryptError) as ei:
loaded.encrypt_file("/no/such/file.bin", USER_PWD)
assert ei.value.code == "E014"
# ---------------------------------------------------------------------------
# Unified error types
# ---------------------------------------------------------------------------
class TestErrorClass:
def test_message_format(self):
from chaoscrypt import ChaosCrypt_ERR_DecryptionFailed_E011
e = ChaosCrypt_ERR_DecryptionFailed_E011()
assert str(e).startswith("ChaosCrypt_ERR_")
assert str(e).endswith("_E011")
def test_code_and_detail_attributes(self):
e = ChaosCrypt_ERR_EmptyPlaintext_E008()
assert e.code == "E008"
assert e.detail == "EmptyPlaintext"
assert e.message == "ChaosCrypt_ERR_EmptyPlaintext_E008"
def test_all_errors_share_base(self):
from chaoscrypt import errors
for name in errors.__all__:
obj = getattr(errors, name)
if name == "ChaosCryptError":
continue
assert issubclass(obj, ChaosCryptError)
assert issubclass(obj, Exception)
def test_codes_are_unique(self):
from chaoscrypt import errors
codes = []
for name in errors.__all__:
obj = getattr(errors, name)
if name == "ChaosCryptError":
continue
codes.append(obj.CODE)
assert len(codes) == len(set(codes)), "duplicate error codes"
def test_custom_detail(self):
e = ChaosCrypt_ERR_KeyFileNotFound_E001(
detail="CustomDetail", code="E001"
)
assert e.detail == "CustomDetail"
assert e.code == "E001"
def test_catchable_as_generic_exception(self):
from chaoscrypt import ChaosCrypt_ERR_DecryptionFailed_E011
with pytest.raises(Exception):
raise ChaosCrypt_ERR_DecryptionFailed_E011()
# ---------------------------------------------------------------------------
# Algorithm compatibility
# ---------------------------------------------------------------------------
class TestLegacyCompatibility:
def test_format_matches_original_chain(self, loaded):
"""Reproduce the original decryption chain step by step."""
text = "compat check compatibility"
ct = loaded.encrypt(text, USER_PWD)
core = loaded.core
combined = core._xor_decrypt_with_final_key(ct, USER_PWD)
hex_data, key_len_enc = combined.split("|")
key_len = int(core._decode_digit(key_len_enc))
x = core._xor_decrypt_with_key(hex_data, core._get_dynamic_key(key_len))
main, eq_char = x.split("|")
eq_count = int(core.equal_reverse[eq_char])
sub = core._substitute_letters(
core._apply_flip(main[::-1]), core.decrypt_map
)
for o, n in core.special_decrypt.items():
sub = sub.replace(o, n)
assert base64.b64decode((sub + "=" * eq_count).encode()).decode() == text
def test_keyfile_readable_by_original_scheme(self, keyfile):
"""A newly generated key file must satisfy the original format."""
_, path = keyfile
core = ChaosCryptCore()
with open(path, "r") as f:
enc = f.read()
decrypted = core._xor_decrypt_data(enc, KEY_PWD)
assert decrypted is not None
data = core._deobfuscate_keys(decrypted)
assert set(data) >= {
"upper_mapping", "lower_mapping", "digit_mapping",
"equal_mapping", "flip_pattern", "long_key", "short_key",
}
assert len(data["long_key"]) == 4096
assert len(data["short_key"]) == 512
def test_reference_vector_stable(self):
"""Fixed key material must always produce the same ciphertext."""
core = ChaosCryptCore()
core.upper_mapping = "BCDEFGHIJKLMNOPQRSTUVWXYZA"
core.lower_mapping = "bcdefghijklmnopqrstuvwxyza"
core.digit_mapping = {
str(i): c for i, c in enumerate("ABCDEFGHIJ")
}
core.equal_mapping = {"0": "X", "1": "Y", "2": "Z", "3": "W"}
core.flip_pattern = [1, 0, 1, 0, 0, 1, 0, 0, 1, 0]
core.long_key = "0123456789abcdef" * 256
core.short_key = "fedcba9876543210" * 32
core.digit_reverse = {v: k for k, v in core.digit_mapping.items()}
core.equal_reverse = {v: k for k, v in core.equal_mapping.items()}
core._build_maps()
core.keys_loaded = True
plaintext = "reference vector"
ct1 = core.encrypt_text(plaintext, USER_PWD)
ct2 = core.encrypt_text(plaintext, USER_PWD)
assert ct1 == ct2
assert core.decrypt_text(ct1, USER_PWD) == plaintext
# ---------------------------------------------------------------------------
# i18n
# ---------------------------------------------------------------------------
class TestI18n:
def test_english_is_default(self):
import chaoscrypt.i18n as i18n
assert i18n.DEFAULT_LANG == "en"
def test_langs_available(self):
assert "en" in LANG_NAMES
assert "zh" in LANG_NAMES
def test_t_returns_both_languages(self):
en = t("app_title", "en")
zh = t("app_title", "zh")
assert en != zh
assert "ChaosCrypt" in en
def test_t_default_is_english(self):
assert t("app_title") == t("app_title", "en")
def test_t_fallback_for_unknown_key(self):
assert t("nonexistent_key_xyz", "en") == "nonexistent_key_xyz"
def test_missing_language_falls_back(self):
assert t("app_title", "fr") == t("app_title", "en")
def test_every_key_has_both_languages(self):
from chaoscrypt.i18n import TEXTS
for key, entry in TEXTS.items():
assert "en" in entry, f"{key} missing English"
assert "zh" in entry, f"{key} missing Chinese"
def test_tui_defaults_to_english(self):
from chaoscrypt.tui import TUI
tui = TUI()
assert tui.lang == "en"
assert tui._tr("menu_encrypt") == "Encrypt text"
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
class TestCLI:
@staticmethod
def _run(args, **kw):
return subprocess.run(
[sys.executable, "-m", "chaoscrypt"] + args,
capture_output=True, text=True, **kw,
)
def test_version(self):
r = self._run(["--version"])
assert r.returncode == 0
assert "2.1.6" in r.stdout
def test_help_mentions_scope(self):
r = self._run(["--help"])
assert r.returncode == 0
assert "unaudited" in r.stdout.lower()
def test_keygen_and_encrypt_decrypt(self, tmp_path):
kf = str(tmp_path / "cli.key")
r = self._run(["keygen", "-k", kf, "-P", KEY_PWD])
assert r.returncode == 0, r.stderr
assert os.path.exists(kf)
r = self._run(["encrypt", "cli round trip", "-p", USER_PWD,
"-k", kf, "-P", KEY_PWD])
assert r.returncode == 0, r.stderr
ct = r.stdout.strip()
r = self._run(["decrypt", ct, "-p", USER_PWD, "-k", kf, "-P", KEY_PWD])
assert r.returncode == 0, r.stderr
assert r.stdout.strip() == "cli round trip"
def test_json_output(self, tmp_path):
kf = str(tmp_path / "j.key")
self._run(["keygen", "-k", kf, "-P", KEY_PWD])
r = self._run(["--json", "encrypt", "json test", "-p", USER_PWD,
"-k", kf, "-P", KEY_PWD])
payload = json.loads(r.stdout)
assert payload["ok"] is True
assert payload["mode"] == "encrypt"
assert payload["ciphertext"]
def test_info_json_redacts_maps(self, tmp_path):
kf = str(tmp_path / "i.key")
self._run(["keygen", "-k", kf, "-P", KEY_PWD])
r = self._run(["--json", "info", "-k", kf, "-P", KEY_PWD])
payload = json.loads(r.stdout)
assert payload["long_key_length"] == 4096
assert "hidden" in payload["upper_mapping"]
def test_error_exit_code(self, tmp_path):
r = self._run(["decrypt", "zzzz", "-p", USER_PWD,
"-k", str(tmp_path / "nope.key"), "-P", KEY_PWD])
assert r.returncode == 1
assert "ChaosCrypt_ERR_" in r.stderr
def test_password_from_env(self, tmp_path):
kf = str(tmp_path / "env.key")
env = dict(os.environ, CC_KP=KEY_PWD, CC_UP=USER_PWD)
r = self._run(["keygen", "-k", kf, "--key-pwd-env", "CC_KP"], env=env)
assert r.returncode == 0, r.stderr
r = self._run(["encrypt", "env test", "--pwd-env", "CC_UP",
"-k", kf, "-P", KEY_PWD], env=env)
assert r.returncode == 0, r.stderr
def test_password_from_file(self, tmp_path):
kf = str(tmp_path / "f.key")
pwd_file = tmp_path / ".pwd"
pwd_file.write_text(KEY_PWD + "\n", encoding="utf-8")
r = self._run(["keygen", "-k", kf, "--key-pwd-file", str(pwd_file)])
assert r.returncode == 0, r.stderr
def test_file_encrypt_decrypt(self, tmp_path):
kf = str(tmp_path / "f.key")
src = tmp_path / "in.txt"
src.write_text("file cli test", encoding="utf-8")
self._run(["keygen", "-k", kf, "-P", KEY_PWD])
r = self._run(["file", "encrypt", str(src), "-p", USER_PWD,
"-k", kf, "-P", KEY_PWD])
assert r.returncode == 0, r.stderr
cc_file = str(src) + ".cc"
assert os.path.exists(cc_file)
dst = str(tmp_path / "out.txt")
r = self._run(["file", "decrypt", cc_file, "-o", dst, "-p", USER_PWD,
"-k", kf, "-P", KEY_PWD])
assert r.returncode == 0, r.stderr
assert open(dst, encoding="utf-8").read() == "file cli test"
def test_chpwd(self, tmp_path):
kf = str(tmp_path / "c.key")
self._run(["keygen", "-k", kf, "-P", KEY_PWD])
r = self._run(["chpwd", "-k", kf, "-P", KEY_PWD,
"--new-pwd", "brand-new"])
assert r.returncode == 0, r.stderr
r = self._run(["info", "-k", kf, "-P", "brand-new"])
assert r.returncode == 0, r.stderr
# ---------------------------------------------------------------------------
# Core used directly
# ---------------------------------------------------------------------------
class TestCoreDirect:
def test_core_generate_and_use(self):
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)
c2 = ChaosCryptCore()
c2.load_keys_from_text(text, KEY_PWD)
assert c2.decrypt_text(ct, USER_PWD) == "core direct"
def test_key_material_sizes(self):
c = ChaosCryptCore()
c.generate_keymaterial()
assert len(c.upper_mapping) == 26
assert len(c.lower_mapping) == 26
assert len(c.digit_mapping) == 10
assert len(c.equal_mapping) == 4
assert len(c.flip_pattern) == 10
assert len(c.long_key) == 4096
assert len(c.short_key) == 512
def test_mappings_are_bijections(self):
c = ChaosCryptCore()
c.generate_keymaterial()
assert sorted(c.upper_mapping) == sorted("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
assert sorted(c.lower_mapping) == sorted("abcdefghijklmnopqrstuvwxyz")
assert len(set(c.digit_mapping.values())) == 10
assert len(set(c.equal_mapping.values())) == 4
def test_key_material_is_random_between_instances(self):
a = ChaosCryptCore()
a.generate_keymaterial()
b = ChaosCryptCore()
b.generate_keymaterial()
assert a.long_key != b.long_key
assert a.short_key != b.short_key
assert a.upper_mapping != b.upper_mapping
+84
View File
@@ -0,0 +1,84 @@
"""
Bidirectional interoperability tests against the original implementation.
These tests load ``chaoscrypt/legacy/chaoscrypt_legacy.py`` and prove that:
* ciphertext produced by the original script decrypts with the packaged
library, and
* ciphertext produced by the packaged library decrypts with the original
script.
They are the regression guard for the promise that the algorithm itself was
ported without any behavioural change.
"""
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
+139
View File
@@ -0,0 +1,139 @@
"""
Interactive TUI tests.
A key sequence is piped into the UI and the rendered output is inspected.
Outside a TTY the UI falls back from ``getpass`` to ``input``, which is what
makes it scriptable.
"""
import os
import re
import subprocess
import sys
import pytest
KEY_PWD = "tui-key-password"
USER_PWD = "tui-user-password"
def _run_tui(seq: str, cwd: str, timeout: int = 90):
env = dict(os.environ, PYTHONIOENCODING="utf-8", NO_COLOR="1")
return subprocess.run(
[sys.executable, "-m", "chaoscrypt"],
input=seq, capture_output=True, text=True,
encoding="utf-8", env=env, cwd=cwd, timeout=timeout,
)
@pytest.fixture
def tui_dir(tmp_path):
"""Create a TUI key file in an isolated directory."""
seq = f"5\nt.key\n{KEY_PWD}\n{KEY_PWD}\n\nq\n"
r = _run_tui(seq, str(tmp_path))
assert (tmp_path / "t.key").exists(), r.stdout
return str(tmp_path)
class TestTUI:
def test_launches_in_english_by_default(self, tmp_path):
r = _run_tui("q\n", str(tmp_path))
assert r.returncode == 0
assert "ChaosCrypt" in r.stdout
assert "Select an action" in r.stdout
assert "Encrypt text" in r.stdout
def test_shows_scope_notice(self, tmp_path):
r = _run_tui("q\n", str(tmp_path))
assert "unaudited" in r.stdout
assert "not for production" in r.stdout.lower()
def test_keygen_creates_file(self, tmp_path):
r = _run_tui(f"5\nmy.key\n{KEY_PWD}\n{KEY_PWD}\n\nq\n", str(tmp_path))
assert (tmp_path / "my.key").exists(), r.stdout
assert "Key file written to" in r.stdout
def test_keygen_password_mismatch(self, tmp_path):
r = _run_tui("5\nm.key\npwd-one\npwd-two\n\nq\n", str(tmp_path))
assert "E007" in r.stdout
assert not (tmp_path / "m.key").exists()
def test_encrypt_then_decrypt_in_new_session(self, tmp_path):
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)
assert m, r1.stdout
ct = m.group(1).strip()
seq2 = f"6\nt.key\n{KEY_PWD}\n\n2\n{ct}\n{USER_PWD}\n\nq\n"
r2 = _run_tui(seq2, str(tmp_path))
assert "secret payload" in r2.stdout, r2.stdout
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
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"
r = _run_tui(seq, tui_dir)
assert "ChaosCrypt_ERR_" in r.stdout
def test_wrong_key_password_shows_e003(self, tui_dir):
r = _run_tui("6\nt.key\nWRONG-KEY-PWD\n\nq\n", tui_dir)
assert "_E003" in r.stdout
def test_language_switch_to_chinese(self, tmp_path):
r = _run_tui("9\n2\n\nq\n", str(tmp_path))
assert "混沌混淆加密" in r.stdout
assert "请选择操作" in r.stdout
def test_language_switch_back_to_english(self, tmp_path):
r = _run_tui("9\n2\n\n9\n1\n\nq\n", str(tmp_path))
assert "Select an action" in r.stdout
def test_chinese_mode_encrypt_works(self, tui_dir):
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
def test_about_page_has_design_notes(self, tmp_path):
r = _run_tui("a\n\nq\n", str(tmp_path))
assert "10^5621" in r.stdout
assert "MIT" in r.stdout
assert "Shor" in r.stdout
def test_key_info_shows_sizes(self, tui_dir):
r = _run_tui(f"6\nt.key\n{KEY_PWD}\n\n7\n\nq\n", tui_dir)
assert "4096" in r.stdout
assert "512" in r.stdout
def test_invalid_option_reprompts(self, tmp_path):
r = _run_tui("zzz\n\nq\n", str(tmp_path))
assert "Unrecognised option" in r.stdout
def test_change_key_password_in_session(self, tui_dir):
seq = f"8\nt.key\n{KEY_PWD}\nnewkeypass\nnewkeypass\n\nq\n"
r = _run_tui(seq, tui_dir)
assert "updated" in r.stdout
r2 = _run_tui("6\nt.key\nnewkeypass\n\nq\n", tui_dir)
assert "Key file loaded" in r2.stdout
def test_file_encrypt_decrypt_via_tui(self, tui_dir):
src = os.path.join(tui_dir, "payload.txt")
with open(src, "w", encoding="utf-8") as f:
f.write("TUI file payload")
seq = (f"6\nt.key\n{KEY_PWD}\n\n"
f"3\n{src}\n{src}.cc\n{USER_PWD}\n\nq\n")
r = _run_tui(seq, tui_dir)
assert os.path.exists(src + ".cc"), r.stdout
seq2 = (f"6\nt.key\n{KEY_PWD}\n\n"
f"4\n{src}.cc\n{src}.out\n{USER_PWD}\n\nq\n")
r2 = _run_tui(seq2, tui_dir)
assert os.path.exists(src + ".out"), r2.stdout
assert open(src + ".out", encoding="utf-8").read() == "TUI file payload"
+473
View File
@@ -0,0 +1,473 @@
"""
ChaosCrypt interactive terminal UI.
A dependency-free menu-driven interface, intended for people who would
rather not memorise command line flags. English is the default language;
the menu can switch to Chinese at runtime.
Running ``chaoscrypt`` with no arguments launches this UI. The module is
imported lazily so that library users never pay for it.
"""
from __future__ import annotations
import os
import sys
from typing import Optional
from . import DEFAULT_KEY_FILE, __version__, ChaosCrypt
from .errors import ChaosCryptError
from .i18n import DEFAULT_LANG, LANG_NAMES, t
__all__ = ["run_tui", "TUI"]
WIDTH = 66
# ANSI styling; degrades to plain text when the terminal cannot handle it.
_C = {
"reset": "\033[0m",
"bold": "\033[1m",
"dim": "\033[2m",
"cyan": "\033[36m",
"green": "\033[32m",
"yellow": "\033[33m",
"red": "\033[31m",
"magenta": "\033[35m",
}
def _supports_color() -> bool:
"""Whether the attached stdout can render ANSI colour."""
if os.environ.get("NO_COLOR"):
return False
if not sys.stdout.isatty():
return False
if os.name == "nt":
try:
import ctypes
kernel32 = ctypes.windll.kernel32
kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)
return True
except Exception:
return False
return True
_COLOR = _supports_color()
def c(text: str, *styles: str) -> str:
"""Wrap ``text`` in ANSI styles, or return it unchanged."""
if not _COLOR or not styles:
return text
return "".join(_C.get(s, "") for s in styles) + text + _C["reset"]
# ---------------------------------------------------------------------------
# Input helpers
# ---------------------------------------------------------------------------
class _Abort(Exception):
"""Raised when the user asks to return to the main menu."""
def _ask(prompt: str, default: Optional[str] = None) -> str:
suffix = f" [{default}]" if default else ""
try:
val = input(f"{c('>', 'cyan')} {prompt}{suffix}: ").strip()
except (EOFError, KeyboardInterrupt):
print()
raise _Abort()
if not val and default is not None:
return default
return val
def _ask_secret(prompt: str) -> str:
"""Read a password without echoing it when possible.
Interactive terminals use ``getpass`` so the input is not shown. Piped or
redirected input cannot use ``getpass``, so it falls back to ``input``,
which keeps the UI scriptable.
"""
label = f"{c('>', 'cyan')} {prompt}: "
if sys.stdin is not None and sys.stdin.isatty():
try:
import getpass
return getpass.getpass(label)
except (EOFError, KeyboardInterrupt):
print()
raise _Abort()
except Exception:
pass # Fall through to the non-echoing fallback below.
try:
return input(label).strip()
except (EOFError, KeyboardInterrupt):
print()
raise _Abort()
def _ask_yes_no(prompt: str, lang: str) -> bool:
try:
val = input(f"{c('>', 'cyan')} {prompt} [y/n]: ").strip().lower()
except (EOFError, KeyboardInterrupt):
print()
raise _Abort()
return val in ("y", "yes")
def _pause(lang: str) -> None:
try:
input(c(f" {t('press_enter', lang)}", "dim"))
except (EOFError, KeyboardInterrupt):
print()
def _rule() -> str:
return "-" * WIDTH
# ---------------------------------------------------------------------------
# TUI
# ---------------------------------------------------------------------------
class TUI:
"""Menu-driven bilingual interface over :class:`~chaoscrypt.ChaosCrypt`."""
def __init__(self, lang: str = DEFAULT_LANG,
key_file: str = DEFAULT_KEY_FILE) -> None:
self.lang = lang if lang in LANG_NAMES else DEFAULT_LANG
self.key_file = key_file
self.cc = ChaosCrypt()
self.key_password: Optional[str] = None
# ------------------------------------------------------------------ view
def _tr(self, key: str) -> str:
return t(key, self.lang)
def banner(self) -> None:
print()
print(c("+" + "=" * (WIDTH - 2) + "+", "magenta"))
title = f" {self._tr('app_title')} v{__version__}"
print(c("|", "magenta")
+ c(title.ljust(WIDTH - 2), "bold", "cyan")
+ c("|", "magenta"))
print(c("+" + "=" * (WIDTH - 2) + "+", "magenta"))
for line in self._tr("warn_banner").split("\n"):
print(c(line, "yellow"))
shown = self.cc.key_file or self.key_file or DEFAULT_KEY_FILE
state = (
c("[*] " + self._tr("key_loaded"), "green")
if self.cc.loaded
else c("[ ] " + self._tr("no_key_loaded"), "red")
)
print(f"\n{state} {c(shown, 'dim')}")
def _print_error(self, exc: Exception) -> None:
"""Render a unified error, with a hint where one applies."""
print()
print(c("+" + "-" * (WIDTH - 2) + "+", "red"))
print(c("| ", "red")
+ c(f"{self._tr('err_prefix')}: {exc}", "red", "bold"))
print(c("+" + "-" * (WIDTH - 2) + "+", "red"))
msg = str(exc)
if "_E011" in msg or "_E003" in msg:
print(c(" " + self._tr("err_hint_password"), "dim"))
elif "_E004" in msg or "_E001" in msg:
print(c(" " + self._tr("err_hint_key_required"), "dim"))
# ------------------------------------------------------------------ menu
def menu(self) -> str:
items = [
("1", "menu_encrypt"),
("2", "menu_decrypt"),
("3", "menu_encrypt_file"),
("4", "menu_decrypt_file"),
("5", "menu_keygen"),
("6", "menu_loadkey"),
("7", "menu_keyinfo"),
("8", "menu_chpwd"),
("9", "menu_lang"),
("a", "menu_about"),
("q", "menu_quit"),
]
print()
print(c(_rule(), "dim"))
print(c(" " + self._tr("menu_choose"), "bold"))
print(c(_rule(), "dim"))
for key, label in items:
print(f" {c('[' + key + ']', 'cyan')} {self._tr(label)}")
print(c(_rule(), "dim"))
return _ask(self._tr("menu_prompt")).lower()
# ------------------------------------------------------------ key state
def _ensure_key(self) -> bool:
"""Make sure a key is loaded, offering to create one if none exists.
Searches the instance's loaded key, then the remembered file, then
the default name.
"""
if self.cc.loaded:
return True
path = (
self.cc.key_file
or self.key_file
or DEFAULT_KEY_FILE
)
self.key_file = path
if not os.path.exists(path):
if _ask_yes_no(self._tr("prompt_create_if_missing"), self.lang):
return self.action_keygen()
return False
try:
pwd = self.key_password or _ask_secret(self._tr("prompt_key_password"))
self.cc.load(path, pwd)
self.key_password = pwd
print(c(f"{self._tr('key_loaded')}: {path}", "green"))
return True
except ChaosCryptError as exc:
self._print_error(exc)
return False
# ---------------------------------------------------------------- actions
def action_encrypt(self) -> None:
if not self._ensure_key():
return
text = _ask(self._tr("prompt_plaintext"))
if not text:
print(c(" " + self._tr("cancelled"), "dim"))
return
pwd = _ask_secret(self._tr("prompt_user_password"))
try:
ct = self.cc.encrypt(text, pwd)
print()
print(c(f"{self._tr('result_ciphertext')}:", "green", "bold"))
print(c(ct, "cyan"))
except ChaosCryptError as exc:
self._print_error(exc)
def action_decrypt(self) -> None:
if not self._ensure_key():
return
text = _ask(self._tr("prompt_ciphertext"))
if not text:
print(c(" " + self._tr("cancelled"), "dim"))
return
pwd = _ask_secret(self._tr("prompt_user_password"))
try:
pt = self.cc.decrypt(text, pwd)
print()
print(c(f"{self._tr('result_plaintext')}:", "green", "bold"))
print(c(pt, "cyan"))
except ChaosCryptError as exc:
self._print_error(exc)
def action_encrypt_file(self) -> None:
if not self._ensure_key():
return
src = _ask(self._tr("prompt_src_file"))
if not src or not os.path.exists(src):
print(c(f" {self._tr('failed')}: {src}", "red"))
return
dst = _ask(self._tr("prompt_dst_file")) or None
pwd = _ask_secret(self._tr("prompt_user_password"))
try:
out = self.cc.encrypt_file(src, pwd, dst)
print(c(f"{self._tr('file_written')}: {out}", "green"))
except ChaosCryptError as exc:
self._print_error(exc)
def action_decrypt_file(self) -> None:
if not self._ensure_key():
return
src = _ask(self._tr("prompt_src_file"))
if not src or not os.path.exists(src):
print(c(f" {self._tr('failed')}: {src}", "red"))
return
dst = _ask(self._tr("prompt_dst_file")) or None
pwd = _ask_secret(self._tr("prompt_user_password"))
try:
out = self.cc.decrypt_file(src, pwd, dst)
print(c(f"{self._tr('file_written')}: {out}", "green"))
except ChaosCryptError as exc:
self._print_error(exc)
def action_keygen(self) -> bool:
default = self.cc.key_file or self.key_file or DEFAULT_KEY_FILE
path = _ask(self._tr("prompt_key_file"), default)
overwrite = False
if os.path.exists(path):
if not _ask_yes_no(self._tr("prompt_overwrite"), self.lang):
print(c(" " + self._tr("cancelled"), "dim"))
return False
overwrite = True
pwd = _ask_secret(self._tr("prompt_key_password_new"))
if not pwd:
print(c(" " + self._tr("failed"), "red"))
return False
confirm = _ask_secret(self._tr("prompt_key_password_confirm"))
if pwd != confirm:
print(c(" ChaosCrypt_ERR_PasswordMismatch_E007", "red"))
return False
try:
out = self.cc.create_key(pwd, path, overwrite=overwrite)
self.key_file = out
self.key_password = pwd
print(c(f"{self._tr('key_saved')}: {out}", "green"))
return True
except ChaosCryptError as exc:
self._print_error(exc)
return False
def action_loadkey(self) -> None:
default = self.cc.key_file or self.key_file or DEFAULT_KEY_FILE
path = _ask(self._tr("prompt_key_file"), default)
pwd = _ask_secret(self._tr("prompt_key_password"))
try:
self.cc.load(path, pwd)
self.key_file = path
self.key_password = pwd
print(c(f"{self._tr('key_loaded')}: {path}", "green"))
except ChaosCryptError as exc:
self._print_error(exc)
def action_keyinfo(self) -> None:
if not self._ensure_key():
return
try:
info = self.cc.info()
except ChaosCryptError as exc:
self._print_error(exc)
return
rows = [
("info_key_file", info["key_file"]),
("info_version", info["version"]),
("info_upper", info["upper_mapping"]),
("info_lower", info["lower_mapping"]),
("info_digit", "".join(info["digit_mapping"].values())),
("info_equal", "".join(info["equal_mapping"].values())),
("info_flip", info["flip_pattern"]),
("info_long_key",
f"{info['long_key_length']} {self._tr('characters')}"),
("info_short_key",
f"{info['short_key_length']} {self._tr('characters')}"),
("info_loaded", self._tr("yes")),
]
print()
print(c(_rule(), "dim"))
for key, val in rows:
print(f" {c(self._tr(key), 'bold'):<38} {val}")
print(c(_rule(), "dim"))
def action_chpwd(self) -> None:
default = self.cc.key_file or self.key_file or DEFAULT_KEY_FILE
path = _ask(self._tr("prompt_key_file"), default)
if not os.path.exists(path):
print(c(" ChaosCrypt_ERR_KeyFileNotFound_E001", "red"))
return
old = _ask_secret(self._tr("prompt_key_password_old"))
new = _ask_secret(self._tr("prompt_key_password_new"))
confirm = _ask_secret(self._tr("prompt_key_password_confirm"))
if new != confirm:
print(c(" ChaosCrypt_ERR_PasswordMismatch_E007", "red"))
return
try:
out = self.cc.change_key_password(old, new, path)
self.key_password = new
print(c(f"{self._tr('key_password_changed')}: {out}", "green"))
except ChaosCryptError as exc:
self._print_error(exc)
def action_lang(self) -> None:
codes = list(LANG_NAMES.keys())
print()
for i, (code, name) in enumerate(LANG_NAMES.items(), 1):
mark = "*" if code == self.lang else " "
print(f" {c('[' + str(i) + ']', 'cyan')} {mark} {name} ({code})")
default_index = str(codes.index(self.lang) + 1) if self.lang in codes else "1"
choice = _ask("Language", default_index)
try:
idx = int(choice) - 1
if 0 <= idx < len(codes):
self.lang = codes[idx]
except ValueError:
if choice in codes:
self.lang = choice
print(c(f" -> {LANG_NAMES[self.lang]}", "green"))
def action_about(self) -> None:
print()
print(c(self._tr("about_body"), "cyan"))
# ------------------------------------------------------------- main loop
def run(self) -> int:
while True:
self.banner()
try:
choice = self.menu()
except _Abort:
print()
print(c(self._tr("bye"), "green"))
return 0
try:
if choice == "1":
self.action_encrypt()
elif choice == "2":
self.action_decrypt()
elif choice == "3":
self.action_encrypt_file()
elif choice == "4":
self.action_decrypt_file()
elif choice == "5":
self.action_keygen()
elif choice == "6":
self.action_loadkey()
elif choice == "7":
self.action_keyinfo()
elif choice == "8":
self.action_chpwd()
elif choice == "9":
self.action_lang()
elif choice in ("a", "about"):
self.action_about()
elif choice in ("q", "quit", "exit"):
print()
print(c(self._tr("bye"), "green"))
return 0
else:
print(c(" " + self._tr("menu_invalid"), "yellow"))
continue
except _Abort:
print(c(" " + self._tr("cancelled"), "dim"))
continue
except KeyboardInterrupt:
print()
print(c(self._tr("bye"), "green"))
return 0
_pause(self.lang)
def run_tui(lang: str = DEFAULT_LANG,
key_file: str = DEFAULT_KEY_FILE) -> int:
"""Launch the interactive UI and return the process exit code."""
try:
return TUI(lang=lang, key_file=key_file).run()
except KeyboardInterrupt:
print()
return 0
if __name__ == "__main__": # pragma: no cover
sys.exit(run_tui())