The global output flags were only registered on the top-level parser, so `chaoscrypt info -k my.key -P keypwd --json` failed with "unrecognized arguments: --json". That is the form most people type first, since the flag reads naturally at the end of a command. Both flags are now also registered on every subcommand. They write to separate destinations (json_local / quiet_local) because argparse would otherwise let an unset subcommand flag overwrite an explicitly set global one; the two are merged in main(). Three regression tests cover the flag in both positions plus the bare ciphertext output when neither flag is given.
638 lines
23 KiB
Python
638 lines
23 KiB
Python
"""
|
|
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_json_flag_accepted_before_and_after_subcommand(self, tmp_path):
|
|
"""--json must work in either position, not only before the subcommand."""
|
|
kf = str(tmp_path / "pos.key")
|
|
self._run(["keygen", "-k", kf, "-P", KEY_PWD])
|
|
|
|
for args in (
|
|
["--json", "info", "-k", kf, "-P", KEY_PWD],
|
|
["info", "-k", kf, "-P", KEY_PWD, "--json"],
|
|
):
|
|
r = self._run(args)
|
|
assert r.returncode == 0, r.stderr
|
|
assert json.loads(r.stdout)["ok"] is True, args
|
|
|
|
def test_quiet_flag_accepted_before_and_after_subcommand(self, tmp_path):
|
|
kf = str(tmp_path / "q.key")
|
|
self._run(["keygen", "-k", kf, "-P", KEY_PWD])
|
|
|
|
for args in (
|
|
["--quiet", "encrypt", "x", "-p", USER_PWD, "-k", kf, "-P", KEY_PWD],
|
|
["encrypt", "x", "-p", USER_PWD, "-k", kf, "-P", KEY_PWD, "--quiet"],
|
|
):
|
|
r = self._run(args)
|
|
assert r.returncode == 0, r.stderr
|
|
assert r.stdout.strip() == "", args
|
|
|
|
def test_plain_output_is_bare_ciphertext(self, tmp_path):
|
|
"""Without --json the ciphertext goes to stdout on its own."""
|
|
kf = str(tmp_path / "p.key")
|
|
self._run(["keygen", "-k", kf, "-P", KEY_PWD])
|
|
r = self._run(["encrypt", "x", "-p", USER_PWD, "-k", kf, "-P", KEY_PWD])
|
|
out = r.stdout.strip()
|
|
assert out and "ciphertext" not in out
|
|
int(out, 16)
|
|
|
|
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
|