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:
@@ -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)
|
||||
Reference in New Issue
Block a user