swarmauri_mre_crypto_shamir 0.2.0.dev3__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.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [2025] [Jacob Stewart @ Swarmauri]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,43 @@
1
+ Metadata-Version: 2.3
2
+ Name: swarmauri_mre_crypto_shamir
3
+ Version: 0.2.0.dev3
4
+ Summary: Shamir secret sharing based MRE crypto provider for Swarmauri
5
+ License: Apache-2.0
6
+ Author: Swarmauri
7
+ Author-email: opensource@swarmauri.com
8
+ Requires-Python: >=3.10,<3.13
9
+ Classifier: License :: OSI Approved :: Apache Software License
10
+ Classifier: Natural Language :: English
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Development Status :: 3 - Alpha
16
+ Classifier: Topic :: Security :: Cryptography
17
+ Classifier: Intended Audience :: Developers
18
+ Provides-Extra: cbor
19
+ Requires-Dist: cbor2 ; extra == "cbor"
20
+ Requires-Dist: cryptography
21
+ Requires-Dist: swarmauri_base
22
+ Requires-Dist: swarmauri_core
23
+ Description-Content-Type: text/markdown
24
+
25
+ # swarmauri_mre_crypto_shamir
26
+
27
+ Shamir Secret Sharing based multi-recipient encryption (MRE) provider for the Swarmauri framework. The provider splits an AES-256-GCM content encryption key using Shamir's threshold scheme and distributes shares to recipients.
28
+
29
+ ## Features
30
+ - AES-256-GCM payload encryption
31
+ - Threshold k-of-n key sharing via Shamir secret sharing
32
+ - Envelope rewrapping with optional payload rotation
33
+
34
+ ## Extras
35
+ The plugin supports optional canonicalization extras:
36
+ - `cbor` – enables CBOR canonicalization via `cbor2`
37
+
38
+ ## Installation
39
+ This package is part of the Swarmauri standards collection and is typically installed as part of the `swarmauri-sdk` workspace.
40
+
41
+ ## License
42
+ Apache-2.0
43
+
@@ -0,0 +1,18 @@
1
+ # swarmauri_mre_crypto_shamir
2
+
3
+ Shamir Secret Sharing based multi-recipient encryption (MRE) provider for the Swarmauri framework. The provider splits an AES-256-GCM content encryption key using Shamir's threshold scheme and distributes shares to recipients.
4
+
5
+ ## Features
6
+ - AES-256-GCM payload encryption
7
+ - Threshold k-of-n key sharing via Shamir secret sharing
8
+ - Envelope rewrapping with optional payload rotation
9
+
10
+ ## Extras
11
+ The plugin supports optional canonicalization extras:
12
+ - `cbor` – enables CBOR canonicalization via `cbor2`
13
+
14
+ ## Installation
15
+ This package is part of the Swarmauri standards collection and is typically installed as part of the `swarmauri-sdk` workspace.
16
+
17
+ ## License
18
+ Apache-2.0
@@ -0,0 +1,70 @@
1
+ [project]
2
+ name = "swarmauri_mre_crypto_shamir"
3
+ version = "0.2.0.dev3"
4
+ description = "Shamir secret sharing based MRE crypto provider for Swarmauri"
5
+ license = "Apache-2.0"
6
+ readme = "README.md"
7
+ requires-python = ">=3.10,<3.13"
8
+ authors = [{ name = "Swarmauri", email = "opensource@swarmauri.com" }]
9
+ classifiers = [
10
+ "License :: OSI Approved :: Apache Software License",
11
+ "Natural Language :: English",
12
+ "Programming Language :: Python :: 3.10",
13
+ "Programming Language :: Python :: 3.11",
14
+ "Programming Language :: Python :: 3.12",
15
+ "Programming Language :: Python :: 3.13",
16
+ "Development Status :: 3 - Alpha",
17
+ "Topic :: Security :: Cryptography",
18
+ "Intended Audience :: Developers",
19
+ ]
20
+ dependencies = [
21
+ "swarmauri_core",
22
+ "swarmauri_base",
23
+ "cryptography",
24
+ ]
25
+
26
+ [project.optional-dependencies]
27
+ cbor = ["cbor2"]
28
+
29
+ [tool.uv.sources]
30
+ swarmauri_core = { workspace = true }
31
+ swarmauri_base = { workspace = true }
32
+
33
+ [tool.pytest.ini_options]
34
+ norecursedirs = ["combined", "scripts"]
35
+ markers = [
36
+ "test: standard test",
37
+ "unit: Unit tests",
38
+ "i9n: Integration tests",
39
+ "r8n: Regression tests",
40
+ "acceptance: Acceptance tests",
41
+ "perf: Performance tests",
42
+ ]
43
+ timeout = 300
44
+ log_cli = true
45
+ log_cli_level = "INFO"
46
+ log_cli_format = "%(asctime)s [%(levelname)s] %(message)s"
47
+ log_cli_date_format = "%Y-%m-%d %H:%M:%S"
48
+ asyncio_default_fixture_loop_scope = "function"
49
+
50
+ [dependency-groups]
51
+ dev = [
52
+ "pytest>=8.0",
53
+ "pytest-asyncio>=0.24.0",
54
+ "pytest-xdist>=3.6.1",
55
+ "pytest-json-report>=1.5.0",
56
+ "pytest-timeout>=2.3.1",
57
+ "pytest-benchmark>=4.0.0",
58
+ "flake8>=7.0",
59
+ "ruff>=0.9.9",
60
+ ]
61
+
62
+ [build-system]
63
+ requires = ["poetry-core>=1.0.0"]
64
+ build-backend = "poetry.core.masonry.api"
65
+
66
+ [project.entry-points.'swarmauri.mre_cryptos']
67
+ ShamirMreCrypto = "swarmauri_mre_crypto_shamir:ShamirMreCrypto"
68
+
69
+ [project.entry-points."peagen.plugins.mre_cryptos"]
70
+ shamir = "swarmauri_mre_crypto_shamir:ShamirMreCrypto"
@@ -0,0 +1,510 @@
1
+ """Shamir-based Multi-Recipient Encryption provider."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import json
7
+ import hashlib
8
+ from typing import Any, Dict, Iterable, Mapping, Optional, Sequence, Tuple, List, Union
9
+
10
+ from cryptography.hazmat.primitives.ciphers.aead import AESGCM
11
+ from swarmauri_core.crypto.types import Alg, KeyRef
12
+ from swarmauri_core.mre_crypto.types import MultiRecipientEnvelope, RecipientId
13
+ from swarmauri_base.mre_crypto.MreCryptoBase import MreCryptoBase
14
+ from swarmauri_base.ComponentBase import ComponentBase
15
+
16
+
17
+ # ======================== Field and envelope constants ========================
18
+
19
+ # Prime field for Shamir (Mersenne prime > 2^521)
20
+ _P = (1 << 521) - 1
21
+ _ZERO = 0
22
+ _ONE = 1
23
+
24
+ # CEK size for AES-256-GCM
25
+ _CEK_LEN = 32
26
+ _NONCE_LEN = 12
27
+ _TAG_LEN = 16
28
+
29
+ # Envelope tokens
30
+ _MODE = "sealed_cek+aead"
31
+ _RECIP_ALG = "SHAMIR-KOFN"
32
+ _PAYLOAD_AEAD_DEFAULT = "AES-256-GCM"
33
+
34
+ # Header (per-recipient share) binary format
35
+ _HDR_MAGIC = b"SHAMIR-KOFN\x00"
36
+ _HDR_VER = b"\x01"
37
+
38
+
39
+ # ================================ utils ======================================
40
+
41
+
42
+ def _int_to_bytes(x: int) -> bytes:
43
+ if x == 0:
44
+ return b"\x00"
45
+ length = (x.bit_length() + 7) // 8
46
+ return x.to_bytes(length, "big")
47
+
48
+
49
+ def _bytes_to_int(b: bytes) -> int:
50
+ return int.from_bytes(b, "big")
51
+
52
+
53
+ def _mod_inv(a: int, p: int) -> int:
54
+ # Modular inverse via Fermat's little theorem; p is prime
55
+ if a % p == 0:
56
+ raise ZeroDivisionError("division by zero in modular inverse")
57
+ return pow(a, p - 2, p)
58
+
59
+
60
+ def _poly_eval_at(x: int, coeffs: Sequence[int], p: int = _P) -> int:
61
+ """
62
+ Evaluate polynomial a0 + a1*x + a2*x^2 + ... at x (mod p).
63
+ coeffs[0] is the secret (a0).
64
+ """
65
+ acc = 0
66
+ power = 1
67
+ for a in coeffs:
68
+ acc = (acc + (a * power)) % p
69
+ power = (power * x) % p
70
+ return acc
71
+
72
+
73
+ def _lagrange_interpolate_at(
74
+ x: int, points: Sequence[Tuple[int, int]], p: int = _P
75
+ ) -> int:
76
+ """
77
+ Compute f(x) from k points (x_i, y_i) on a degree-(k-1) polynomial over GF(p).
78
+ Works for x == 0 (reconstruct secret) or any other x (evaluate at new x).
79
+ """
80
+ k = len(points)
81
+ xs = [xi for (xi, _) in points]
82
+ ys = [yi for (_, yi) in points]
83
+ total = 0
84
+ for i in range(k):
85
+ xi, yi = xs[i], ys[i]
86
+ num = 1
87
+ den = 1
88
+ for j in range(k):
89
+ if i == j:
90
+ continue
91
+ xj = xs[j]
92
+ num = (num * (x - xj)) % p
93
+ den = (den * (xi - xj)) % p
94
+ li = (num * _mod_inv(den % p, p)) % p
95
+ total = (total + (yi * li)) % p
96
+ return total
97
+
98
+
99
+ def _encode_share(x: int, y: int) -> bytes:
100
+ xb = _int_to_bytes(x)
101
+ yb = _int_to_bytes(y)
102
+ return b"".join(
103
+ [
104
+ _HDR_MAGIC,
105
+ _HDR_VER,
106
+ len(xb).to_bytes(2, "big"),
107
+ xb,
108
+ len(yb).to_bytes(2, "big"),
109
+ yb,
110
+ ]
111
+ )
112
+
113
+
114
+ def _decode_share(b: bytes) -> Tuple[int, int]:
115
+ if not b.startswith(_HDR_MAGIC):
116
+ raise ValueError("Malformed Shamir header (magic).")
117
+ off = len(_HDR_MAGIC)
118
+ ver = b[off : off + 1]
119
+ off += 1
120
+ if ver != _HDR_VER:
121
+ raise ValueError("Unsupported Shamir header version.")
122
+ xlen = int.from_bytes(b[off : off + 2], "big")
123
+ off += 2
124
+ xb = b[off : off + xlen]
125
+ off += xlen
126
+ ylen = int.from_bytes(b[off : off + 2], "big")
127
+ off += 2
128
+ yb = b[off : off + ylen]
129
+ if len(xb) != xlen or len(yb) != ylen:
130
+ raise ValueError("Malformed Shamir header (length).")
131
+ return (_bytes_to_int(xb), _bytes_to_int(yb))
132
+
133
+
134
+ def _sha256(data: bytes) -> bytes:
135
+ return hashlib.sha256(data).digest()
136
+
137
+
138
+ def _stable_recipient_id(ref: KeyRef) -> str:
139
+ """
140
+ Produce a stable recipient id from a KeyRef without assuming key type.
141
+ Preference:
142
+ - explicit 'kid' or 'id' in dict
143
+ - raw public bytes if available
144
+ - canonicalized JSON of the dict
145
+ - repr fallback
146
+ """
147
+ if isinstance(ref, dict):
148
+ if "kid" in ref and isinstance(ref["kid"], (str, bytes)):
149
+ v = ref["kid"]
150
+ if isinstance(v, bytes):
151
+ v = v.decode("utf-8", "ignore")
152
+ return v
153
+ if "id" in ref and isinstance(ref["id"], (str, bytes)):
154
+ v = ref["id"]
155
+ if isinstance(v, bytes):
156
+ v = v.decode("utf-8", "ignore")
157
+ return v
158
+ obj = ref.get("obj")
159
+ if hasattr(obj, "public_bytes"):
160
+ try:
161
+ pb = obj.public_bytes(encoding=None, format=None) # type: ignore[arg-type]
162
+ return hashlib.sha256(pb).hexdigest()
163
+ except Exception:
164
+ pass
165
+ try:
166
+ canon = json.dumps(
167
+ ref, sort_keys=True, separators=(",", ":"), default=str
168
+ ).encode("utf-8")
169
+ except Exception:
170
+ canon = repr(ref).encode("utf-8")
171
+ return hashlib.sha256(canon).hexdigest()
172
+ return hashlib.sha256(repr(ref).encode("utf-8")).hexdigest()
173
+
174
+
175
+ def _x_from_recipient_id(rid: str, used: set[int]) -> int:
176
+ base = (
177
+ int.from_bytes(_sha256(("SHAMIR-X|" + rid).encode("utf-8")), "big") % (_P - 1)
178
+ ) + 1
179
+ x = base
180
+ while x in used:
181
+ x = (x + 1) % _P
182
+ if x == 0:
183
+ x = 1
184
+ used.add(x)
185
+ return x
186
+
187
+
188
+ def _aes_gcm_encrypt(
189
+ cek: bytes, pt: bytes, aad: Optional[bytes]
190
+ ) -> Tuple[bytes, bytes, bytes]:
191
+ nonce = os.urandom(_NONCE_LEN)
192
+ enc = AESGCM(cek).encrypt(nonce, pt, aad)
193
+ ct, tag = enc[:-_TAG_LEN], enc[-_TAG_LEN:]
194
+ return nonce, ct, tag
195
+
196
+
197
+ def _aes_gcm_decrypt(
198
+ cek: bytes, nonce: bytes, ct: bytes, tag: bytes, aad: Optional[bytes]
199
+ ) -> bytes:
200
+ return AESGCM(cek).decrypt(nonce, ct + tag, aad)
201
+
202
+
203
+ # ============================== implementation ===============================
204
+
205
+
206
+ @ComponentBase.register_type(MreCryptoBase, "ShamirMreCrypto")
207
+ class ShamirMreCrypto(MreCryptoBase):
208
+ """Shamir secret sharing based MRE crypto provider."""
209
+
210
+ type: str = "ShamirMreCrypto"
211
+
212
+ def supports(self) -> Dict[str, Iterable[str]]:
213
+ return {
214
+ "payload": (_PAYLOAD_AEAD_DEFAULT,),
215
+ "recipient": (_RECIP_ALG,),
216
+ "modes": (_MODE,),
217
+ "features": ("aad", "threshold", "rewrap_without_reencrypt"),
218
+ }
219
+
220
+ # ----------------------------- encrypt_for_many -----------------------------
221
+ async def encrypt_for_many(
222
+ self,
223
+ recipients: Sequence[KeyRef],
224
+ pt: bytes,
225
+ *,
226
+ payload_alg: Optional[Alg] = None,
227
+ recipient_alg: Optional[Alg] = None,
228
+ mode: Optional[Union[str, Any]] = None,
229
+ aad: Optional[bytes] = None,
230
+ shared: Optional[Mapping[str, bytes]] = None,
231
+ opts: Optional[Mapping[str, object]] = None,
232
+ ) -> MultiRecipientEnvelope:
233
+ m = str(mode or _MODE)
234
+ if m != _MODE:
235
+ raise ValueError("ShamirMreCrypto supports only mode='sealed_cek+aead'.")
236
+ if recipient_alg not in (None, _RECIP_ALG):
237
+ raise ValueError(
238
+ "ShamirMreCrypto supports only recipient_alg='SHAMIR-KOFN'."
239
+ )
240
+ palg = str(payload_alg or _PAYLOAD_AEAD_DEFAULT)
241
+ if palg != _PAYLOAD_AEAD_DEFAULT:
242
+ raise ValueError("ShamirMreCrypto supports only AES-256-GCM for now.")
243
+ if not recipients:
244
+ raise ValueError("At least one recipient is required.")
245
+ n = len(recipients)
246
+ k = int((opts or {}).get("threshold_k", (n // 2) + 1))
247
+ k = max(1, min(k, n))
248
+ cek = os.urandom(_CEK_LEN)
249
+ nonce, ct, tag = _aes_gcm_encrypt(cek, pt, aad)
250
+ secret = _bytes_to_int(cek)
251
+ coeffs = [secret] + [
252
+ int.from_bytes(os.urandom(64), "big") % _P for _ in range(max(0, k - 1))
253
+ ]
254
+ used_x: set[int] = set()
255
+ rec_entries: List[Dict[str, Any]] = []
256
+ for ref in recipients:
257
+ rid = _stable_recipient_id(ref)
258
+ x = _x_from_recipient_id(rid, used_x)
259
+ y = _poly_eval_at(x, coeffs, _P)
260
+ header = _encode_share(x, y)
261
+ rec_entries.append({"id": rid, "header": header})
262
+ payload = {
263
+ "kind": "aead",
264
+ "alg": palg,
265
+ "nonce": nonce,
266
+ "ct": ct,
267
+ "tag": tag,
268
+ "aad": aad,
269
+ }
270
+ env: MultiRecipientEnvelope = {
271
+ "mode": _MODE,
272
+ "payload": payload,
273
+ "recipient_alg": _RECIP_ALG,
274
+ "recipients": rec_entries,
275
+ "shared": {
276
+ "threshold_k": k.to_bytes(2, "big"),
277
+ "cek_len": _CEK_LEN.to_bytes(2, "big"),
278
+ },
279
+ }
280
+ if shared:
281
+ extra = dict(shared)
282
+ extra.pop("threshold_k", None)
283
+ extra.pop("cek_len", None)
284
+ env["shared"].update(extra) # type: ignore[index]
285
+ return env
286
+
287
+ # --------------------------------- open_for --------------------------------
288
+ async def open_for(
289
+ self,
290
+ my_identity: KeyRef,
291
+ env: MultiRecipientEnvelope,
292
+ *,
293
+ aad: Optional[bytes] = None,
294
+ opts: Optional[Mapping[str, object]] = None,
295
+ ) -> bytes:
296
+ k = _decode_k(env)
297
+ if k != 1:
298
+ raise ValueError(
299
+ "This envelope requires ≥2 shares; call open_for_many(...)."
300
+ )
301
+ rid = _stable_recipient_id(my_identity)
302
+ share = _find_share_for(rid, env)
303
+ if share is None:
304
+ raise ValueError("This identity has no share in the envelope.")
305
+ x, y = _decode_share(share)
306
+ cek_int = y % _P
307
+ cek = _int_to_bytes(cek_int).rjust(_decode_cek_len(env), b"\x00")
308
+ payload = _expect_aead_payload(env)
309
+ return _aes_gcm_decrypt(
310
+ cek,
311
+ payload["nonce"],
312
+ payload["ct"],
313
+ payload["tag"],
314
+ aad or payload.get("aad"),
315
+ )
316
+
317
+ # ------------------------------- open_for_many ------------------------------
318
+ async def open_for_many(
319
+ self,
320
+ my_identities: Sequence[KeyRef],
321
+ env: MultiRecipientEnvelope,
322
+ *,
323
+ aad: Optional[bytes] = None,
324
+ opts: Optional[Mapping[str, object]] = None,
325
+ ) -> bytes:
326
+ if not my_identities:
327
+ raise ValueError("No identities provided.")
328
+ k = _decode_k(env)
329
+ payload = _expect_aead_payload(env)
330
+ points: List[Tuple[int, int]] = []
331
+ seen_x: set[int] = set()
332
+ for ident in my_identities:
333
+ rid = _stable_recipient_id(ident)
334
+ h = _find_share_for(rid, env)
335
+ if h is None:
336
+ continue
337
+ x, y = _decode_share(h)
338
+ if x in seen_x:
339
+ continue
340
+ seen_x.add(x)
341
+ points.append((x, y))
342
+ if len(points) >= k:
343
+ break
344
+ if len(points) < k:
345
+ raise ValueError(
346
+ f"Need at least {k} shares; provided {len(points)} that match the envelope."
347
+ )
348
+ cek_int = _lagrange_interpolate_at(0, points, _P)
349
+ cek = _int_to_bytes(cek_int).rjust(_decode_cek_len(env), b"\x00")
350
+ return _aes_gcm_decrypt(
351
+ cek,
352
+ payload["nonce"],
353
+ payload["ct"],
354
+ payload["tag"],
355
+ aad or payload.get("aad"),
356
+ )
357
+
358
+ # ---------------------------------- rewrap ---------------------------------
359
+ async def rewrap(
360
+ self,
361
+ env: MultiRecipientEnvelope,
362
+ *,
363
+ add: Optional[Sequence[KeyRef]] = None,
364
+ remove: Optional[Sequence[RecipientId]] = None,
365
+ recipient_alg: Optional[Alg] = None,
366
+ opts: Optional[Mapping[str, object]] = None,
367
+ ) -> MultiRecipientEnvelope:
368
+ if env.get("mode") != _MODE or env.get("recipient_alg") != _RECIP_ALG:
369
+ raise ValueError("Envelope does not match ShamirMreCrypto mode/alg.")
370
+ if recipient_alg not in (None, _RECIP_ALG):
371
+ raise ValueError("recipient_alg must be SHAMIR-KOFN for ShamirMreCrypto.")
372
+ k = _decode_k(env)
373
+ cek_len = _decode_cek_len(env)
374
+ recs: List[Dict[str, Any]] = list(env.get("recipients", []))
375
+ if remove:
376
+ to_remove = set(remove)
377
+ recs = [r for r in recs if r.get("id") not in to_remove]
378
+ rotate = (
379
+ bool((opts or {}).get("rotate_payload_on_revoke", True))
380
+ if remove
381
+ else False
382
+ )
383
+ points = _collect_k_points(recs, k)
384
+ if add and not rotate:
385
+ used_x = {_decode_share(r["header"])[0] for r in recs}
386
+ for ref in add:
387
+ rid = _stable_recipient_id(ref)
388
+ x_new = _x_from_recipient_id(rid, used_x)
389
+ y_new = _lagrange_interpolate_at(x_new, points, _P)
390
+ recs.append({"id": rid, "header": _encode_share(x_new, y_new)})
391
+ updated = {
392
+ "mode": _MODE,
393
+ "payload": env["payload"],
394
+ "recipient_alg": _RECIP_ALG,
395
+ "recipients": recs,
396
+ "shared": dict(env.get("shared", {})),
397
+ }
398
+ return updated # type: ignore[return-value]
399
+ _ = _lagrange_interpolate_at(0, points, _P)
400
+ new_cek = os.urandom(cek_len)
401
+ payload = _expect_aead_payload(env)
402
+ pt = _aes_gcm_decrypt(
403
+ cek=_int_to_bytes(_lagrange_interpolate_at(0, points, _P)).rjust(
404
+ cek_len, b"\x00"
405
+ ),
406
+ nonce=payload["nonce"],
407
+ ct=payload["ct"],
408
+ tag=payload["tag"],
409
+ aad=payload.get("aad"),
410
+ )
411
+ nonce, ct, tag = _aes_gcm_encrypt(new_cek, pt, payload.get("aad"))
412
+ secret = _bytes_to_int(new_cek)
413
+ coeffs = [secret] + [
414
+ int.from_bytes(os.urandom(64), "big") % _P for _ in range(max(0, k - 1))
415
+ ]
416
+ used_x: set[int] = set()
417
+ new_recs: List[Dict[str, Any]] = []
418
+ base_ids = [r["id"] for r in recs]
419
+ add_ids: List[str] = []
420
+ add = add or []
421
+ for ref in add:
422
+ add_ids.append(_stable_recipient_id(ref))
423
+ all_ids = base_ids + add_ids
424
+ for rid in all_ids:
425
+ x = _x_from_recipient_id(rid, used_x)
426
+ y = _poly_eval_at(x, coeffs, _P)
427
+ new_recs.append({"id": rid, "header": _encode_share(x, y)})
428
+ updated_payload = {
429
+ "kind": "aead",
430
+ "alg": payload["alg"],
431
+ "nonce": nonce,
432
+ "ct": ct,
433
+ "tag": tag,
434
+ "aad": payload.get("aad"),
435
+ }
436
+ updated = {
437
+ "mode": _MODE,
438
+ "payload": updated_payload,
439
+ "recipient_alg": _RECIP_ALG,
440
+ "recipients": new_recs,
441
+ "shared": {
442
+ **dict(env.get("shared", {})),
443
+ "cek_len": cek_len.to_bytes(2, "big"),
444
+ "threshold_k": k.to_bytes(2, "big"),
445
+ },
446
+ }
447
+ return updated # type: ignore[return-value]
448
+
449
+
450
+ # ============================== local helpers ================================
451
+
452
+
453
+ def _decode_k(env: MultiRecipientEnvelope) -> int:
454
+ s = env.get("shared", {}) or {}
455
+ k_b = s.get("threshold_k")
456
+ if not isinstance(k_b, (bytes, bytearray)):
457
+ raise ValueError("Envelope missing 'shared.threshold_k'.")
458
+ return int.from_bytes(k_b, "big")
459
+
460
+
461
+ def _decode_cek_len(env: MultiRecipientEnvelope) -> int:
462
+ s = env.get("shared", {}) or {}
463
+ b = s.get("cek_len")
464
+ if not isinstance(b, (bytes, bytearray)):
465
+ return _CEK_LEN
466
+ return int.from_bytes(b, "big")
467
+
468
+
469
+ def _expect_aead_payload(env: MultiRecipientEnvelope) -> Dict[str, Any]:
470
+ payload = env.get("payload")
471
+ if not isinstance(payload, dict) or payload.get("kind") != "aead":
472
+ raise ValueError("Envelope payload is not AEAD kind.")
473
+ for key in ("alg", "nonce", "ct", "tag"):
474
+ if key not in payload:
475
+ raise ValueError(f"Envelope payload missing '{key}'.")
476
+ if payload["alg"] != _PAYLOAD_AEAD_DEFAULT:
477
+ raise ValueError("Unsupported payload AEAD algorithm.")
478
+ return payload # type: ignore[return-value]
479
+
480
+
481
+ def _find_share_for(rid: str, env: MultiRecipientEnvelope) -> Optional[bytes]:
482
+ for r in env.get("recipients", []):
483
+ if r.get("id") == rid:
484
+ h = r.get("header")
485
+ if isinstance(h, (bytes, bytearray)):
486
+ return bytes(h)
487
+ return None
488
+
489
+
490
+ def _collect_k_points(
491
+ recs: Sequence[Mapping[str, Any]], k: int
492
+ ) -> List[Tuple[int, int]]:
493
+ points: List[Tuple[int, int]] = []
494
+ seen: set[int] = set()
495
+ for r in recs:
496
+ h = r.get("header")
497
+ if not isinstance(h, (bytes, bytearray)):
498
+ continue
499
+ x, y = _decode_share(h)
500
+ if x in seen:
501
+ continue
502
+ seen.add(x)
503
+ points.append((x, y))
504
+ if len(points) >= k:
505
+ break
506
+ if len(points) < k:
507
+ raise ValueError(
508
+ f"Envelope has only {len(points)} usable shares; need at least {k}."
509
+ )
510
+ return points
@@ -0,0 +1,3 @@
1
+ from .ShamirMreCrypto import ShamirMreCrypto
2
+
3
+ __all__ = ["ShamirMreCrypto"]