kransx 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
kransx-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 KRANSX
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
kransx-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,160 @@
1
+ Metadata-Version: 2.4
2
+ Name: kransx
3
+ Version: 0.1.0
4
+ Summary: KRANSX authenticated encryption-envelope reference implementation
5
+ Author: KRANSX contributors
6
+ License-Expression: MIT
7
+ Keywords: aead,compression,encryption,zstandard
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Topic :: Security :: Cryptography
11
+ Classifier: Topic :: System :: Archiving :: Compression
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Programming Language :: Python :: 3.14
18
+ Classifier: Operating System :: OS Independent
19
+ Classifier: Typing :: Typed
20
+ Requires-Python: >=3.10
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Requires-Dist: cryptography>=42
24
+ Requires-Dist: zstandard>=0.22
25
+ Provides-Extra: dev
26
+ Requires-Dist: mypy>=1.10; extra == "dev"
27
+ Requires-Dist: pre-commit>=4; extra == "dev"
28
+ Requires-Dist: pytest>=7; extra == "dev"
29
+ Requires-Dist: ruff>=0.4; extra == "dev"
30
+ Dynamic: license-file
31
+
32
+ # KRANSX
33
+
34
+ [![CI](https://github.com/HEKPYTO/KRANSX/actions/workflows/ci.yml/badge.svg)](https://github.com/HEKPYTO/KRANSX/actions)
35
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org)
36
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
37
+
38
+ Authenticated encryption with adaptive compression for Python.
39
+
40
+ KRANSX seals arbitrary bytes into a compact, authenticated envelope. It applies Zstandard compression only when it reduces size, otherwise stores the payload as-is, and protects both with AES-256-GCM-SIV. The result is a single self-contained binary with 29 bytes of overhead.
41
+
42
+ ## Features
43
+
44
+ - Adaptive compression — Zstandard when beneficial, raw otherwise
45
+ - Authenticated encryption — AES-256-GCM-SIV (nonce-misuse resistant)
46
+ - Small fixed overhead — 29 bytes (`suite` + `nonce` + `tag`)
47
+ - Simple API — `seal` / `open_data`, fully typed
48
+ - Dictionary support — optional Zstandard dictionaries for structured data
49
+ - CLI — `keygen`, `seal`, `open`, `train`
50
+ - No background services or async dependencies
51
+
52
+ ## Installation
53
+
54
+ ```bash
55
+ pip install kransx
56
+ ```
57
+
58
+ For development:
59
+
60
+ ```bash
61
+ uv sync --locked --extra dev
62
+ ```
63
+
64
+ Requires Python 3.10+, `cryptography >= 42`, `zstandard >= 0.22`.
65
+
66
+ ## Usage
67
+
68
+ ### Python API
69
+
70
+ ```python
71
+ import secrets
72
+ from kransx import open_data, seal
73
+
74
+ key = secrets.token_bytes(32) # 32 uniformly random bytes
75
+ aad = b"record-42" # associated data, authenticated but not encrypted
76
+
77
+ sealed = seal(b"hello world", key, aad=aad)
78
+ assert open_data(sealed, key, aad=aad) == b"hello world"
79
+ ```
80
+
81
+ Authentication failures raise `cryptography.exceptions.InvalidTag` (wrong key, AAD, dictionary, or modified bytes). Structural errors raise `ValueError`.
82
+
83
+ With a shared dictionary (non-secret, improves compression on similar payloads):
84
+
85
+ ```python
86
+ from kransx import train_dict
87
+
88
+ dictionary = train_dict([b'{"user":1,"action":"login"}'] * 300)
89
+ sealed = seal(b'{"user":1,"action":"login"}', key, dict_obj=dictionary)
90
+ assert open_data(sealed, key, dict_obj=dictionary) == b'{"user":1,"action":"login"}'
91
+ ```
92
+
93
+ API reference:
94
+
95
+ ```python
96
+ seal(data: bytes, key: bytes, *, dict_obj=None, aad=b"", compress=True, level=3) -> bytes
97
+ open_data(blob: bytes, key: bytes, *, dict_obj=None, aad=b"", max_output_size=64*1024*1024) -> bytes
98
+ train_dict(samples: Iterable[bytes], dict_size=16384) -> ZstdCompressionDict
99
+ save_dict(dictionary, path) / load_dict(path)
100
+ ```
101
+
102
+ `compress=True` retains the Zstandard frame only when strictly smaller than the input. `max_output_size` limits the decompressed output size.
103
+
104
+ ### CLI
105
+
106
+ ```bash
107
+ kransx keygen key.bin
108
+ kransx seal plain.bin sealed.bin --key-file key.bin --aad 7265636f72642d3432
109
+ kransx open sealed.bin restored.bin --key-file key.bin --aad 7265636f72642d3432
110
+
111
+ kransx train 'samples/*.json' --output model.dict
112
+ kransx seal plain.bin out.bin --key-file key.bin --dict model.dict
113
+ kransx open out.bin restored.bin --key-file key.bin --dict model.dict --max-output-size 1048576
114
+ ```
115
+
116
+ - `--aad` accepts hex-encoded bytes
117
+ - `--max-output-size` caps plaintext size on open
118
+ - Output files are created exclusively and never overwritten
119
+
120
+ ## Design
121
+
122
+ Envelope layout: `suite (1) | nonce (12) | ciphertext | tag (16)`
123
+
124
+ | Suite | Payload | Authenticated associated data |
125
+ |-------|---------|-------------------------------|
126
+ | `0x21` | Zstandard frame | `suite` + dictionary binding + `aad` |
127
+ | `0x22` | raw bytes | `suite` + `aad` |
128
+
129
+ - The dictionary binding is `SHA-256` over the dictionary bytes (or a constant for no dictionary), ensuring a mismatched dictionary fails authentication before decompression.
130
+ - Keys are 32 random bytes expanded via HKDF-SHA256 to the AEAD key. A fresh 12-byte nonce is generated per seal.
131
+ - Opening validates the envelope before decryption: size and suite checks, then AEAD authentication, then — for compressed payloads — single-frame Zstandard validation and bounded decompression.
132
+
133
+ ## Security considerations
134
+
135
+ This library implements the envelope only. Key generation, distribution, storage, rotation, and encrypted-input size bounding are the caller's responsibility.
136
+
137
+ - **Keys** must be 32 uniformly random bytes. Passwords are not valid keys.
138
+ - **Nonces** are generated with `os.urandom(12)` per seal. AES-GCM-SIV is nonce-misuse resistant, but reuse should still be avoided.
139
+ - **Compression oracles** — the sealed size reveals whether compression was used. Do not compress data that mixes secrets with attacker-controlled input without application-level separation. Use `compress=False` when this is a concern.
140
+ - **Resource limits** — `max_output_size` bounds decompressed output. For untrusted inputs, also bound the encrypted input size before calling `open_data`.
141
+
142
+ ## Development
143
+
144
+ ```bash
145
+ uv sync --locked --extra dev
146
+ uv run ruff check .
147
+ uv run mypy kransx
148
+ uv run pytest -q
149
+ ```
150
+
151
+ Pre-commit hooks are configured for `ruff` and `mypy` (see `.pre-commit-config.yaml`).
152
+
153
+ ```
154
+ kransx/ seal, open_data, dicts, cli
155
+ tests/ conformance vectors, tamper checks, resource limits
156
+ ```
157
+
158
+ ## License
159
+
160
+ MIT — see [LICENSE](LICENSE).
kransx-0.1.0/README.md ADDED
@@ -0,0 +1,129 @@
1
+ # KRANSX
2
+
3
+ [![CI](https://github.com/HEKPYTO/KRANSX/actions/workflows/ci.yml/badge.svg)](https://github.com/HEKPYTO/KRANSX/actions)
4
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org)
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
6
+
7
+ Authenticated encryption with adaptive compression for Python.
8
+
9
+ KRANSX seals arbitrary bytes into a compact, authenticated envelope. It applies Zstandard compression only when it reduces size, otherwise stores the payload as-is, and protects both with AES-256-GCM-SIV. The result is a single self-contained binary with 29 bytes of overhead.
10
+
11
+ ## Features
12
+
13
+ - Adaptive compression — Zstandard when beneficial, raw otherwise
14
+ - Authenticated encryption — AES-256-GCM-SIV (nonce-misuse resistant)
15
+ - Small fixed overhead — 29 bytes (`suite` + `nonce` + `tag`)
16
+ - Simple API — `seal` / `open_data`, fully typed
17
+ - Dictionary support — optional Zstandard dictionaries for structured data
18
+ - CLI — `keygen`, `seal`, `open`, `train`
19
+ - No background services or async dependencies
20
+
21
+ ## Installation
22
+
23
+ ```bash
24
+ pip install kransx
25
+ ```
26
+
27
+ For development:
28
+
29
+ ```bash
30
+ uv sync --locked --extra dev
31
+ ```
32
+
33
+ Requires Python 3.10+, `cryptography >= 42`, `zstandard >= 0.22`.
34
+
35
+ ## Usage
36
+
37
+ ### Python API
38
+
39
+ ```python
40
+ import secrets
41
+ from kransx import open_data, seal
42
+
43
+ key = secrets.token_bytes(32) # 32 uniformly random bytes
44
+ aad = b"record-42" # associated data, authenticated but not encrypted
45
+
46
+ sealed = seal(b"hello world", key, aad=aad)
47
+ assert open_data(sealed, key, aad=aad) == b"hello world"
48
+ ```
49
+
50
+ Authentication failures raise `cryptography.exceptions.InvalidTag` (wrong key, AAD, dictionary, or modified bytes). Structural errors raise `ValueError`.
51
+
52
+ With a shared dictionary (non-secret, improves compression on similar payloads):
53
+
54
+ ```python
55
+ from kransx import train_dict
56
+
57
+ dictionary = train_dict([b'{"user":1,"action":"login"}'] * 300)
58
+ sealed = seal(b'{"user":1,"action":"login"}', key, dict_obj=dictionary)
59
+ assert open_data(sealed, key, dict_obj=dictionary) == b'{"user":1,"action":"login"}'
60
+ ```
61
+
62
+ API reference:
63
+
64
+ ```python
65
+ seal(data: bytes, key: bytes, *, dict_obj=None, aad=b"", compress=True, level=3) -> bytes
66
+ open_data(blob: bytes, key: bytes, *, dict_obj=None, aad=b"", max_output_size=64*1024*1024) -> bytes
67
+ train_dict(samples: Iterable[bytes], dict_size=16384) -> ZstdCompressionDict
68
+ save_dict(dictionary, path) / load_dict(path)
69
+ ```
70
+
71
+ `compress=True` retains the Zstandard frame only when strictly smaller than the input. `max_output_size` limits the decompressed output size.
72
+
73
+ ### CLI
74
+
75
+ ```bash
76
+ kransx keygen key.bin
77
+ kransx seal plain.bin sealed.bin --key-file key.bin --aad 7265636f72642d3432
78
+ kransx open sealed.bin restored.bin --key-file key.bin --aad 7265636f72642d3432
79
+
80
+ kransx train 'samples/*.json' --output model.dict
81
+ kransx seal plain.bin out.bin --key-file key.bin --dict model.dict
82
+ kransx open out.bin restored.bin --key-file key.bin --dict model.dict --max-output-size 1048576
83
+ ```
84
+
85
+ - `--aad` accepts hex-encoded bytes
86
+ - `--max-output-size` caps plaintext size on open
87
+ - Output files are created exclusively and never overwritten
88
+
89
+ ## Design
90
+
91
+ Envelope layout: `suite (1) | nonce (12) | ciphertext | tag (16)`
92
+
93
+ | Suite | Payload | Authenticated associated data |
94
+ |-------|---------|-------------------------------|
95
+ | `0x21` | Zstandard frame | `suite` + dictionary binding + `aad` |
96
+ | `0x22` | raw bytes | `suite` + `aad` |
97
+
98
+ - The dictionary binding is `SHA-256` over the dictionary bytes (or a constant for no dictionary), ensuring a mismatched dictionary fails authentication before decompression.
99
+ - Keys are 32 random bytes expanded via HKDF-SHA256 to the AEAD key. A fresh 12-byte nonce is generated per seal.
100
+ - Opening validates the envelope before decryption: size and suite checks, then AEAD authentication, then — for compressed payloads — single-frame Zstandard validation and bounded decompression.
101
+
102
+ ## Security considerations
103
+
104
+ This library implements the envelope only. Key generation, distribution, storage, rotation, and encrypted-input size bounding are the caller's responsibility.
105
+
106
+ - **Keys** must be 32 uniformly random bytes. Passwords are not valid keys.
107
+ - **Nonces** are generated with `os.urandom(12)` per seal. AES-GCM-SIV is nonce-misuse resistant, but reuse should still be avoided.
108
+ - **Compression oracles** — the sealed size reveals whether compression was used. Do not compress data that mixes secrets with attacker-controlled input without application-level separation. Use `compress=False` when this is a concern.
109
+ - **Resource limits** — `max_output_size` bounds decompressed output. For untrusted inputs, also bound the encrypted input size before calling `open_data`.
110
+
111
+ ## Development
112
+
113
+ ```bash
114
+ uv sync --locked --extra dev
115
+ uv run ruff check .
116
+ uv run mypy kransx
117
+ uv run pytest -q
118
+ ```
119
+
120
+ Pre-commit hooks are configured for `ruff` and `mypy` (see `.pre-commit-config.yaml`).
121
+
122
+ ```
123
+ kransx/ seal, open_data, dicts, cli
124
+ tests/ conformance vectors, tamper checks, resource limits
125
+ ```
126
+
127
+ ## License
128
+
129
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,8 @@
1
+ """KRANSX authenticated encryption-envelope reference implementation."""
2
+
3
+ from .core import open_data, seal
4
+ from .dicts import load_dict, save_dict, train_dict
5
+
6
+ __version__ = "0.1.0"
7
+
8
+ __all__ = ["seal", "open_data", "train_dict", "save_dict", "load_dict", "__version__"]
@@ -0,0 +1,160 @@
1
+ """Command-line interface for KRANSX."""
2
+
3
+ import argparse
4
+ import glob
5
+ import os
6
+ import platform
7
+ import zlib
8
+ from collections.abc import Callable
9
+ from pathlib import Path
10
+
11
+ import cryptography
12
+ import zstandard as zstd
13
+ from cryptography.exceptions import InvalidTag
14
+
15
+ from . import __version__
16
+ from .core import open_data, seal
17
+ from .dicts import load_dict, train_dict
18
+
19
+
20
+ def _hex(value: str) -> bytes:
21
+ try:
22
+ return bytes.fromhex(value) if value else b""
23
+ except ValueError as error:
24
+ raise ValueError("AAD must be hexadecimal") from error
25
+
26
+
27
+ def _key(path: str) -> bytes:
28
+ key = Path(path).read_bytes()
29
+ if len(key) != 32:
30
+ raise ValueError("key file must contain exactly 32 raw bytes")
31
+ return key
32
+
33
+
34
+ def _write_new(path: Path, data: bytes) -> None:
35
+ with path.open("xb") as output:
36
+ output.write(data)
37
+
38
+
39
+ def _seal(args: argparse.Namespace) -> None:
40
+ source, target = Path(args.infile), Path(args.outfile)
41
+ dictionary = load_dict(args.dictionary) if args.dictionary else None
42
+ result = seal(
43
+ source.read_bytes(),
44
+ _key(args.key_file),
45
+ dict_obj=dictionary,
46
+ aad=_hex(args.aad),
47
+ compress=not args.no_compress,
48
+ level=args.level,
49
+ )
50
+ _write_new(target, result)
51
+ print(f"sealed {source.stat().st_size} -> {len(result)} bytes")
52
+
53
+
54
+ def _open(args: argparse.Namespace) -> None:
55
+ source, target = Path(args.infile), Path(args.outfile)
56
+ dictionary = load_dict(args.dictionary) if args.dictionary else None
57
+ result = open_data(
58
+ source.read_bytes(),
59
+ _key(args.key_file),
60
+ dict_obj=dictionary,
61
+ aad=_hex(args.aad),
62
+ max_output_size=args.max_output_size,
63
+ )
64
+ _write_new(target, result)
65
+ print(f"opened {source.stat().st_size} -> {len(result)} bytes")
66
+
67
+
68
+ def _train(args: argparse.Namespace) -> None:
69
+ paths = sorted(
70
+ {Path(path) for pattern in args.samples for path in glob.glob(pattern, recursive=True)}
71
+ )
72
+ samples = [path.read_bytes() for path in paths if path.is_file()]
73
+ if not samples:
74
+ raise ValueError("no sample files matched")
75
+ dictionary = train_dict(samples, args.size)
76
+ _write_new(Path(args.outfile), dictionary.as_bytes())
77
+ print(f"trained {len(samples)} samples -> {args.outfile} ({len(dictionary.as_bytes())} bytes)")
78
+
79
+
80
+ def _keygen(args: argparse.Namespace) -> None:
81
+ path = Path(args.key_file)
82
+ descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
83
+ with os.fdopen(descriptor, "wb") as output:
84
+ output.write(os.urandom(32))
85
+ print(f"wrote 32-byte key to {path}")
86
+
87
+
88
+ def _bench(_: argparse.Namespace) -> None:
89
+ key = bytes(range(32))
90
+ corpora = (
91
+ ("repeated-text", b"The quick brown fox jumps over the lazy dog.\n" * 1_000),
92
+ ("structured-json", b'{"event":"login","actor":"alice","ok":true}\n' * 1_000),
93
+ ("small-raw", bytes(range(32))),
94
+ )
95
+ print("KRANSX deterministic size benchmark (generated corpora; not a speed or SOTA claim)")
96
+ print(
97
+ f"kransx={__version__} python={platform.python_version()} "
98
+ f"cryptography={cryptography.__version__} zstandard={zstd.__version__}"
99
+ )
100
+ print(f"{'corpus':16} {'raw':>8} {'zlib':>8} {'zstd':>8} {'envelope':>10} {'stored':>10}")
101
+ for name, data in corpora:
102
+ compressed = zstd.ZstdCompressor(level=3).compress(data)
103
+ envelope = seal(data, key)
104
+ stored = "zstd" if envelope[0] == 0x21 else "raw"
105
+ print(
106
+ f"{name:16} {len(data):8} {len(zlib.compress(data)):8} {len(compressed):8} "
107
+ f"{len(envelope):10} {stored:>10}"
108
+ )
109
+ print("Envelope overhead is 29 bytes: suite (1), nonce (12), and AEAD tag (16).")
110
+
111
+
112
+ def _parser() -> argparse.ArgumentParser:
113
+ parser = argparse.ArgumentParser(prog="kransx")
114
+ commands = parser.add_subparsers(dest="command", required=True)
115
+ seal_parser = commands.add_parser("seal", help="compress then encrypt")
116
+ seal_parser.add_argument("infile")
117
+ seal_parser.add_argument("outfile")
118
+ seal_parser.add_argument("--key-file", required=True)
119
+ seal_parser.add_argument("--dict", dest="dictionary")
120
+ seal_parser.add_argument("--aad", default="", help="hexadecimal associated data")
121
+ seal_parser.add_argument("--no-compress", action="store_true")
122
+ seal_parser.add_argument("--level", type=int, default=3)
123
+ seal_parser.set_defaults(handler=_seal)
124
+ open_parser = commands.add_parser("open", help="authenticate then decrypt")
125
+ open_parser.add_argument("infile")
126
+ open_parser.add_argument("outfile")
127
+ open_parser.add_argument("--key-file", required=True)
128
+ open_parser.add_argument("--dict", dest="dictionary")
129
+ open_parser.add_argument("--aad", default="", help="hexadecimal associated data")
130
+ open_parser.add_argument("--max-output-size", type=int, default=64 * 1024 * 1024)
131
+ open_parser.set_defaults(handler=_open)
132
+ train_parser = commands.add_parser("train", help="train a Zstandard dictionary")
133
+ train_parser.add_argument("samples", nargs="+")
134
+ train_parser.add_argument("-o", "--output", dest="outfile", required=True)
135
+ train_parser.add_argument("--size", type=int, default=16_384)
136
+ train_parser.set_defaults(handler=_train)
137
+ keygen_parser = commands.add_parser("keygen", help="create a new raw 32-byte key file")
138
+ keygen_parser.add_argument("key_file")
139
+ keygen_parser.set_defaults(handler=_keygen)
140
+ bench_parser = commands.add_parser(
141
+ "bench", help="run deterministic generated-corpus size measurements"
142
+ )
143
+ bench_parser.set_defaults(handler=_bench)
144
+ return parser
145
+
146
+
147
+ def main() -> None:
148
+ parser = _parser()
149
+ args = parser.parse_args()
150
+ handler: Callable[[argparse.Namespace], None] = args.handler
151
+ try:
152
+ handler(args)
153
+ except InvalidTag:
154
+ parser.error("authentication failed")
155
+ except (OSError, ValueError, zstd.ZstdError) as error:
156
+ parser.error(str(error))
157
+
158
+
159
+ if __name__ == "__main__":
160
+ main()
@@ -0,0 +1,134 @@
1
+ """Version 0.1 compress-then-encrypt envelope."""
2
+
3
+ import hashlib
4
+ import os
5
+
6
+ import zstandard as zstd
7
+ from cryptography.hazmat.primitives import hashes
8
+ from cryptography.hazmat.primitives.ciphers.aead import AESGCMSIV
9
+ from cryptography.hazmat.primitives.kdf.hkdf import HKDF
10
+
11
+ _NONCE_SIZE = 12
12
+ _TAG_SIZE = 16
13
+ _FIXED_OVERHEAD = 1 + _NONCE_SIZE + _TAG_SIZE
14
+ _SUITES = {0x21: True, 0x22: False}
15
+ _ZSTD_MAGIC = b"\x28\xb5\x2f\xfd"
16
+ _DICT_BINDING_PREFIX = b"kransx/v0.1/zstd-dictionary/"
17
+ _NO_DICT_BINDING = hashlib.sha256(_DICT_BINDING_PREFIX + b"none").digest()
18
+
19
+
20
+ def _require_bytes(name: str, value: object) -> bytes:
21
+ if not isinstance(value, bytes):
22
+ raise TypeError(f"{name} must be bytes")
23
+ return value
24
+
25
+
26
+ def _validate_key(key: object) -> bytes:
27
+ key = _require_bytes("key", key)
28
+ if len(key) != 32:
29
+ raise ValueError("key must be exactly 32 random bytes")
30
+ return key
31
+
32
+
33
+ def _aead_key(key: bytes) -> bytes:
34
+ return HKDF(
35
+ hashes.SHA256(),
36
+ 32,
37
+ None,
38
+ b"kransx/v0.1/aead/aes-256-gcm-siv",
39
+ ).derive(key)
40
+
41
+
42
+ def _compressed_aad(suite: int, aad: bytes, dict_obj: zstd.ZstdCompressionDict | None) -> bytes:
43
+ binding = _NO_DICT_BINDING
44
+ if dict_obj is not None:
45
+ binding = hashlib.sha256(_DICT_BINDING_PREFIX + b"bytes\0" + dict_obj.as_bytes()).digest()
46
+ return bytes([suite]) + binding + aad
47
+
48
+
49
+ def _decompress(payload: bytes, dict_obj: zstd.ZstdCompressionDict | None, limit: int) -> bytes:
50
+ if not payload.startswith(_ZSTD_MAGIC):
51
+ raise ValueError("compressed payload must start with an ordinary Zstandard frame")
52
+ try:
53
+ advertised_size = zstd.frame_content_size(payload)
54
+ if advertised_size == zstd.CONTENTSIZE_ERROR:
55
+ raise ValueError("invalid Zstandard frame")
56
+ if advertised_size != zstd.CONTENTSIZE_UNKNOWN and advertised_size > limit:
57
+ raise ValueError("decompressed data exceeds max_output_size")
58
+ return zstd.ZstdDecompressor(
59
+ dict_data=dict_obj, max_window_size=max(1, (limit + 1023) // 1024)
60
+ ).decompress(payload, max_output_size=limit, allow_extra_data=False)
61
+ except zstd.ZstdError as error:
62
+ raise ValueError("invalid or oversized Zstandard payload") from error
63
+
64
+
65
+ def seal(
66
+ data: bytes,
67
+ key: bytes,
68
+ *,
69
+ dict_obj: zstd.ZstdCompressionDict | None = None,
70
+ aad: bytes = b"",
71
+ compress: bool = True,
72
+ level: int = 3,
73
+ ) -> bytes:
74
+ """Compress *data* when smaller, then encrypt it in a envelope."""
75
+ data = _require_bytes("data", data)
76
+ key = _validate_key(key)
77
+ aad = _require_bytes("aad", aad)
78
+ if not isinstance(compress, bool):
79
+ raise TypeError("compress must be bool")
80
+ if isinstance(level, bool) or not isinstance(level, int):
81
+ raise TypeError("level must be an integer")
82
+
83
+ payload = data
84
+ compressed = False
85
+ if compress:
86
+ candidate = zstd.ZstdCompressor(level=level, dict_data=dict_obj).compress(data)
87
+ if len(candidate) < len(data):
88
+ payload, compressed = candidate, True
89
+ suite = 0x21 if compressed else 0x22
90
+ nonce = os.urandom(_NONCE_SIZE)
91
+ authenticated_data = bytes([suite]) + aad
92
+ if compressed:
93
+ authenticated_data = _compressed_aad(suite, aad, dict_obj)
94
+ ciphertext = AESGCMSIV(_aead_key(key)).encrypt(
95
+ nonce, payload, authenticated_data
96
+ )
97
+ return bytes([suite]) + nonce + ciphertext
98
+
99
+
100
+ def open_data(
101
+ blob: bytes,
102
+ key: bytes,
103
+ *,
104
+ dict_obj: zstd.ZstdCompressionDict | None = None,
105
+ aad: bytes = b"",
106
+ max_output_size: int = 64 * 1024 * 1024,
107
+ ) -> bytes:
108
+ """Authenticate and open a envelope, enforcing an output limit."""
109
+ blob = _require_bytes("blob", blob)
110
+ key = _validate_key(key)
111
+ aad = _require_bytes("aad", aad)
112
+ if isinstance(max_output_size, bool) or not isinstance(max_output_size, int):
113
+ raise TypeError("max_output_size must be an integer")
114
+ if max_output_size <= 0:
115
+ raise ValueError("max_output_size must be positive")
116
+ if len(blob) < _FIXED_OVERHEAD:
117
+ raise ValueError("blob is shorter than the 29-byte envelope overhead")
118
+
119
+ suite = blob[0]
120
+ try:
121
+ compressed = _SUITES[suite]
122
+ except KeyError as error:
123
+ raise ValueError(f"unknown suite byte: {suite:#x}") from error
124
+ if not compressed and len(blob) - _FIXED_OVERHEAD > max_output_size:
125
+ raise ValueError("raw data exceeds max_output_size")
126
+ authenticated_data = bytes([suite]) + aad
127
+ if compressed:
128
+ authenticated_data = _compressed_aad(suite, aad, dict_obj)
129
+ payload = AESGCMSIV(_aead_key(key)).decrypt(
130
+ blob[1 : 1 + _NONCE_SIZE], blob[1 + _NONCE_SIZE :], authenticated_data
131
+ )
132
+ if compressed:
133
+ return _decompress(payload, dict_obj, max_output_size)
134
+ return payload
@@ -0,0 +1,27 @@
1
+ """Zstandard dictionary helpers; dictionaries are shared compression models."""
2
+
3
+ import os
4
+ from collections.abc import Iterable
5
+ from pathlib import Path
6
+
7
+ import zstandard as zstd
8
+
9
+
10
+ def train_dict(samples: Iterable[bytes], dict_size: int = 16_384) -> zstd.ZstdCompressionDict:
11
+ """Train a Zstandard dictionary, propagating training errors to the caller."""
12
+ if isinstance(dict_size, bool) or not isinstance(dict_size, int) or dict_size <= 0:
13
+ raise ValueError("dict_size must be a positive integer")
14
+ sample_list: list[bytes | bytearray | memoryview[int]] = list(samples)
15
+ if any(not isinstance(sample, bytes) for sample in sample_list):
16
+ raise TypeError("samples must contain bytes")
17
+ return zstd.train_dictionary(dict_size, sample_list)
18
+
19
+
20
+ def save_dict(dict_obj: zstd.ZstdCompressionDict, path: str | os.PathLike[str]) -> None:
21
+ """Save a dictionary's public bytes to *path*."""
22
+ Path(path).write_bytes(dict_obj.as_bytes())
23
+
24
+
25
+ def load_dict(path: str | os.PathLike[str]) -> zstd.ZstdCompressionDict:
26
+ """Load an ordinary Zstandard dictionary from *path*."""
27
+ return zstd.ZstdCompressionDict(Path(path).read_bytes())
File without changes
@@ -0,0 +1,160 @@
1
+ Metadata-Version: 2.4
2
+ Name: kransx
3
+ Version: 0.1.0
4
+ Summary: KRANSX authenticated encryption-envelope reference implementation
5
+ Author: KRANSX contributors
6
+ License-Expression: MIT
7
+ Keywords: aead,compression,encryption,zstandard
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Topic :: Security :: Cryptography
11
+ Classifier: Topic :: System :: Archiving :: Compression
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Programming Language :: Python :: 3.14
18
+ Classifier: Operating System :: OS Independent
19
+ Classifier: Typing :: Typed
20
+ Requires-Python: >=3.10
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Requires-Dist: cryptography>=42
24
+ Requires-Dist: zstandard>=0.22
25
+ Provides-Extra: dev
26
+ Requires-Dist: mypy>=1.10; extra == "dev"
27
+ Requires-Dist: pre-commit>=4; extra == "dev"
28
+ Requires-Dist: pytest>=7; extra == "dev"
29
+ Requires-Dist: ruff>=0.4; extra == "dev"
30
+ Dynamic: license-file
31
+
32
+ # KRANSX
33
+
34
+ [![CI](https://github.com/HEKPYTO/KRANSX/actions/workflows/ci.yml/badge.svg)](https://github.com/HEKPYTO/KRANSX/actions)
35
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org)
36
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
37
+
38
+ Authenticated encryption with adaptive compression for Python.
39
+
40
+ KRANSX seals arbitrary bytes into a compact, authenticated envelope. It applies Zstandard compression only when it reduces size, otherwise stores the payload as-is, and protects both with AES-256-GCM-SIV. The result is a single self-contained binary with 29 bytes of overhead.
41
+
42
+ ## Features
43
+
44
+ - Adaptive compression — Zstandard when beneficial, raw otherwise
45
+ - Authenticated encryption — AES-256-GCM-SIV (nonce-misuse resistant)
46
+ - Small fixed overhead — 29 bytes (`suite` + `nonce` + `tag`)
47
+ - Simple API — `seal` / `open_data`, fully typed
48
+ - Dictionary support — optional Zstandard dictionaries for structured data
49
+ - CLI — `keygen`, `seal`, `open`, `train`
50
+ - No background services or async dependencies
51
+
52
+ ## Installation
53
+
54
+ ```bash
55
+ pip install kransx
56
+ ```
57
+
58
+ For development:
59
+
60
+ ```bash
61
+ uv sync --locked --extra dev
62
+ ```
63
+
64
+ Requires Python 3.10+, `cryptography >= 42`, `zstandard >= 0.22`.
65
+
66
+ ## Usage
67
+
68
+ ### Python API
69
+
70
+ ```python
71
+ import secrets
72
+ from kransx import open_data, seal
73
+
74
+ key = secrets.token_bytes(32) # 32 uniformly random bytes
75
+ aad = b"record-42" # associated data, authenticated but not encrypted
76
+
77
+ sealed = seal(b"hello world", key, aad=aad)
78
+ assert open_data(sealed, key, aad=aad) == b"hello world"
79
+ ```
80
+
81
+ Authentication failures raise `cryptography.exceptions.InvalidTag` (wrong key, AAD, dictionary, or modified bytes). Structural errors raise `ValueError`.
82
+
83
+ With a shared dictionary (non-secret, improves compression on similar payloads):
84
+
85
+ ```python
86
+ from kransx import train_dict
87
+
88
+ dictionary = train_dict([b'{"user":1,"action":"login"}'] * 300)
89
+ sealed = seal(b'{"user":1,"action":"login"}', key, dict_obj=dictionary)
90
+ assert open_data(sealed, key, dict_obj=dictionary) == b'{"user":1,"action":"login"}'
91
+ ```
92
+
93
+ API reference:
94
+
95
+ ```python
96
+ seal(data: bytes, key: bytes, *, dict_obj=None, aad=b"", compress=True, level=3) -> bytes
97
+ open_data(blob: bytes, key: bytes, *, dict_obj=None, aad=b"", max_output_size=64*1024*1024) -> bytes
98
+ train_dict(samples: Iterable[bytes], dict_size=16384) -> ZstdCompressionDict
99
+ save_dict(dictionary, path) / load_dict(path)
100
+ ```
101
+
102
+ `compress=True` retains the Zstandard frame only when strictly smaller than the input. `max_output_size` limits the decompressed output size.
103
+
104
+ ### CLI
105
+
106
+ ```bash
107
+ kransx keygen key.bin
108
+ kransx seal plain.bin sealed.bin --key-file key.bin --aad 7265636f72642d3432
109
+ kransx open sealed.bin restored.bin --key-file key.bin --aad 7265636f72642d3432
110
+
111
+ kransx train 'samples/*.json' --output model.dict
112
+ kransx seal plain.bin out.bin --key-file key.bin --dict model.dict
113
+ kransx open out.bin restored.bin --key-file key.bin --dict model.dict --max-output-size 1048576
114
+ ```
115
+
116
+ - `--aad` accepts hex-encoded bytes
117
+ - `--max-output-size` caps plaintext size on open
118
+ - Output files are created exclusively and never overwritten
119
+
120
+ ## Design
121
+
122
+ Envelope layout: `suite (1) | nonce (12) | ciphertext | tag (16)`
123
+
124
+ | Suite | Payload | Authenticated associated data |
125
+ |-------|---------|-------------------------------|
126
+ | `0x21` | Zstandard frame | `suite` + dictionary binding + `aad` |
127
+ | `0x22` | raw bytes | `suite` + `aad` |
128
+
129
+ - The dictionary binding is `SHA-256` over the dictionary bytes (or a constant for no dictionary), ensuring a mismatched dictionary fails authentication before decompression.
130
+ - Keys are 32 random bytes expanded via HKDF-SHA256 to the AEAD key. A fresh 12-byte nonce is generated per seal.
131
+ - Opening validates the envelope before decryption: size and suite checks, then AEAD authentication, then — for compressed payloads — single-frame Zstandard validation and bounded decompression.
132
+
133
+ ## Security considerations
134
+
135
+ This library implements the envelope only. Key generation, distribution, storage, rotation, and encrypted-input size bounding are the caller's responsibility.
136
+
137
+ - **Keys** must be 32 uniformly random bytes. Passwords are not valid keys.
138
+ - **Nonces** are generated with `os.urandom(12)` per seal. AES-GCM-SIV is nonce-misuse resistant, but reuse should still be avoided.
139
+ - **Compression oracles** — the sealed size reveals whether compression was used. Do not compress data that mixes secrets with attacker-controlled input without application-level separation. Use `compress=False` when this is a concern.
140
+ - **Resource limits** — `max_output_size` bounds decompressed output. For untrusted inputs, also bound the encrypted input size before calling `open_data`.
141
+
142
+ ## Development
143
+
144
+ ```bash
145
+ uv sync --locked --extra dev
146
+ uv run ruff check .
147
+ uv run mypy kransx
148
+ uv run pytest -q
149
+ ```
150
+
151
+ Pre-commit hooks are configured for `ruff` and `mypy` (see `.pre-commit-config.yaml`).
152
+
153
+ ```
154
+ kransx/ seal, open_data, dicts, cli
155
+ tests/ conformance vectors, tamper checks, resource limits
156
+ ```
157
+
158
+ ## License
159
+
160
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,15 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ kransx/__init__.py
5
+ kransx/cli.py
6
+ kransx/core.py
7
+ kransx/dicts.py
8
+ kransx/py.typed
9
+ kransx.egg-info/PKG-INFO
10
+ kransx.egg-info/SOURCES.txt
11
+ kransx.egg-info/dependency_links.txt
12
+ kransx.egg-info/entry_points.txt
13
+ kransx.egg-info/requires.txt
14
+ kransx.egg-info/top_level.txt
15
+ tests/test_kransx.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ kransx = kransx.cli:main
@@ -0,0 +1,8 @@
1
+ cryptography>=42
2
+ zstandard>=0.22
3
+
4
+ [dev]
5
+ mypy>=1.10
6
+ pre-commit>=4
7
+ pytest>=7
8
+ ruff>=0.4
@@ -0,0 +1 @@
1
+ kransx
@@ -0,0 +1,56 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "kransx"
7
+ version = "0.1.0"
8
+ description = "KRANSX authenticated encryption-envelope reference implementation"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ authors = [{name = "KRANSX contributors"}]
13
+ classifiers = [
14
+ "Development Status :: 3 - Alpha",
15
+ "Intended Audience :: Developers",
16
+ "Topic :: Security :: Cryptography",
17
+ "Topic :: System :: Archiving :: Compression",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3.10",
20
+ "Programming Language :: Python :: 3.11",
21
+ "Programming Language :: Python :: 3.12",
22
+ "Programming Language :: Python :: 3.13",
23
+ "Programming Language :: Python :: 3.14",
24
+ "Operating System :: OS Independent",
25
+ "Typing :: Typed",
26
+ ]
27
+ keywords = ["aead", "compression", "encryption", "zstandard"]
28
+ dependencies = ["cryptography>=42", "zstandard>=0.22"]
29
+
30
+ [project.optional-dependencies]
31
+ dev = ["mypy>=1.10", "pre-commit>=4", "pytest>=7", "ruff>=0.4"]
32
+
33
+ [project.scripts]
34
+ kransx = "kransx.cli:main"
35
+
36
+ [tool.setuptools.packages.find]
37
+ include = ["kransx"]
38
+
39
+ [tool.setuptools.package-data]
40
+ kransx = ["py.typed"]
41
+
42
+ [tool.pytest.ini_options]
43
+ testpaths = ["tests"]
44
+ addopts = "-q"
45
+
46
+ [tool.ruff]
47
+ line-length = 100
48
+ target-version = "py310"
49
+
50
+ [tool.ruff.lint]
51
+ select = ["E", "F", "W", "B", "UP", "SIM"]
52
+
53
+ [tool.mypy]
54
+ python_version = "3.10"
55
+ strict = true
56
+ warn_unused_configs = true
kransx-0.1.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,310 @@
1
+ import os
2
+ import subprocess
3
+ import sys
4
+ from pathlib import Path
5
+
6
+ import pytest
7
+ import zstandard as zstd
8
+ from cryptography.exceptions import InvalidTag
9
+
10
+ import kransx.core as core
11
+ from kransx import load_dict, open_data, save_dict, seal, train_dict
12
+
13
+
14
+ MASTER_KEY = bytes(range(32))
15
+ RAW_DATA = b"raw conformance"
16
+ RAW_AAD = b"context/raw"
17
+ RAW_ENVELOPE = bytes.fromhex(
18
+ "22000102030405060708090a0b2713d344ba60e715b1ba535c474736a1dea83de5477abfb43c9279028f2ecc"
19
+ )
20
+ COMPRESSED_DATA = b"KRANS-X compressed conformance payload.\n" * 12
21
+ COMPRESSED_AAD = b"context/compressed"
22
+ COMPRESSED_ENVELOPE = bytes.fromhex(
23
+ "21f0f1f2f3f4f5f6f7f8f9fafb92b8e0e2b9e90d7542e553cd2fa9a999cde676f96f0878097cb71fdebe05d19ee7561c6d1fc2bd6f7f61ac1184a49abd6d6c85fa522132cddb3f0b2287be72d50214ee6ebcfd853fcdcaba"
24
+ )
25
+ UNKNOWN_SIZE_COMPRESSED_ENVELOPE = bytes.fromhex(
26
+ "2100112233445566778899aabbe311494f3b244bb769c9838c91ab7cfd2e4c57d82389a345f2336ab42cc201ca273c"
27
+ )
28
+ _REFERENCE_ZSTD = ("0.25.0", (1, 5, 7))
29
+
30
+
31
+ def _authenticated_compressed_payload(payload: bytes) -> bytes:
32
+ nonce, aad = bytes.fromhex("102132435465768798a9bacb"), b"trailing-frame"
33
+ ciphertext = core.AESGCMSIV(core._aead_key(MASTER_KEY)).encrypt(
34
+ nonce, payload, core._compressed_aad(0x21, aad, None)
35
+ )
36
+ return b"\x21" + nonce + ciphertext
37
+
38
+
39
+ def _skippable_frame(data: bytes = b"") -> bytes:
40
+ return b"\x50\x2a\x4d\x18" + len(data).to_bytes(4, "little") + data
41
+
42
+
43
+ def test_raw_conformance_vector(monkeypatch: pytest.MonkeyPatch) -> None:
44
+ """Fixed nonces are test-only and document the construction."""
45
+ monkeypatch.setattr("kransx.core.os.urandom", lambda size: bytes(range(12)))
46
+ assert seal(RAW_DATA, MASTER_KEY, aad=RAW_AAD, compress=False) == RAW_ENVELOPE
47
+ assert open_data(RAW_ENVELOPE, MASTER_KEY, aad=RAW_AAD) == RAW_DATA
48
+
49
+
50
+ def test_compressed_conformance_vector_opens_on_all_versions(
51
+ monkeypatch: pytest.MonkeyPatch,
52
+ ) -> None:
53
+ assert open_data(COMPRESSED_ENVELOPE, MASTER_KEY, aad=COMPRESSED_AAD) == COMPRESSED_DATA
54
+ if (zstd.__version__, zstd.ZSTD_VERSION) != _REFERENCE_ZSTD:
55
+ return
56
+ monkeypatch.setattr("kransx.core.os.urandom", lambda size: bytes(range(0xF0, 0xFC)))
57
+ assert seal(COMPRESSED_DATA, MASTER_KEY, aad=COMPRESSED_AAD) == COMPRESSED_ENVELOPE
58
+
59
+
60
+ def test_round_trip_for_both_suites() -> None:
61
+ assert RAW_ENVELOPE[0] == 0x22
62
+ assert COMPRESSED_ENVELOPE[0] == 0x21
63
+ assert open_data(RAW_ENVELOPE, MASTER_KEY, aad=RAW_AAD) == RAW_DATA
64
+ assert open_data(COMPRESSED_ENVELOPE, MASTER_KEY, aad=COMPRESSED_AAD) == COMPRESSED_DATA
65
+
66
+
67
+ def test_adaptive_raw_and_forced_raw_round_trip() -> None:
68
+ data = os.urandom(2_048)
69
+ adaptive = seal(data, MASTER_KEY)
70
+ forced = seal(data, MASTER_KEY, compress=False)
71
+ assert adaptive[0] == 0x22
72
+ assert forced[0] == 0x22
73
+ assert open_data(adaptive, MASTER_KEY) == data
74
+ assert open_data(forced, MASTER_KEY) == data
75
+
76
+
77
+ @pytest.mark.parametrize("region", [0, 1, 13, -1])
78
+ def test_every_envelope_region_is_authenticated(region: int) -> None:
79
+ tampered = bytearray(COMPRESSED_ENVELOPE)
80
+ if region == 0:
81
+ tampered[region] = 0x22
82
+ else:
83
+ tampered[region] ^= 1
84
+ with pytest.raises(InvalidTag):
85
+ open_data(bytes(tampered), MASTER_KEY, aad=COMPRESSED_AAD)
86
+
87
+
88
+ @pytest.mark.parametrize("size", range(len(RAW_ENVELOPE)))
89
+ def test_truncation_boundaries_fail(size: int) -> None:
90
+ expected_error = ValueError if size < 29 else InvalidTag
91
+ with pytest.raises(expected_error):
92
+ open_data(RAW_ENVELOPE[:size], MASTER_KEY, aad=RAW_AAD)
93
+
94
+
95
+ def test_wrong_key_aad_and_dictionary_fail_authentication() -> None:
96
+ with pytest.raises(InvalidTag):
97
+ open_data(COMPRESSED_ENVELOPE, bytes(reversed(MASTER_KEY)), aad=COMPRESSED_AAD)
98
+ with pytest.raises(InvalidTag):
99
+ open_data(COMPRESSED_ENVELOPE, MASTER_KEY, aad=b"other")
100
+ wrong_dict = zstd.ZstdCompressionDict(
101
+ b"different dictionary", dict_type=zstd.DICT_TYPE_RAWCONTENT
102
+ )
103
+ with pytest.raises(InvalidTag):
104
+ open_data(COMPRESSED_ENVELOPE, MASTER_KEY, dict_obj=wrong_dict, aad=COMPRESSED_AAD)
105
+
106
+
107
+ def test_raw_size_is_rejected_before_decryption(monkeypatch: pytest.MonkeyPatch) -> None:
108
+ class MustNotDecrypt:
109
+ def __init__(self, _: bytes) -> None:
110
+ raise AssertionError("raw output limit must precede AEAD construction")
111
+
112
+ oversized = b"\x22" + bytes(12 + 10 + 16)
113
+ monkeypatch.setattr(core, "AESGCMSIV", MustNotDecrypt)
114
+ with pytest.raises(ValueError, match="raw data"):
115
+ open_data(oversized, MASTER_KEY, max_output_size=9)
116
+
117
+
118
+ def test_decompression_limits_known_and_unknown_size_frames() -> None:
119
+ with pytest.raises(ValueError, match="max_output_size"):
120
+ open_data(COMPRESSED_ENVELOPE, MASTER_KEY, aad=COMPRESSED_AAD, max_output_size=99)
121
+ with pytest.raises(ValueError, match="oversized"):
122
+ open_data(
123
+ UNKNOWN_SIZE_COMPRESSED_ENVELOPE, MASTER_KEY, aad=b"unknown-size", max_output_size=99
124
+ )
125
+ assert (
126
+ open_data(UNKNOWN_SIZE_COMPRESSED_ENVELOPE, MASTER_KEY, aad=b"unknown-size") == b"Z" * 4096
127
+ )
128
+
129
+
130
+ @pytest.mark.parametrize(
131
+ "trailer", [b"junk", zstd.ZstdCompressor().compress(b"second frame")]
132
+ )
133
+ def test_compressed_trailing_data_is_rejected(trailer: bytes) -> None:
134
+ payload = zstd.ZstdCompressor().compress(b"first frame") + trailer
135
+ with pytest.raises(ValueError, match="invalid or oversized"):
136
+ open_data(_authenticated_compressed_payload(payload), MASTER_KEY, aad=b"trailing-frame")
137
+
138
+
139
+ @pytest.mark.parametrize(
140
+ "payload",
141
+ [
142
+ _skippable_frame() + zstd.ZstdCompressor().compress(b"ordinary frame"),
143
+ _skippable_frame() + b"junk",
144
+ ],
145
+ )
146
+ def test_compressed_skippable_frame_is_rejected(payload: bytes) -> None:
147
+ with pytest.raises(ValueError, match="ordinary Zstandard"):
148
+ open_data(_authenticated_compressed_payload(payload), MASTER_KEY, aad=b"trailing-frame")
149
+
150
+
151
+ def test_validation_and_unknown_suite() -> None:
152
+ with pytest.raises(ValueError, match="32 random"):
153
+ seal(b"x", b"short")
154
+ with pytest.raises(TypeError, match="data"):
155
+ seal("x", MASTER_KEY) # type: ignore[arg-type]
156
+ with pytest.raises(TypeError, match="aad"):
157
+ seal(b"x", MASTER_KEY, aad="header") # type: ignore[arg-type]
158
+ with pytest.raises(TypeError, match="compress"):
159
+ seal(b"x", MASTER_KEY, compress=1) # type: ignore[arg-type]
160
+ with pytest.raises(TypeError, match="level"):
161
+ seal(b"x", MASTER_KEY, level=True) # type: ignore[arg-type]
162
+ with pytest.raises(ValueError, match="shorter"):
163
+ open_data(b"", MASTER_KEY)
164
+ with pytest.raises(ValueError, match="unknown"):
165
+ open_data(bytes([0x99]) + bytes(28), MASTER_KEY)
166
+ with pytest.raises(TypeError, match="max_output_size"):
167
+ open_data(RAW_ENVELOPE, MASTER_KEY, max_output_size=True)
168
+ with pytest.raises(ValueError, match="positive"):
169
+ open_data(RAW_ENVELOPE, MASTER_KEY, max_output_size=0)
170
+
171
+
172
+ def test_dictionary_save_load_round_trip_and_mismatch(tmp_path: Path) -> None:
173
+ samples = [f'{{"user":{index},"action":"login","ok":true}}'.encode() for index in range(300)]
174
+ dictionary = train_dict(samples, 2_048)
175
+ path = tmp_path / "model.dict"
176
+ save_dict(dictionary, path)
177
+ loaded = load_dict(path)
178
+ data = samples[42]
179
+ blob = seal(data, MASTER_KEY, dict_obj=loaded)
180
+ assert open_data(blob, MASTER_KEY, dict_obj=loaded) == data
181
+ other_samples = [b"different sample data " + bytes([index % 256]) * 30 for index in range(300)]
182
+ other = train_dict(other_samples, 2_048)
183
+ with pytest.raises(InvalidTag):
184
+ open_data(blob, MASTER_KEY, dict_obj=other)
185
+
186
+
187
+ def test_raw_content_dictionary_substitution_fails_authentication() -> None:
188
+ raw_good = b"0123456789abcdef" * 128
189
+ raw_bad = b"fedcba9876543210" * 128
190
+ data = raw_good[-512:] + b"!"
191
+ good = zstd.ZstdCompressionDict(raw_good, dict_type=zstd.DICT_TYPE_RAWCONTENT)
192
+ substitute = zstd.ZstdCompressionDict(raw_bad, dict_type=zstd.DICT_TYPE_RAWCONTENT)
193
+ blob = seal(data, MASTER_KEY, dict_obj=good)
194
+ assert blob[0] == 0x21
195
+ assert open_data(blob, MASTER_KEY, dict_obj=good) == data
196
+ with pytest.raises(InvalidTag):
197
+ open_data(blob, MASTER_KEY)
198
+ with pytest.raises(InvalidTag):
199
+ open_data(blob, MASTER_KEY, dict_obj=substitute)
200
+
201
+
202
+ def test_cli_key_file_round_trip_and_expected_errors(tmp_path: Path) -> None:
203
+ key, source, sealed, opened = (tmp_path / name for name in ("key", "in", "sealed", "out"))
204
+ source.write_bytes(b"cli data" * 100)
205
+ result = subprocess.run(
206
+ [sys.executable, "-m", "kransx.cli", "keygen", str(key)], text=True, capture_output=True
207
+ )
208
+ assert result.returncode == 0, result.stderr
209
+ if os.name != "nt":
210
+ assert key.stat().st_mode & 0o777 == 0o600
211
+ result = subprocess.run(
212
+ [sys.executable, "-m", "kransx.cli", "keygen", str(key)], text=True, capture_output=True
213
+ )
214
+ assert result.returncode == 2
215
+ assert "File exists" in result.stderr
216
+ result = subprocess.run(
217
+ [
218
+ sys.executable,
219
+ "-m",
220
+ "kransx.cli",
221
+ "seal",
222
+ str(source),
223
+ str(sealed),
224
+ "--key-file",
225
+ str(key),
226
+ ],
227
+ text=True,
228
+ capture_output=True,
229
+ )
230
+ assert result.returncode == 0, result.stderr
231
+ result = subprocess.run(
232
+ [
233
+ sys.executable,
234
+ "-m",
235
+ "kransx.cli",
236
+ "open",
237
+ str(sealed),
238
+ str(opened),
239
+ "--key-file",
240
+ str(key),
241
+ ],
242
+ text=True,
243
+ capture_output=True,
244
+ )
245
+ assert result.returncode == 0, result.stderr
246
+ assert opened.read_bytes() == source.read_bytes()
247
+ wrong_key = tmp_path / "wrong-key"
248
+ wrong_key.write_bytes(bytes(32))
249
+ result = subprocess.run(
250
+ [
251
+ sys.executable,
252
+ "-m",
253
+ "kransx.cli",
254
+ "open",
255
+ str(sealed),
256
+ str(opened),
257
+ "--key-file",
258
+ str(wrong_key),
259
+ ],
260
+ text=True,
261
+ capture_output=True,
262
+ )
263
+ assert result.returncode == 2
264
+ assert "authentication failed" in result.stderr
265
+ assert "Traceback" not in result.stderr
266
+ existing_output = tmp_path / "existing-output"
267
+ existing_output.write_bytes(b"do not replace")
268
+ result = subprocess.run(
269
+ [
270
+ sys.executable,
271
+ "-m",
272
+ "kransx.cli",
273
+ "seal",
274
+ str(source),
275
+ str(existing_output),
276
+ "--key-file",
277
+ str(key),
278
+ ],
279
+ text=True,
280
+ capture_output=True,
281
+ )
282
+ assert result.returncode == 2
283
+ assert "File exists" in result.stderr
284
+ assert "Traceback" not in result.stderr
285
+ assert existing_output.read_bytes() == b"do not replace"
286
+ if not hasattr(os, "link"):
287
+ return
288
+ key_alias = tmp_path / "key-alias"
289
+ try:
290
+ os.link(key, key_alias)
291
+ except OSError:
292
+ pytest.skip("hard links are unavailable")
293
+ original_key = key.read_bytes()
294
+ result = subprocess.run(
295
+ [
296
+ sys.executable,
297
+ "-m",
298
+ "kransx.cli",
299
+ "seal",
300
+ str(source),
301
+ str(key_alias),
302
+ "--key-file",
303
+ str(key),
304
+ ],
305
+ text=True,
306
+ capture_output=True,
307
+ )
308
+ assert result.returncode == 2
309
+ assert "Traceback" not in result.stderr
310
+ assert key.read_bytes() == original_key