b53 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.
b53/__init__.py ADDED
@@ -0,0 +1,54 @@
1
+ """b53 — Reversible 53-bit cryptographic packing of bool[1..50] into IEEE 754 double."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from b53.core import (
6
+ BASES,
7
+ DEFAULT_SALT_BYTES,
8
+ FEISTEL_ROUNDS,
9
+ LEFT_BITS,
10
+ MANTISSA_BITS,
11
+ MAX_LEN,
12
+ MIN_LEN,
13
+ MIN_SALT_BYTES,
14
+ NONCE_COUNTS,
15
+ RIGHT_BITS,
16
+ SIZES,
17
+ STATE_SPACE,
18
+ B53Cipher,
19
+ Cipher,
20
+ decrypt,
21
+ decrypt_bool_array,
22
+ encrypt,
23
+ encrypt_bool_array,
24
+ format_bits,
25
+ generate_salt,
26
+ parse_bits,
27
+ )
28
+
29
+ __version__ = "0.1.0"
30
+
31
+ __all__ = [
32
+ "BASES",
33
+ "DEFAULT_SALT_BYTES",
34
+ "FEISTEL_ROUNDS",
35
+ "LEFT_BITS",
36
+ "MANTISSA_BITS",
37
+ "MAX_LEN",
38
+ "MIN_LEN",
39
+ "MIN_SALT_BYTES",
40
+ "NONCE_COUNTS",
41
+ "RIGHT_BITS",
42
+ "SIZES",
43
+ "STATE_SPACE",
44
+ "B53Cipher",
45
+ "Cipher",
46
+ "__version__",
47
+ "decrypt",
48
+ "decrypt_bool_array",
49
+ "encrypt",
50
+ "encrypt_bool_array",
51
+ "format_bits",
52
+ "generate_salt",
53
+ "parse_bits",
54
+ ]
b53/__main__.py ADDED
@@ -0,0 +1,8 @@
1
+ """Allow ``python -m b53`` execution."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from b53.cli import main
6
+
7
+ if __name__ == "__main__":
8
+ raise SystemExit(main())
b53/cli.py ADDED
@@ -0,0 +1,162 @@
1
+ """Command-line interface for b53."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import os
7
+ import sys
8
+ from collections.abc import Sequence
9
+ from pathlib import Path
10
+
11
+ from b53 import __version__
12
+ from b53.core import (
13
+ DEFAULT_SALT_BYTES,
14
+ NONCE_COUNTS,
15
+ decrypt_bool_array,
16
+ encrypt_bool_array,
17
+ format_bits,
18
+ generate_salt,
19
+ parse_bits,
20
+ )
21
+
22
+
23
+ def _resolve_salt(salt: str | None, salt_file: Path | None) -> str:
24
+ if salt is not None and salt_file is not None:
25
+ raise ValueError("Specify either --salt or --salt-file, not both.")
26
+ if salt is not None:
27
+ return salt
28
+ if salt_file is not None:
29
+ return salt_file.read_text(encoding="utf-8").strip()
30
+ env_salt = os.environ.get("B53_SALT")
31
+ if env_salt:
32
+ return env_salt
33
+ raise ValueError("A secret salt is required (--salt, --salt-file, or B53_SALT).")
34
+
35
+
36
+ def _build_parser() -> argparse.ArgumentParser:
37
+ parser = argparse.ArgumentParser(
38
+ prog="b53",
39
+ description=(
40
+ "Reversible 53-bit cryptographic packing of bool arrays (1..50) "
41
+ "into IEEE 754 double values in [0.0, 1.0)."
42
+ ),
43
+ )
44
+ parser.add_argument(
45
+ "--version",
46
+ action="version",
47
+ version=f"%(prog)s {__version__}",
48
+ )
49
+
50
+ subparsers = parser.add_subparsers(dest="command", required=True)
51
+
52
+ salt_parser = subparsers.add_parser(
53
+ "generate-salt",
54
+ aliases=["keygen"],
55
+ help="Generate a cryptographically secure hex-encoded salt.",
56
+ )
57
+ salt_parser.add_argument(
58
+ "--bytes",
59
+ type=int,
60
+ default=DEFAULT_SALT_BYTES,
61
+ help=f"Key length in bytes (default: {DEFAULT_SALT_BYTES} bytes = 256 bits).",
62
+ )
63
+ salt_parser.add_argument(
64
+ "--out",
65
+ type=Path,
66
+ default=None,
67
+ help="Optional output file path to save the generated salt.",
68
+ )
69
+
70
+ enc_parser = subparsers.add_parser(
71
+ "encrypt",
72
+ help="Encrypt a boolean array into a double in [0.0, 1.0).",
73
+ )
74
+ enc_parser.add_argument(
75
+ "bits",
76
+ help="Boolean array as bit string (1011001) or comma list (true,false,true).",
77
+ )
78
+ enc_parser.add_argument("--salt", default=None, help="Secret salt (hex or UTF-8 string).")
79
+ enc_parser.add_argument("--salt-file", type=Path, default=None, help="Read salt from file.")
80
+ enc_parser.add_argument(
81
+ "--count",
82
+ type=int,
83
+ default=1,
84
+ help="Number of independent random encryptions to generate.",
85
+ )
86
+ enc_parser.add_argument(
87
+ "-q",
88
+ "--quiet",
89
+ action="store_true",
90
+ help="Print only the resulting double value(s).",
91
+ )
92
+
93
+ dec_parser = subparsers.add_parser(
94
+ "decrypt",
95
+ help="Decrypt a double back into the original boolean array.",
96
+ )
97
+ dec_parser.add_argument(
98
+ "value",
99
+ help="IEEE 754 double value with full precision (e.g. repr(x)).",
100
+ )
101
+ dec_parser.add_argument("--salt", default=None, help="Secret salt used during encryption.")
102
+ dec_parser.add_argument("--salt-file", type=Path, default=None, help="Read salt from file.")
103
+ dec_parser.add_argument(
104
+ "-q",
105
+ "--quiet",
106
+ action="store_true",
107
+ help="Print only the restored bit string.",
108
+ )
109
+
110
+ return parser
111
+
112
+
113
+ def main(argv: Sequence[str] | None = None) -> int:
114
+ """Entry point for the ``b53`` CLI."""
115
+ parser = _build_parser()
116
+ args = parser.parse_args(list(argv) if argv is not None else None)
117
+
118
+ try:
119
+ if args.command in ("generate-salt", "keygen"):
120
+ salt = generate_salt(args.bytes)
121
+ if args.out is not None:
122
+ args.out.write_text(salt + "\n", encoding="utf-8")
123
+ print(f"Salt saved to {args.out}: {salt}")
124
+ else:
125
+ print(salt)
126
+ return 0
127
+
128
+ if args.command == "encrypt":
129
+ if args.count < 1:
130
+ raise ValueError("--count must be at least 1.")
131
+ salt = _resolve_salt(args.salt, args.salt_file)
132
+ bool_array = parse_bits(args.bits)
133
+ if not args.quiet:
134
+ print(
135
+ f"Length: {len(bool_array)} | "
136
+ f"Available random nonces: {NONCE_COUNTS[len(bool_array)]}"
137
+ )
138
+ for idx in range(1, args.count + 1):
139
+ encoded = encrypt_bool_array(bool_array, salt)
140
+ prefix = f"[{idx}] " if (args.count > 1 and not args.quiet) else ""
141
+ print(f"{prefix}{encoded!r}")
142
+ return 0
143
+
144
+ if args.command == "decrypt":
145
+ salt = _resolve_salt(args.salt, args.salt_file)
146
+ double_val = float(args.value)
147
+ restored = decrypt_bool_array(double_val, salt)
148
+ bit_string = format_bits(restored)
149
+ if args.quiet:
150
+ print(bit_string)
151
+ else:
152
+ print(f"Restored length: {len(restored)}")
153
+ print(f"Bit string: {bit_string}")
154
+ print(f"Python list: {restored}")
155
+ return 0
156
+
157
+ parser.error(f"Unknown command: {args.command}")
158
+ except (OSError, TypeError, ValueError) as exc:
159
+ print(f"Error: {exc}", file=sys.stderr)
160
+ return 1
161
+
162
+ return 0
b53/core.py ADDED
@@ -0,0 +1,287 @@
1
+ """Core 53-bit reversible boolean-array packing and Feistel cipher."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hmac
6
+ import math
7
+ import secrets
8
+ from bisect import bisect_right
9
+ from collections.abc import Iterable, Mapping
10
+
11
+ MANTISSA_BITS = 53
12
+ MIN_LEN = 1
13
+ MAX_LEN = 50
14
+ STATE_SPACE = 1 << MANTISSA_BITS
15
+
16
+ LEFT_BITS = 26
17
+ RIGHT_BITS = 27 # 26 + 27 = 53 bits
18
+ LEFT_MASK = (1 << LEFT_BITS) - 1
19
+ RIGHT_MASK = (1 << RIGHT_BITS) - 1
20
+ FEISTEL_ROUNDS = 8
21
+
22
+ MIN_SALT_BYTES = 16
23
+ DEFAULT_SALT_BYTES = 32
24
+
25
+ SaltType = str | bytes | bytearray
26
+
27
+
28
+ def _build_partition_tables() -> tuple[dict[int, int], dict[int, int], dict[int, int]]:
29
+ """Build exact partition tables splitting ``2^53`` states across ``L = 1..50``."""
30
+ nonce_counts: dict[int, int] = {}
31
+ remaining = STATE_SPACE
32
+
33
+ for length in range(MAX_LEN, 1, -1):
34
+ unit = 1 << length
35
+ count = max(3, remaining // (4 * unit))
36
+ nonce_counts[length] = count
37
+ remaining -= count * unit
38
+
39
+ # Remaining budget at L = 1 is guaranteed even and absorbed completely.
40
+ if remaining <= 0 or remaining % 2 != 0:
41
+ raise RuntimeError("53-bit partition integrity check failed at L=1.")
42
+ nonce_counts[1] = remaining // 2
43
+
44
+ bases: dict[int, int] = {}
45
+ sizes: dict[int, int] = {}
46
+ cursor = 0
47
+ for length in range(MIN_LEN, MAX_LEN + 1):
48
+ size = nonce_counts[length] << length
49
+ bases[length] = cursor
50
+ sizes[length] = size
51
+ cursor += size
52
+
53
+ if cursor != STATE_SPACE:
54
+ raise RuntimeError("53-bit partition does not sum to 2^53.")
55
+
56
+ return nonce_counts, bases, sizes
57
+
58
+
59
+ NONCE_COUNTS, BASES, SIZES = _build_partition_tables()
60
+ _BASE_LIST: tuple[int, ...] = tuple(BASES[length] for length in range(MIN_LEN, MAX_LEN + 1))
61
+
62
+
63
+ def _normalize_salt(salt: SaltType) -> bytes:
64
+ """Validate and normalize a hex string, UTF-8 passphrase, or raw byte key."""
65
+ if isinstance(salt, (bytes, bytearray)):
66
+ key = bytes(salt)
67
+ if not key:
68
+ raise ValueError("Salt must not be empty.")
69
+ return key
70
+ if not isinstance(salt, str):
71
+ raise TypeError(f"Salt must be str or bytes, got {type(salt).__name__}.")
72
+
73
+ cleaned = salt.strip()
74
+ if not cleaned:
75
+ raise ValueError("Salt must not be empty.")
76
+
77
+ try:
78
+ decoded = bytes.fromhex(cleaned)
79
+ except ValueError:
80
+ return cleaned.encode("utf-8")
81
+
82
+ if not decoded:
83
+ raise ValueError("Salt must not be empty.")
84
+ return decoded
85
+
86
+
87
+ def _coerce_bits(bits: Iterable[bool], *, max_items: int | None = None) -> list[bool]:
88
+ """Convert an iterable of bool or 0/1 ints to ``list[bool]`` safely."""
89
+ if isinstance(bits, (str, bytes, bytearray, memoryview, Mapping)):
90
+ raise TypeError(
91
+ "bits must be a sequence or iterable of booleans (not str, bytes, or mapping); "
92
+ "use parse_bits() to parse a bit string."
93
+ )
94
+
95
+ result: list[bool] = []
96
+ for item in bits:
97
+ if max_items is not None and len(result) >= max_items:
98
+ raise ValueError(
99
+ f"Array length must be between {MIN_LEN} and {MAX_LEN} elements."
100
+ )
101
+ if isinstance(item, bool):
102
+ result.append(item)
103
+ elif isinstance(item, int):
104
+ if item not in (0, 1):
105
+ raise ValueError(f"Integer bit elements must be 0 or 1, got {item!r}.")
106
+ result.append(bool(item))
107
+ elif type(item).__name__ == "bool_" and hasattr(item, "__bool__"):
108
+ # Support numpy.bool_ without taking a runtime dependency on numpy.
109
+ result.append(bool(item))
110
+ else:
111
+ raise TypeError(
112
+ f"Bit elements must be bool (or 0/1 int), got {type(item).__name__}."
113
+ )
114
+ return result
115
+
116
+
117
+ def _prf(key_bytes: bytes, round_idx: int, half_val: int) -> int:
118
+ """Compute a 32-bit keyed round output via HMAC-SHA256."""
119
+ msg = round_idx.to_bytes(1, "big") + half_val.to_bytes(4, "big")
120
+ digest = hmac.digest(key_bytes, msg, "sha256")
121
+ return int.from_bytes(digest[:4], "big")
122
+
123
+
124
+ def _feistel_encrypt_53(value: int, key_bytes: bytes) -> int:
125
+ """Bijective 53-bit encryption via an 8-round unbalanced Feistel network (26 + 27)."""
126
+ left = (value >> RIGHT_BITS) & LEFT_MASK
127
+ right = value & RIGHT_MASK
128
+ for r in range(FEISTEL_ROUNDS):
129
+ if r % 2 == 0:
130
+ left ^= _prf(key_bytes, r, right) & LEFT_MASK
131
+ else:
132
+ right ^= _prf(key_bytes, r, left) & RIGHT_MASK
133
+ return (left << RIGHT_BITS) | right
134
+
135
+
136
+ def _feistel_decrypt_53(value: int, key_bytes: bytes) -> int:
137
+ """Inverse 8-round unbalanced Feistel permutation over 53-bit integers."""
138
+ left = (value >> RIGHT_BITS) & LEFT_MASK
139
+ right = value & RIGHT_MASK
140
+ for r in reversed(range(FEISTEL_ROUNDS)):
141
+ if r % 2 == 0:
142
+ left ^= _prf(key_bytes, r, right) & LEFT_MASK
143
+ else:
144
+ right ^= _prf(key_bytes, r, left) & RIGHT_MASK
145
+ return (left << RIGHT_BITS) | right
146
+
147
+
148
+ def _encrypt_with_key(bits: Iterable[bool], key_bytes: bytes) -> float:
149
+ bools = _coerce_bits(bits, max_items=MAX_LEN)
150
+ length = len(bools)
151
+ if not (MIN_LEN <= length <= MAX_LEN):
152
+ raise ValueError(
153
+ f"Array length must be between {MIN_LEN} and {MAX_LEN} elements, got {length}."
154
+ )
155
+
156
+ data_int = 0
157
+ for idx, bit in enumerate(bools):
158
+ if bit:
159
+ data_int |= 1 << idx
160
+
161
+ nonce = secrets.randbelow(NONCE_COUNTS[length])
162
+ plain_53 = BASES[length] + (nonce << length) + data_int
163
+ cipher_53 = _feistel_encrypt_53(plain_53, key_bytes)
164
+ return math.ldexp(cipher_53, -MANTISSA_BITS)
165
+
166
+
167
+ def _decrypt_with_key(double_val: float, key_bytes: bytes) -> list[bool]:
168
+ if isinstance(double_val, bool) or not isinstance(double_val, float):
169
+ raise TypeError("Expected a float (IEEE 754 binary64 double).")
170
+ if not math.isfinite(double_val) or not (0.0 <= double_val < 1.0):
171
+ raise ValueError("Double value must be finite and in the half-open interval [0.0, 1.0).")
172
+
173
+ scaled = math.ldexp(double_val, MANTISSA_BITS)
174
+ if not scaled.is_integer():
175
+ raise ValueError("Double value does not lie on the exact 53-bit IEEE 754 grid.")
176
+
177
+ cipher_53 = int(scaled)
178
+ plain_53 = _feistel_decrypt_53(cipher_53, key_bytes)
179
+
180
+ length = bisect_right(_BASE_LIST, plain_53)
181
+ base = BASES[length]
182
+ if not (base <= plain_53 < base + SIZES[length]):
183
+ raise ValueError("Failed to decode 53-bit state.")
184
+
185
+ offset = plain_53 - base
186
+ data_int = offset & ((1 << length) - 1)
187
+ return [((data_int >> idx) & 1) == 1 for idx in range(length)]
188
+
189
+
190
+ def generate_salt(num_bytes: int = DEFAULT_SALT_BYTES) -> str:
191
+ """Generate a cryptographically secure hex-encoded salt (default 32 bytes / 256 bits)."""
192
+ if isinstance(num_bytes, bool) or not isinstance(num_bytes, int):
193
+ raise TypeError(f"num_bytes must be int, got {type(num_bytes).__name__}.")
194
+ if num_bytes < MIN_SALT_BYTES:
195
+ raise ValueError(
196
+ f"Salt size must be at least {MIN_SALT_BYTES} bytes (128 bits), got {num_bytes}."
197
+ )
198
+ return secrets.token_hex(num_bytes)
199
+
200
+
201
+ def parse_bits(raw: str) -> list[bool]:
202
+ """Parse a bit string (e.g. ``'1011001'``) or comma-separated booleans into ``list[bool]``."""
203
+ if not isinstance(raw, str):
204
+ raise TypeError(f"Expected str, got {type(raw).__name__}.")
205
+
206
+ cleaned = raw.strip()
207
+ if not cleaned:
208
+ raise ValueError("Bit string must not be empty.")
209
+
210
+ if all(ch in "01" for ch in cleaned):
211
+ return [ch == "1" for ch in cleaned]
212
+
213
+ tokens = [token.strip().lower() for token in cleaned.split(",") if token.strip()]
214
+ if not tokens:
215
+ raise ValueError("Bit string must not be empty.")
216
+
217
+ result: list[bool] = []
218
+ for token in tokens:
219
+ if token in ("1", "true", "t"):
220
+ result.append(True)
221
+ elif token in ("0", "false", "f"):
222
+ result.append(False)
223
+ else:
224
+ raise ValueError(f"Unrecognized boolean token: {token!r}.")
225
+ return result
226
+
227
+
228
+ def format_bits(bits: Iterable[bool]) -> str:
229
+ """Format an iterable of booleans as a ``'0'``/``'1'`` bit string."""
230
+ return "".join("1" if bit else "0" for bit in _coerce_bits(bits))
231
+
232
+
233
+ def encrypt_bool_array(bits: Iterable[bool], salt: SaltType) -> float:
234
+ """Encrypt 1..50 booleans with hidden length and random nonce into [0.0, 1.0)."""
235
+ key_bytes = _normalize_salt(salt)
236
+ return _encrypt_with_key(bits, key_bytes)
237
+
238
+
239
+ def decrypt_bool_array(double_val: float, salt: SaltType) -> list[bool]:
240
+ """Recover the original boolean list and its hidden length from a double and salt."""
241
+ key_bytes = _normalize_salt(salt)
242
+ return _decrypt_with_key(double_val, key_bytes)
243
+
244
+
245
+ def encrypt(bits: Iterable[bool], salt: SaltType) -> float:
246
+ """Alias for :func:`encrypt_bool_array`."""
247
+ return encrypt_bool_array(bits, salt)
248
+
249
+
250
+ def decrypt(double_val: float, salt: SaltType) -> list[bool]:
251
+ """Alias for :func:`decrypt_bool_array`."""
252
+ return decrypt_bool_array(double_val, salt)
253
+
254
+
255
+ class B53Cipher:
256
+ """Reusable cipher bound to a normalized secret salt."""
257
+
258
+ def __init__(self, salt: SaltType) -> None:
259
+ self._key_bytes = _normalize_salt(salt)
260
+
261
+ def __repr__(self) -> str:
262
+ return f"{type(self).__name__}(key_bytes={len(self._key_bytes)})"
263
+
264
+ @classmethod
265
+ def generate(cls, num_bytes: int = DEFAULT_SALT_BYTES) -> tuple[B53Cipher, str]:
266
+ """Generate a new random salt and return ``(cipher, salt_hex)``."""
267
+ salt = generate_salt(num_bytes)
268
+ return cls(salt), salt
269
+
270
+ def encrypt(self, bits: Iterable[bool]) -> float:
271
+ """Encrypt 1..50 booleans into a double in ``[0.0, 1.0)``."""
272
+ return _encrypt_with_key(bits, self._key_bytes)
273
+
274
+ def decrypt(self, double_val: float) -> list[bool]:
275
+ """Decrypt a double in ``[0.0, 1.0)`` back into the original ``list[bool]``."""
276
+ return _decrypt_with_key(double_val, self._key_bytes)
277
+
278
+ def encrypt_str(self, raw_bits: str) -> float:
279
+ """Parse a bit string (e.g. ``'10110'``) and encrypt it."""
280
+ return self.encrypt(parse_bits(raw_bits))
281
+
282
+ def decrypt_str(self, double_val: float) -> str:
283
+ """Decrypt a double and format the result as a ``'0'``/``'1'`` bit string."""
284
+ return format_bits(self.decrypt(double_val))
285
+
286
+
287
+ Cipher = B53Cipher
b53/py.typed ADDED
File without changes
@@ -0,0 +1,158 @@
1
+ Metadata-Version: 2.5
2
+ Name: b53
3
+ Version: 0.1.0
4
+ Summary: Reversible 53-bit cryptographic packing of 1-50 booleans with hidden length and random nonce into an IEEE 754 double in [0.0, 1.0)
5
+ Project-URL: Homepage, https://github.com/1orgar/b53
6
+ Project-URL: Repository, https://github.com/1orgar/b53
7
+ Project-URL: Issues, https://github.com/1orgar/b53/issues
8
+ Author: 1orgar
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: bit-packing,boolean,cipher,double,encryption,feistel,format-preserving,hmac-sha256,ieee754
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Programming Language :: Python :: 3.14
23
+ Classifier: Topic :: Security :: Cryptography
24
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
25
+ Classifier: Typing :: Typed
26
+ Requires-Python: >=3.10
27
+ Provides-Extra: dev
28
+ Requires-Dist: build>=1.2; extra == 'dev'
29
+ Requires-Dist: mypy>=1.11; extra == 'dev'
30
+ Requires-Dist: pytest>=8.0; extra == 'dev'
31
+ Requires-Dist: ruff>=0.8; extra == 'dev'
32
+ Requires-Dist: twine>=6.1; extra == 'dev'
33
+ Description-Content-Type: text/markdown
34
+
35
+ # b53
36
+
37
+ **English** | [🇷🇺 Русская версия](README_RU.md)
38
+
39
+ [![PyPI version](https://img.shields.io/pypi/v/b53.svg)](https://pypi.org/project/b53/)
40
+ [![Python versions](https://img.shields.io/pypi/pyversions/b53.svg)](https://pypi.org/project/b53/)
41
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
42
+ [![CI](https://github.com/1orgar/b53/actions/workflows/ci.yml/badge.svg)](https://github.com/1orgar/b53/actions/workflows/ci.yml)
43
+
44
+ **`b53`** is a zero-dependency Python library for reversible cryptographic packing of boolean arrays of arbitrary length $L \in [1, 50]$ into a single standard IEEE 754 `binary64` (`double` / Python `float`) in the half-open interval $[0.0, 1.0)$.
45
+
46
+ ## Key Properties
47
+
48
+ - **Hidden length inside the float:** the original array length $L \in [1, 50]$ is encoded directly inside the 53-bit mantissa space—no external length metadata is required.
49
+ - **Randomized output (nonce) per encryption:** encrypting the same boolean array with the same salt produces different pseudorandom doubles in $[0.0, 1.0)$.
50
+ - **Bijective 53-bit permutation:** uses an 8-round unbalanced Feistel network ($26 + 27 = 53$ bits) keyed by `HMAC-SHA256` with your secret salt.
51
+ - **Pure Python standard library:** zero runtime dependencies, typed (`py.typed`), Python 3.10+.
52
+
53
+ ## Installation
54
+
55
+ ```bash
56
+ pip install b53
57
+ ```
58
+
59
+ ## Quick Start
60
+
61
+ ### Python API
62
+
63
+ ```python
64
+ import b53
65
+
66
+ # 1. Generate a 256-bit secret salt (store securely)
67
+ salt = b53.generate_salt()
68
+
69
+ # 2. Encrypt a boolean array (1..50 elements) into a float in [0.0, 1.0)
70
+ bits = [True, False, True, True, False, False, True, False, True, True]
71
+ x1 = b53.encrypt(bits, salt)
72
+ x2 = b53.encrypt(bits, salt) # different float due to random nonce
73
+ assert x1 != x2
74
+
75
+ # 3. Decrypt back to the exact original list[bool] and length
76
+ assert b53.decrypt(x1, salt) == bits
77
+ assert b53.decrypt(x2, salt) == bits
78
+ ```
79
+
80
+ For repeated operations with the same salt, use `B53Cipher` (alias `Cipher`):
81
+
82
+ ```python
83
+ from b53 import B53Cipher
84
+
85
+ cipher = B53Cipher(salt)
86
+ encoded = cipher.encrypt_str("1011001011")
87
+ print(repr(encoded))
88
+ print(cipher.decrypt_str(encoded)) # "1011001011"
89
+ ```
90
+
91
+ ### Command-Line Interface
92
+
93
+ ```bash
94
+ # 1. Generate a 256-bit hex salt
95
+ SALT=$(b53 generate-salt)
96
+
97
+ # 2. Encrypt the same bit string 3 times
98
+ b53 encrypt 1011001011 --salt "$SALT" --count 3
99
+
100
+ # 3. Decrypt any generated double back to the original array
101
+ b53 decrypt 0.7419283058129402 --salt "$SALT"
102
+ ```
103
+
104
+ You can also run via `python -m b53 ...`, pass `--salt-file path/to/salt`, or set the `B53_SALT` environment variable.
105
+
106
+ ## How It Works
107
+
108
+ An IEEE 754 `binary64` float on the uniform $2^{-53}$ grid represents $x = C \cdot 2^{-53}$ for $C \in \{0, 1, \dots, 2^{53} - 1\}$.
109
+
110
+ The entire 53-bit state space ($2^{53} = 9\,007\,199\,254\,740\,992$ states) is partitioned without gaps or overlaps across all 50 lengths $L \in [1, 50]$ so that:
111
+
112
+ $$\sum_{L=1}^{50} M_L \cdot 2^L = 2^{53}$$
113
+
114
+ Space is allocated top-down from $L = 50$ to $L = 1$, reserving $\approx 25\%$ of the remaining budget at each step (at least $M_L \ge 3$ nonces even at $L = 50$):
115
+
116
+ | Length $L$ | Data combinations ($2^L$) | Nonces per array ($M_L$) | Segment size ($M_L \cdot 2^L$) |
117
+ |---:|---:|---:|---:|
118
+ | 50 | $2^{50}$ | 3 | $3 \times 2^{50}$ |
119
+ | 49 | $2^{49}$ | 3 | $3 \times 2^{49}$ |
120
+ | 48 | $2^{48}$ | 3 | $3 \times 2^{48}$ |
121
+ | 47 | $2^{47}$ | 5 | $5 \times 2^{47}$ |
122
+ | 45 | $2^{45}$ | 13 | $13 \times 2^{45}$ |
123
+ | 40 | $2^{40}$ | 100 | $100 \times 2^{40}$ |
124
+ | 30 | $2^{30}$ | 5,811 | $5{,}811 \times 2^{30}$ |
125
+ | 20 | $2^{20}$ | 335,103 | $335{,}103 \times 2^{20}$ |
126
+ | 10 | $2^{10}$ | 19,323,738 | $\approx 1.98 \times 10^{10}$ |
127
+ | 1 | $2^1$ | 2,971,477,630 | $\approx 5.94 \times 10^{9}$ |
128
+
129
+ 1. **Pack:** encode `bits` as $D \in [0, 2^L - 1]$, pick $r \in [0, M_L - 1]$ via `secrets.randbelow`, and compute $P = \text{BASE}[L] + r \cdot 2^L + D$.
130
+ 2. **Permute:** apply an 8-round unbalanced Feistel network ($26 + 27$ bits) with `HMAC-SHA256` keyed by the normalized salt to obtain $C \in [0, 2^{53} - 1]$.
131
+ 3. **Float conversion:** return `math.ldexp(C, -53)` ($C \cdot 2^{-53}$).
132
+ 4. **Decrypt:** verify $x \in [0.0, 1.0)$ lies exactly on the $2^{-53}$ grid, invert the Feistel permutation to recover $P$, find the unique range $L$, discard $r$, and unpack the lower $L$ bits of $P - \text{BASE}[L]$.
133
+
134
+ ## Precision Requirements
135
+
136
+ When serializing the encrypted `double` to text, JSON, CSV, or CLI arguments, always preserve all significant binary64 digits using `repr(x)` / `f"{x:.17g}"` (or native `DOUBLE PRECISION` / `FLOAT8` in databases). Rounding even the least significant digit alters the lower bits of the 53-bit ciphertext and breaks decryption.
137
+
138
+ ## API Reference
139
+
140
+ - `generate_salt(num_bytes: int = 32) -> str` — generate a cryptographically random hex salt ($\ge 16$ bytes).
141
+ - `encrypt(bits, salt) -> float` / `encrypt_bool_array(bits, salt) -> float` — encrypt $1..50$ booleans (or `0`/`1` ints) into a double in $[0.0, 1.0)$.
142
+ - `decrypt(double_val, salt) -> list[bool]` / `decrypt_bool_array(double_val, salt) -> list[bool]` — recover the exact boolean list and length.
143
+ - `parse_bits(raw: str) -> list[bool]` — parse `"10110"` or `"true,false,1,0"`.
144
+ - `format_bits(bits) -> str` — format booleans as `"10110"`.
145
+ - `B53Cipher(salt)` (alias `Cipher`) — reusable cipher object with `.encrypt()`, `.decrypt()`, `.encrypt_str()`, `.decrypt_str()`, and `B53Cipher.generate()`.
146
+
147
+ ## Development
148
+
149
+ ```bash
150
+ pip install -e ".[dev]"
151
+ pytest
152
+ ruff check src tests
153
+ mypy src
154
+ ```
155
+
156
+ ## License
157
+
158
+ [MIT](LICENSE)
@@ -0,0 +1,10 @@
1
+ b53/__init__.py,sha256=y3S-o2-gD2de5ZvRVMYKMjR36CKIe3Sqg5Iy3q6M7Ak,952
2
+ b53/__main__.py,sha256=Ps4Nh7deqY5aFmiUniEa4maixlmPhma28mNeiTIf3hQ,160
3
+ b53/cli.py,sha256=iH0TbX_I1Qn-2qpziqkGQTA0JuKGa4I_IV-hVSfTc0Q,5235
4
+ b53/core.py,sha256=VeSDtCGswADEwuZd2eE0PtsoVyzqj9X366X4AWkSH_I,10294
5
+ b53/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ b53-0.1.0.dist-info/METADATA,sha256=hFh9VnRB7PwFy3fQq1_9nJ8B3-ZfZyImSTVnCPxZ8hI,7065
7
+ b53-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
8
+ b53-0.1.0.dist-info/entry_points.txt,sha256=I_qKBWtD8wdMJPfLjlZFmAYgnQ_jL_QAVh1KMtUcJjM,37
9
+ b53-0.1.0.dist-info/licenses/LICENSE,sha256=kEra6OKxz7swdhkWkboX8tZmRdvKtnY2Q6-pWy49-W8,1063
10
+ b53-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ b53 = b53.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 1orgar
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.