swarmauri_mre_crypto_age 0.3.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,92 @@
1
+ Metadata-Version: 2.3
2
+ Name: swarmauri_mre_crypto_age
3
+ Version: 0.3.0.dev3
4
+ Summary: Age-style X25519 sealed-per-recipient MRE 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 (>=41)
21
+ Requires-Dist: swarmauri_base
22
+ Requires-Dist: swarmauri_core
23
+ Description-Content-Type: text/markdown
24
+
25
+ ![Swamauri Logo](https://res.cloudinary.com/dbjmpekvl/image/upload/v1730099724/Swarmauri-logo-lockup-2048x757_hww01w.png)
26
+
27
+ <p align="center">
28
+ <a href="https://pypi.org/project/swarmauri_mre_crypto_age/">
29
+ <img src="https://img.shields.io/pypi/dm/swarmauri_mre_crypto_age" alt="PyPI - Downloads"/></a>
30
+ <a href="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/standards/swarmauri_mre_crypto_age/">
31
+ <img alt="Hits" src="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/standards/swarmauri_mre_crypto_age.svg"/></a>
32
+ <a href="https://pypi.org/project/swarmauri_mre_crypto_age/">
33
+ <img src="https://img.shields.io/pypi/pyversions/swarmauri_mre_crypto_age" alt="PyPI - Python Version"/></a>
34
+ <a href="https://pypi.org/project/swarmauri_mre_crypto_age/">
35
+ <img src="https://img.shields.io/pypi/l/swarmauri_mre_crypto_age" alt="PyPI - License"/></a>
36
+ <a href="https://pypi.org/project/swarmauri_mre_crypto_age/">
37
+ <img src="https://img.shields.io/pypi/v/swarmauri_mre_crypto_age?label=swarmauri_mre_crypto_age&color=green" alt="PyPI - swarmauri_mre_crypto_age"/></a>
38
+ </p>
39
+
40
+ ---
41
+
42
+ ## Swarmauri MRE Crypto Age
43
+
44
+ Age-based multi-recipient encryption provider implementing the `IMreCrypto` contract.
45
+
46
+ - Sealed-per-recipient X25519 stanzas
47
+ - ChaCha20-Poly1305 payload encryption
48
+ - Deterministic recipient identifiers via SHA-256 public key fingerprints
49
+
50
+ ### Installation
51
+
52
+ ```bash
53
+ pip install swarmauri_mre_crypto_age
54
+ ```
55
+
56
+ ### Usage
57
+
58
+ The provider exposes asynchronous helpers for encrypting data to many
59
+ recipients and decrypting it for a specific private key. The example below
60
+ walks through a complete round trip.
61
+
62
+ 1. Create the crypto provider.
63
+ 2. Generate key pairs for two recipients.
64
+ 3. Encrypt a payload for both recipients.
65
+ 4. Decrypt the payload for one recipient.
66
+
67
+ ```python
68
+ from swarmauri_mre_crypto_age import AgeMreCrypto
69
+ from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey
70
+
71
+ crypto = AgeMreCrypto()
72
+
73
+ # generate key pairs for each participant
74
+ sk1 = X25519PrivateKey.generate()
75
+ pk1 = sk1.public_key()
76
+ sk2 = X25519PrivateKey.generate()
77
+ pk2 = sk2.public_key()
78
+
79
+ recipients = [
80
+ {"kind": "cryptography_obj", "obj": pk1},
81
+ {"kind": "cryptography_obj", "obj": pk2},
82
+ ]
83
+
84
+ env = await crypto.encrypt_for_many(recipients, b"secret")
85
+ pt = await crypto.open_for({"kind": "cryptography_obj", "obj": sk1}, env)
86
+ assert pt == b"secret"
87
+ ```
88
+
89
+ ## Entry point
90
+
91
+ The provider is registered under the `swarmauri.mre_cryptos` entry-point as `AgeMreCrypto`.
92
+
@@ -0,0 +1,67 @@
1
+ ![Swamauri Logo](https://res.cloudinary.com/dbjmpekvl/image/upload/v1730099724/Swarmauri-logo-lockup-2048x757_hww01w.png)
2
+
3
+ <p align="center">
4
+ <a href="https://pypi.org/project/swarmauri_mre_crypto_age/">
5
+ <img src="https://img.shields.io/pypi/dm/swarmauri_mre_crypto_age" alt="PyPI - Downloads"/></a>
6
+ <a href="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/standards/swarmauri_mre_crypto_age/">
7
+ <img alt="Hits" src="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/standards/swarmauri_mre_crypto_age.svg"/></a>
8
+ <a href="https://pypi.org/project/swarmauri_mre_crypto_age/">
9
+ <img src="https://img.shields.io/pypi/pyversions/swarmauri_mre_crypto_age" alt="PyPI - Python Version"/></a>
10
+ <a href="https://pypi.org/project/swarmauri_mre_crypto_age/">
11
+ <img src="https://img.shields.io/pypi/l/swarmauri_mre_crypto_age" alt="PyPI - License"/></a>
12
+ <a href="https://pypi.org/project/swarmauri_mre_crypto_age/">
13
+ <img src="https://img.shields.io/pypi/v/swarmauri_mre_crypto_age?label=swarmauri_mre_crypto_age&color=green" alt="PyPI - swarmauri_mre_crypto_age"/></a>
14
+ </p>
15
+
16
+ ---
17
+
18
+ ## Swarmauri MRE Crypto Age
19
+
20
+ Age-based multi-recipient encryption provider implementing the `IMreCrypto` contract.
21
+
22
+ - Sealed-per-recipient X25519 stanzas
23
+ - ChaCha20-Poly1305 payload encryption
24
+ - Deterministic recipient identifiers via SHA-256 public key fingerprints
25
+
26
+ ### Installation
27
+
28
+ ```bash
29
+ pip install swarmauri_mre_crypto_age
30
+ ```
31
+
32
+ ### Usage
33
+
34
+ The provider exposes asynchronous helpers for encrypting data to many
35
+ recipients and decrypting it for a specific private key. The example below
36
+ walks through a complete round trip.
37
+
38
+ 1. Create the crypto provider.
39
+ 2. Generate key pairs for two recipients.
40
+ 3. Encrypt a payload for both recipients.
41
+ 4. Decrypt the payload for one recipient.
42
+
43
+ ```python
44
+ from swarmauri_mre_crypto_age import AgeMreCrypto
45
+ from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey
46
+
47
+ crypto = AgeMreCrypto()
48
+
49
+ # generate key pairs for each participant
50
+ sk1 = X25519PrivateKey.generate()
51
+ pk1 = sk1.public_key()
52
+ sk2 = X25519PrivateKey.generate()
53
+ pk2 = sk2.public_key()
54
+
55
+ recipients = [
56
+ {"kind": "cryptography_obj", "obj": pk1},
57
+ {"kind": "cryptography_obj", "obj": pk2},
58
+ ]
59
+
60
+ env = await crypto.encrypt_for_many(recipients, b"secret")
61
+ pt = await crypto.open_for({"kind": "cryptography_obj", "obj": sk1}, env)
62
+ assert pt == b"secret"
63
+ ```
64
+
65
+ ## Entry point
66
+
67
+ The provider is registered under the `swarmauri.mre_cryptos` entry-point as `AgeMreCrypto`.
@@ -0,0 +1,71 @@
1
+ [project]
2
+ name = "swarmauri_mre_crypto_age"
3
+ version = "0.3.0.dev3"
4
+ description = "Age-style X25519 sealed-per-recipient MRE 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>=41",
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
+ "example: Example usage tests",
43
+ ]
44
+ timeout = 300
45
+ log_cli = true
46
+ log_cli_level = "INFO"
47
+ log_cli_format = "%(asctime)s [%(levelname)s] %(message)s"
48
+ log_cli_date_format = "%Y-%m-%d %H:%M:%S"
49
+ asyncio_default_fixture_loop_scope = "function"
50
+
51
+ [build-system]
52
+ requires = ["poetry-core>=1.0.0"]
53
+ build-backend = "poetry.core.masonry.api"
54
+
55
+ [dependency-groups]
56
+ dev = [
57
+ "pytest>=8.0",
58
+ "pytest-asyncio>=0.24.0",
59
+ "pytest-xdist>=3.6.1",
60
+ "pytest-json-report>=1.5.0",
61
+ "flake8>=7.0",
62
+ "ruff>=0.9.9",
63
+ "pytest-timeout>=2.3.1",
64
+ "pytest-benchmark>=4.0.0",
65
+ ]
66
+
67
+ [project.entry-points.'swarmauri.mre_cryptos']
68
+ AgeMreCrypto = "swarmauri_mre_crypto_age:AgeMreCrypto"
69
+
70
+ [project.entry-points."peagen.plugins.mre_cryptos"]
71
+ age_mre = "swarmauri_mre_crypto_age:AgeMreCrypto"
@@ -0,0 +1,277 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import os
5
+ from typing import Any, Dict, Iterable, List, Mapping, Optional, Sequence, Union
6
+
7
+ from cryptography.hazmat.primitives import hashes
8
+ from cryptography.hazmat.primitives.asymmetric.x25519 import (
9
+ X25519PrivateKey,
10
+ X25519PublicKey,
11
+ )
12
+ from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305
13
+ from cryptography.hazmat.primitives.kdf.hkdf import HKDF
14
+ from cryptography.hazmat.primitives import serialization
15
+
16
+ from swarmauri_base.mre_crypto.MreCryptoBase import MreCryptoBase
17
+ from swarmauri_core.crypto.types import Alg, KeyRef
18
+ from swarmauri_core.mre_crypto.types import MultiRecipientEnvelope, RecipientId
19
+
20
+ try: # Optional enum import; string fallback for portability.
21
+ _HAVE_MREMODE = True
22
+ except Exception: # pragma: no cover
23
+ _HAVE_MREMODE = False
24
+
25
+
26
+ # ---------------------------------------------------------------------------
27
+ # helper functions
28
+ # ---------------------------------------------------------------------------
29
+
30
+
31
+ def _mode_token(value: Optional[Union[str, Any]] = None) -> str:
32
+ """Normalize a mode token to str. Default to sealed_per_recipient."""
33
+ if value is None:
34
+ return "sealed_per_recipient"
35
+ if _HAVE_MREMODE and hasattr(value, "value"):
36
+ return str(value.value)
37
+ return str(value)
38
+
39
+
40
+ def _pub_from_keyref(ref: KeyRef) -> X25519PublicKey:
41
+ """Extract an X25519 public key from a KeyRef."""
42
+ if isinstance(ref, dict):
43
+ kind = ref.get("kind")
44
+ if kind == "cryptography_obj" and isinstance(ref.get("obj"), X25519PublicKey):
45
+ return ref["obj"] # type: ignore[return-value]
46
+ if kind in ("raw_x25519_pk", "age_x25519_pk"):
47
+ b = ref.get("bytes")
48
+ if isinstance(b, (bytes, bytearray)) and len(b) == 32:
49
+ return X25519PublicKey.from_public_bytes(bytes(b))
50
+ raise TypeError("Unsupported KeyRef for X25519 public key.")
51
+
52
+
53
+ def _priv_from_keyref(ref: KeyRef) -> X25519PrivateKey:
54
+ """Extract an X25519 private key from a KeyRef."""
55
+ if isinstance(ref, dict):
56
+ kind = ref.get("kind")
57
+ if kind == "cryptography_obj" and isinstance(ref.get("obj"), X25519PrivateKey):
58
+ return ref["obj"] # type: ignore[return-value]
59
+ if kind in ("raw_x25519_sk", "age_x25519_sk"):
60
+ b = ref.get("bytes")
61
+ if isinstance(b, (bytes, bytearray)) and len(b) == 32:
62
+ return X25519PrivateKey.from_private_bytes(bytes(b))
63
+ raise TypeError("Unsupported KeyRef for X25519 private key.")
64
+
65
+
66
+ def _pub_bytes(pk: X25519PublicKey) -> bytes:
67
+ return pk.public_bytes(
68
+ encoding=serialization.Encoding.Raw, format=serialization.PublicFormat.Raw
69
+ )
70
+
71
+
72
+ def _fingerprint(pk: X25519PublicKey) -> str:
73
+ return hashlib.sha256(_pub_bytes(pk)).hexdigest()
74
+
75
+
76
+ _MAGIC = b"AGE-MRE-X25519\x00"
77
+ _VERSION = b"\x01"
78
+ _NONCE_LEN = 12
79
+ _KEY_LEN = 32
80
+
81
+
82
+ def _hkdf_key(
83
+ shared_secret: bytes, salt: bytes, info: bytes, length: int = 32
84
+ ) -> bytes:
85
+ hkdf = HKDF(
86
+ algorithm=hashes.SHA256(),
87
+ length=length,
88
+ salt=salt,
89
+ info=info,
90
+ )
91
+ return hkdf.derive(shared_secret)
92
+
93
+
94
+ def _seal_x25519(pt: bytes, recipient_pk: X25519PublicKey) -> bytes:
95
+ eph_sk = X25519PrivateKey.generate()
96
+ eph_pk = eph_sk.public_key()
97
+ shared = eph_sk.exchange(recipient_pk)
98
+ salt = _pub_bytes(recipient_pk)
99
+ info = _MAGIC + _pub_bytes(eph_pk)
100
+ key = _hkdf_key(shared, salt=salt, info=info, length=_KEY_LEN)
101
+ aead = ChaCha20Poly1305(key)
102
+ nonce = os.urandom(_NONCE_LEN)
103
+ ct = aead.encrypt(nonce, pt, _MAGIC)
104
+ return b"".join([_MAGIC, _VERSION, _pub_bytes(eph_pk), nonce, ct])
105
+
106
+
107
+ def _unseal_x25519(sk: X25519PrivateKey, sealed: bytes) -> bytes:
108
+ if (
109
+ not sealed.startswith(_MAGIC)
110
+ or len(sealed) < len(_MAGIC) + 1 + 32 + _NONCE_LEN + 16
111
+ ):
112
+ raise ValueError("Malformed sealed blob.")
113
+ off = len(_MAGIC)
114
+ v = sealed[off : off + 1]
115
+ off += 1
116
+ if v != _VERSION:
117
+ raise ValueError("Unsupported sealed blob version.")
118
+ eph_pk_b = sealed[off : off + 32]
119
+ off += 32
120
+ nonce = sealed[off : off + _NONCE_LEN]
121
+ off += _NONCE_LEN
122
+ ct = sealed[off:]
123
+ eph_pk = X25519PublicKey.from_public_bytes(eph_pk_b)
124
+ shared = sk.exchange(eph_pk)
125
+ my_pub = sk.public_key()
126
+ salt = _pub_bytes(my_pub)
127
+ info = _MAGIC + eph_pk_b
128
+ key = _hkdf_key(shared, salt=salt, info=info, length=_KEY_LEN)
129
+ aead = ChaCha20Poly1305(key)
130
+ return aead.decrypt(nonce, ct, _MAGIC)
131
+
132
+
133
+ class AgeMreCrypto(MreCryptoBase):
134
+ """AgeMreCrypto (sealed-per-recipient, X25519 stanzas)."""
135
+
136
+ type: str = "AgeMreCrypto"
137
+
138
+ def supports(self) -> Dict[str, Iterable[str]]:
139
+ modes = ("sealed_per_recipient",)
140
+ return {
141
+ "recipient": ("X25519-SEAL",),
142
+ "modes": modes,
143
+ "features": (),
144
+ }
145
+
146
+ async def encrypt_for_many(
147
+ self,
148
+ recipients: Sequence[KeyRef],
149
+ pt: bytes,
150
+ *,
151
+ payload_alg: Optional[Alg] = None,
152
+ recipient_alg: Optional[Alg] = None,
153
+ mode: Optional[Union[str, Any]] = None,
154
+ aad: Optional[bytes] = None,
155
+ shared: Optional[Mapping[str, bytes]] = None,
156
+ opts: Optional[Mapping[str, object]] = None,
157
+ ) -> MultiRecipientEnvelope:
158
+ m = _mode_token(mode)
159
+ if m != "sealed_per_recipient":
160
+ raise ValueError("AgeMreCrypto supports only mode='sealed_per_recipient'.")
161
+ if recipient_alg not in (None, "X25519-SEAL"):
162
+ raise ValueError("AgeMreCrypto supports only recipient_alg='X25519-SEAL'.")
163
+ recs: List[Dict[str, Any]] = []
164
+ for ref in recipients:
165
+ pk = _pub_from_keyref(ref)
166
+ sealed = _seal_x25519(pt, pk)
167
+ rid = _fingerprint(pk)
168
+ recs.append({"id": rid, "header": sealed})
169
+ env: MultiRecipientEnvelope = {
170
+ "mode": m,
171
+ "payload": {"kind": "sealed_per_recipient"},
172
+ "recipient_alg": "X25519-SEAL",
173
+ "recipients": recs,
174
+ }
175
+ if shared:
176
+ env["shared"] = dict(shared)
177
+ return env
178
+
179
+ async def open_for(
180
+ self,
181
+ my_identity: KeyRef,
182
+ env: MultiRecipientEnvelope,
183
+ *,
184
+ aad: Optional[bytes] = None,
185
+ opts: Optional[Mapping[str, object]] = None,
186
+ ) -> bytes:
187
+ mode = str(env.get("mode", ""))
188
+ if mode != "sealed_per_recipient":
189
+ raise ValueError(
190
+ "Envelope mode is not 'sealed_per_recipient' for AgeMreCrypto."
191
+ )
192
+ recip_alg = env.get("recipient_alg")
193
+ if recip_alg != "X25519-SEAL":
194
+ raise ValueError(
195
+ "Envelope recipient_alg must be 'X25519-SEAL' for AgeMreCrypto."
196
+ )
197
+ sk = _priv_from_keyref(my_identity)
198
+ my_rid = _fingerprint(sk.public_key())
199
+ for r in env.get("recipients", []):
200
+ if r.get("id") == my_rid:
201
+ sealed = r.get("header")
202
+ if not isinstance(sealed, (bytes, bytearray)):
203
+ raise ValueError("Recipient header is not bytes.")
204
+ return _unseal_x25519(sk, sealed)
205
+ for r in env.get("recipients", []):
206
+ sealed = r.get("header")
207
+ if not isinstance(sealed, (bytes, bytearray)):
208
+ continue
209
+ try:
210
+ return _unseal_x25519(sk, sealed)
211
+ except Exception:
212
+ continue
213
+ raise ValueError("This identity cannot open the envelope.")
214
+
215
+ async def open_for_many(
216
+ self,
217
+ my_identities: Sequence[KeyRef],
218
+ env: MultiRecipientEnvelope,
219
+ *,
220
+ aad: Optional[bytes] = None,
221
+ opts: Optional[Mapping[str, object]] = None,
222
+ ) -> bytes:
223
+ last_err: Optional[Exception] = None
224
+ for ident in my_identities:
225
+ try:
226
+ return await self.open_for(ident, env, aad=aad, opts=opts)
227
+ except Exception as e: # pragma: no cover - keep last error
228
+ last_err = e
229
+ continue
230
+ raise last_err if last_err else ValueError("No identities provided.")
231
+
232
+ async def rewrap(
233
+ self,
234
+ env: MultiRecipientEnvelope,
235
+ *,
236
+ add: Optional[Sequence[KeyRef]] = None,
237
+ remove: Optional[Sequence[RecipientId]] = None,
238
+ recipient_alg: Optional[Alg] = None,
239
+ opts: Optional[Mapping[str, object]] = None,
240
+ ) -> MultiRecipientEnvelope:
241
+ mode = str(env.get("mode", ""))
242
+ if mode != "sealed_per_recipient":
243
+ raise ValueError(
244
+ "Envelope mode is not 'sealed_per_recipient' for AgeMreCrypto."
245
+ )
246
+ if recipient_alg not in (None, "X25519-SEAL"):
247
+ raise ValueError("AgeMreCrypto supports only recipient_alg='X25519-SEAL'.")
248
+ recipients_list: List[Dict[str, Any]] = list(env.get("recipients", []))
249
+ if remove:
250
+ remove_set = set(remove)
251
+ recipients_list = [
252
+ r for r in recipients_list if r.get("id") not in remove_set
253
+ ]
254
+ plaintext: Optional[bytes] = None
255
+ if add:
256
+ if opts and isinstance(opts.get("pt"), (bytes, bytearray)):
257
+ plaintext = bytes(opts["pt"])
258
+ elif opts and opts.get("open_with") is not None:
259
+ plaintext = await self.open_for(opts["open_with"], env) # type: ignore[arg-type]
260
+ else:
261
+ raise ValueError(
262
+ "Adding recipients requires opts['pt'] or opts['open_with']."
263
+ )
264
+ for ref in add:
265
+ pk = _pub_from_keyref(ref)
266
+ sealed = _seal_x25519(plaintext, pk)
267
+ rid = _fingerprint(pk)
268
+ recipients_list.append({"id": rid, "header": sealed})
269
+ updated: MultiRecipientEnvelope = {
270
+ "mode": "sealed_per_recipient",
271
+ "payload": {"kind": "sealed_per_recipient"},
272
+ "recipient_alg": "X25519-SEAL",
273
+ "recipients": recipients_list,
274
+ }
275
+ if "shared" in env:
276
+ updated["shared"] = env["shared"]
277
+ return updated
@@ -0,0 +1,3 @@
1
+ from .AgeMreCrypto import AgeMreCrypto
2
+
3
+ __all__ = ["AgeMreCrypto"]