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

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

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

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

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

119 lines
3.9 KiB
Python

"""
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()