kransx 0.1.0__py3-none-any.whl
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/__init__.py +8 -0
- kransx/cli.py +160 -0
- kransx/core.py +134 -0
- kransx/dicts.py +27 -0
- kransx/py.typed +0 -0
- kransx-0.1.0.dist-info/METADATA +160 -0
- kransx-0.1.0.dist-info/RECORD +11 -0
- kransx-0.1.0.dist-info/WHEEL +5 -0
- kransx-0.1.0.dist-info/entry_points.txt +2 -0
- kransx-0.1.0.dist-info/licenses/LICENSE +21 -0
- kransx-0.1.0.dist-info/top_level.txt +1 -0
kransx/__init__.py
ADDED
|
@@ -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__"]
|
kransx/cli.py
ADDED
|
@@ -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()
|
kransx/core.py
ADDED
|
@@ -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
|
kransx/dicts.py
ADDED
|
@@ -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())
|
kransx/py.typed
ADDED
|
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
|
+
[](https://github.com/HEKPYTO/KRANSX/actions)
|
|
35
|
+
[](https://www.python.org)
|
|
36
|
+
[](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,11 @@
|
|
|
1
|
+
kransx/__init__.py,sha256=mH18CoEtrHnQLSDjzMswQ_YSA7NmYpZwcVguHPCAqKs,271
|
|
2
|
+
kransx/cli.py,sha256=Lquc5slvUNF95YnEy_bD3_fKoXvOj3yVrc_wWFXOLtQ,5953
|
|
3
|
+
kransx/core.py,sha256=ofjAusAGRaaKQ1nIwsWRGxwCYGsSSwU-YuqMKm6SSuY,4787
|
|
4
|
+
kransx/dicts.py,sha256=DE2YXIJB3FMEHaDvM893C3t7sS7JXAElGfHrtkIIc90,1157
|
|
5
|
+
kransx/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
kransx-0.1.0.dist-info/licenses/LICENSE,sha256=4Jrhz2LpxmDjlg-o5yDKtsUcjjb51_9qig3I8yfdqGQ,1063
|
|
7
|
+
kransx-0.1.0.dist-info/METADATA,sha256=5VSobqXLQKZaS0mhlxgPMS2GRnYpdQx7aAW-uIvEtbM,6235
|
|
8
|
+
kransx-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
|
|
9
|
+
kransx-0.1.0.dist-info/entry_points.txt,sha256=r_nxPVxPtU6XdMUMp2Jauf5yrEGAvkwnFwZTldLFy2k,43
|
|
10
|
+
kransx-0.1.0.dist-info/top_level.txt,sha256=wP8pe1Lev2Kx5D4ZMWh2jucONPKyBHCoCTyuNC-rlU8,7
|
|
11
|
+
kransx-0.1.0.dist-info/RECORD,,
|
|
@@ -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.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
kransx
|