swarmauri_crypto_pgp 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,86 @@
1
+ Metadata-Version: 2.3
2
+ Name: swarmauri_crypto_pgp
3
+ Version: 0.2.0.dev3
4
+ Summary: OpenPGP (GnuPG) + AES-GCM 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
+ Requires-Dist: cryptography (>=41)
19
+ Requires-Dist: python-gnupg (>=0.5.0)
20
+ Requires-Dist: swarmauri_base
21
+ Requires-Dist: swarmauri_core
22
+ Description-Content-Type: text/markdown
23
+
24
+ ![Swamauri Logo](https://res.cloudinary.com/dbjmpekvl/image/upload/v1730099724/Swarmauri-logo-lockup-2048x757_hww01w.png)
25
+
26
+ <p align="center">
27
+ <a href="https://pypi.org/project/swarmauri_crypto_pgp/">
28
+ <img src="https://img.shields.io/pypi/dm/swarmauri_crypto_pgp" alt="PyPI - Downloads"/></a>
29
+ <a href="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/standards/swarmauri_crypto_pgp/">
30
+ <img alt="Hits" src="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/standards/swarmauri_crypto_pgp.svg"/></a>
31
+ <a href="https://pypi.org/project/swarmauri_crypto_pgp/">
32
+ <img src="https://img.shields.io/pypi/pyversions/swarmauri_crypto_pgp" alt="PyPI - Python Version"/></a>
33
+ <a href="https://pypi.org/project/swarmauri_crypto_pgp/">
34
+ <img src="https://img.shields.io/pypi/l/swarmauri_crypto_pgp" alt="PyPI - License"/></a>
35
+ <a href="https://pypi.org/project/swarmauri_crypto_pgp/">
36
+ <img src="https://img.shields.io/pypi/v/swarmauri_crypto_pgp?label=swarmauri_crypto_pgp&color=green" alt="PyPI - swarmauri_crypto_pgp"/></a>
37
+ </p>
38
+
39
+ ---
40
+
41
+ ## Swarmauri Crypto PGP
42
+
43
+ OpenPGP (GnuPG-backed) crypto provider implementing the `ICrypto` contract.
44
+
45
+ - Symmetric AEAD: AES-256-GCM
46
+ - Key wrapping: OpenPGP public-key encryption (RSA keys recommended)
47
+ - Hybrid encrypt-for-many supported
48
+
49
+ ### Key material expectations
50
+
51
+ - `encrypt`/`decrypt`: `KeyRef.material` must be 16/24/32 bytes for AES-GCM
52
+ - `wrap`/`encrypt_for_many`: `KeyRef.public` must be ASCII-armored OpenPGP public key bytes
53
+ - `unwrap`: `KeyRef.material` must be ASCII-armored OpenPGP private key bytes
54
+
55
+ ## Installation
56
+
57
+ ```bash
58
+ pip install swarmauri_crypto_pgp
59
+ ```
60
+
61
+ ## Usage
62
+
63
+ ```python
64
+ from swarmauri_crypto_pgp import PGPCrypto
65
+ from swarmauri_core.crypto.types import KeyRef, KeyType, KeyUse, ExportPolicy
66
+
67
+ crypto = PGPCrypto()
68
+
69
+ # Symmetric key for AEAD
70
+ sym = KeyRef(
71
+ kid="sym1",
72
+ version=1,
73
+ type=KeyType.SYMMETRIC,
74
+ uses=(KeyUse.ENCRYPT, KeyUse.DECRYPT),
75
+ export_policy=ExportPolicy.SECRET_WHEN_ALLOWED,
76
+ material=b"\x00" * 32,
77
+ )
78
+
79
+ ct = await crypto.encrypt(sym, b"hello")
80
+ pt = await crypto.decrypt(sym, ct)
81
+ ```
82
+
83
+ ## Entry point
84
+
85
+ The provider is registered under the `swarmauri.cryptos` entry-point as `PGPCrypto`.
86
+
@@ -0,0 +1,62 @@
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_crypto_pgp/">
5
+ <img src="https://img.shields.io/pypi/dm/swarmauri_crypto_pgp" alt="PyPI - Downloads"/></a>
6
+ <a href="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/standards/swarmauri_crypto_pgp/">
7
+ <img alt="Hits" src="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/standards/swarmauri_crypto_pgp.svg"/></a>
8
+ <a href="https://pypi.org/project/swarmauri_crypto_pgp/">
9
+ <img src="https://img.shields.io/pypi/pyversions/swarmauri_crypto_pgp" alt="PyPI - Python Version"/></a>
10
+ <a href="https://pypi.org/project/swarmauri_crypto_pgp/">
11
+ <img src="https://img.shields.io/pypi/l/swarmauri_crypto_pgp" alt="PyPI - License"/></a>
12
+ <a href="https://pypi.org/project/swarmauri_crypto_pgp/">
13
+ <img src="https://img.shields.io/pypi/v/swarmauri_crypto_pgp?label=swarmauri_crypto_pgp&color=green" alt="PyPI - swarmauri_crypto_pgp"/></a>
14
+ </p>
15
+
16
+ ---
17
+
18
+ ## Swarmauri Crypto PGP
19
+
20
+ OpenPGP (GnuPG-backed) crypto provider implementing the `ICrypto` contract.
21
+
22
+ - Symmetric AEAD: AES-256-GCM
23
+ - Key wrapping: OpenPGP public-key encryption (RSA keys recommended)
24
+ - Hybrid encrypt-for-many supported
25
+
26
+ ### Key material expectations
27
+
28
+ - `encrypt`/`decrypt`: `KeyRef.material` must be 16/24/32 bytes for AES-GCM
29
+ - `wrap`/`encrypt_for_many`: `KeyRef.public` must be ASCII-armored OpenPGP public key bytes
30
+ - `unwrap`: `KeyRef.material` must be ASCII-armored OpenPGP private key bytes
31
+
32
+ ## Installation
33
+
34
+ ```bash
35
+ pip install swarmauri_crypto_pgp
36
+ ```
37
+
38
+ ## Usage
39
+
40
+ ```python
41
+ from swarmauri_crypto_pgp import PGPCrypto
42
+ from swarmauri_core.crypto.types import KeyRef, KeyType, KeyUse, ExportPolicy
43
+
44
+ crypto = PGPCrypto()
45
+
46
+ # Symmetric key for AEAD
47
+ sym = KeyRef(
48
+ kid="sym1",
49
+ version=1,
50
+ type=KeyType.SYMMETRIC,
51
+ uses=(KeyUse.ENCRYPT, KeyUse.DECRYPT),
52
+ export_policy=ExportPolicy.SECRET_WHEN_ALLOWED,
53
+ material=b"\x00" * 32,
54
+ )
55
+
56
+ ct = await crypto.encrypt(sym, b"hello")
57
+ pt = await crypto.decrypt(sym, ct)
58
+ ```
59
+
60
+ ## Entry point
61
+
62
+ The provider is registered under the `swarmauri.cryptos` entry-point as `PGPCrypto`.
@@ -0,0 +1,67 @@
1
+ [project]
2
+ name = "swarmauri_crypto_pgp"
3
+ version = "0.2.0.dev3"
4
+ description = "OpenPGP (GnuPG) + AES-GCM 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>=41",
24
+ "python-gnupg>=0.5.0",
25
+ ]
26
+
27
+ [tool.uv.sources]
28
+ swarmauri_core = { workspace = true }
29
+ swarmauri_base = { workspace = true }
30
+
31
+ [tool.pytest.ini_options]
32
+ norecursedirs = ["combined", "scripts"]
33
+ markers = [
34
+ "test: standard test",
35
+ "unit: Unit tests",
36
+ "i9n: Integration tests",
37
+ "r8n: Regression tests",
38
+ "acceptance: Acceptance tests",
39
+ "perf: Performance tests",
40
+ ]
41
+ timeout = 300
42
+ log_cli = true
43
+ log_cli_level = "INFO"
44
+ log_cli_format = "%(asctime)s [%(levelname)s] %(message)s"
45
+ log_cli_date_format = "%Y-%m-%d %H:%M:%S"
46
+ asyncio_default_fixture_loop_scope = "function"
47
+
48
+ [build-system]
49
+ requires = ["poetry-core>=1.0.0"]
50
+ build-backend = "poetry.core.masonry.api"
51
+
52
+ [dependency-groups]
53
+ dev = [
54
+ "pytest>=8.0",
55
+ "pytest-asyncio>=0.24.0",
56
+ "pytest-xdist>=3.6.1",
57
+ "pytest-json-report>=1.5.0",
58
+ "flake8>=7.0",
59
+ "ruff>=0.9.9",
60
+ "pytest-timeout>=2.3.1",
61
+ ]
62
+
63
+ [project.entry-points.'swarmauri.cryptos']
64
+ PGPCrypto = "swarmauri_crypto_pgp:PGPCrypto"
65
+
66
+ [project.entry-points."peagen.plugins.cryptos"]
67
+ pgp = "swarmauri_crypto_pgp:PGPCrypto"
@@ -0,0 +1,371 @@
1
+ """OpenPGP-backed crypto provider with sealing support.
2
+
3
+ Implements the ICrypto contract using:
4
+ - AES-256-GCM for symmetric encrypt/decrypt (AEAD)
5
+ - OpenPGP public-key encryption for:
6
+ • wrapping the session key to many recipients (KEM+AEAD mode)
7
+ • sealing/unsealing (direct public-key encryption of plaintext) for one or many
8
+
9
+ Notes
10
+ -----
11
+ - For wrap/encrypt_for_many/seal, ``KeyRef.public`` must contain an ASCII-armored
12
+ OpenPGP public key (as produced by ``gpg --armor --export``)
13
+ - For unwrap/unseal, ``KeyRef.material`` must contain an ASCII-armored OpenPGP
14
+ private key (as produced by ``gpg --armor --export-secret-keys``)
15
+ - Sealed mode ("OpenPGP-SEAL") does not bind AAD and produces per-recipient
16
+ ciphertexts (shared nonce/ct/tag are empty in MultiRecipientEnvelope).
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import secrets
22
+ import tempfile
23
+ from typing import Any, Dict, Iterable, Literal, Optional
24
+ from enum import Enum
25
+
26
+ import gnupg
27
+ from cryptography.hazmat.primitives.ciphers.aead import AESGCM
28
+
29
+ from swarmauri_core.crypto.types import (
30
+ AEADCiphertext,
31
+ Alg,
32
+ MultiRecipientEnvelope,
33
+ RecipientInfo,
34
+ UnsupportedAlgorithm,
35
+ WrappedKey,
36
+ KeyRef, # re-exported name used in ICrypto
37
+ )
38
+
39
+ from swarmauri_base.crypto.CryptoBase import CryptoBase
40
+ from swarmauri_base.ComponentBase import ComponentBase
41
+
42
+
43
+ _AEAD_DEFAULT = "AES-256-GCM"
44
+ _WRAP_ALG = "OpenPGP"
45
+ _SEAL_ALG = "OpenPGP-SEAL"
46
+
47
+
48
+ @ComponentBase.register_type(CryptoBase, "PGPCrypto")
49
+ class PGPCrypto(CryptoBase):
50
+ """Concrete implementation of the ICrypto contract using AES-GCM and OpenPGP."""
51
+
52
+ type: Literal["PGPCrypto"] = "PGPCrypto"
53
+
54
+ def supports(self) -> Dict[str, Iterable[Alg]]:
55
+ return {
56
+ "encrypt": (_AEAD_DEFAULT,),
57
+ "decrypt": (_AEAD_DEFAULT,),
58
+ "wrap": (_WRAP_ALG,),
59
+ "unwrap": (_WRAP_ALG,),
60
+ # Sealed-mode convenience
61
+ "seal": (_SEAL_ALG,),
62
+ "unseal": (_SEAL_ALG,),
63
+ # encrypt_for_many supports both KEM+AEAD (AES-256-GCM + OpenPGP)
64
+ # and sealed-style envelopes (OpenPGP-SEAL)
65
+ }
66
+
67
+ # ────────────────────────── symmetric AEAD ──────────────────────────
68
+
69
+ def _normalize_aead_alg(self, alg: Any) -> Alg:
70
+ if isinstance(alg, Enum):
71
+ alg = alg.value
72
+ alg = alg or _AEAD_DEFAULT
73
+ if alg == "AES256_GCM":
74
+ alg = _AEAD_DEFAULT
75
+ return alg
76
+
77
+ async def encrypt(
78
+ self,
79
+ key: KeyRef,
80
+ pt: bytes,
81
+ *,
82
+ alg: Optional[Alg] = None,
83
+ aad: Optional[bytes] = None,
84
+ nonce: Optional[bytes] = None,
85
+ ) -> AEADCiphertext:
86
+ alg = self._normalize_aead_alg(alg)
87
+ if alg != _AEAD_DEFAULT:
88
+ raise UnsupportedAlgorithm(f"Unsupported AEAD algorithm: {alg}")
89
+
90
+ if key.material is None:
91
+ raise ValueError(
92
+ "KeyRef.material must contain symmetric key bytes for AEAD"
93
+ )
94
+ if len(key.material) not in (16, 24, 32):
95
+ raise ValueError("KeyRef.material must be 16/24/32 bytes for AES-GCM")
96
+
97
+ nonce = nonce or secrets.token_bytes(12)
98
+ aead = AESGCM(key.material)
99
+ ct_with_tag = aead.encrypt(nonce, pt, aad)
100
+ # AESGCM returns ciphertext||tag (16 bytes)
101
+ ct, tag = ct_with_tag[:-16], ct_with_tag[-16:]
102
+ return AEADCiphertext(
103
+ kid=key.kid,
104
+ version=key.version,
105
+ alg=alg,
106
+ nonce=nonce,
107
+ ct=ct,
108
+ tag=tag,
109
+ aad=aad,
110
+ )
111
+
112
+ async def decrypt(
113
+ self,
114
+ key: KeyRef,
115
+ ct: AEADCiphertext,
116
+ *,
117
+ aad: Optional[bytes] = None,
118
+ ) -> bytes:
119
+ if self._normalize_aead_alg(ct.alg) != _AEAD_DEFAULT:
120
+ raise UnsupportedAlgorithm(f"Unsupported AEAD algorithm: {ct.alg}")
121
+ if key.material is None:
122
+ raise ValueError(
123
+ "KeyRef.material must contain symmetric key bytes for AEAD"
124
+ )
125
+
126
+ aead = AESGCM(key.material)
127
+ blob = ct.ct + ct.tag
128
+ return aead.decrypt(ct.nonce, blob, aad or ct.aad)
129
+
130
+ # ─────────────────────────── sealing ───────────────────────────
131
+ # (OpenPGP public-key encryption of plaintext; gpg handles hybrid internally)
132
+
133
+ async def seal(
134
+ self,
135
+ recipient: KeyRef,
136
+ pt: bytes,
137
+ *,
138
+ alg: Optional[Alg] = _SEAL_ALG,
139
+ ) -> bytes:
140
+ if alg != _SEAL_ALG:
141
+ raise UnsupportedAlgorithm(f"Unsupported seal alg: {alg}")
142
+ if recipient.public is None:
143
+ raise ValueError(
144
+ "KeyRef.public must contain ASCII-armored OpenPGP public key"
145
+ )
146
+
147
+ with tempfile.TemporaryDirectory() as gpg_home:
148
+ gpg = gnupg.GPG(gnupghome=gpg_home)
149
+ import_result = gpg.import_keys(
150
+ recipient.public.decode()
151
+ if isinstance(recipient.public, bytes)
152
+ else recipient.public
153
+ )
154
+ if not import_result.fingerprints:
155
+ raise RuntimeError("Failed to import recipient OpenPGP public key")
156
+ fp = import_result.fingerprints[0]
157
+
158
+ enc = gpg.encrypt(pt, fp, armor=False, always_trust=True)
159
+ if not enc.ok:
160
+ raise RuntimeError(f"GPG encrypt (seal) failed: {enc.status}")
161
+ return bytes(enc.data)
162
+
163
+ async def unseal(
164
+ self,
165
+ recipient_priv: KeyRef,
166
+ sealed: bytes,
167
+ *,
168
+ alg: Optional[Alg] = _SEAL_ALG,
169
+ ) -> bytes:
170
+ if alg != _SEAL_ALG:
171
+ raise UnsupportedAlgorithm(f"Unsupported seal alg: {alg}")
172
+ if recipient_priv.material is None:
173
+ raise ValueError(
174
+ "KeyRef.material must contain ASCII-armored OpenPGP private key"
175
+ )
176
+
177
+ passphrase = None
178
+ if recipient_priv.tags and "passphrase" in recipient_priv.tags:
179
+ passphrase = recipient_priv.tags["passphrase"]
180
+
181
+ with tempfile.TemporaryDirectory() as gpg_home:
182
+ gpg = gnupg.GPG(gnupghome=gpg_home)
183
+ import_result = gpg.import_keys(
184
+ recipient_priv.material.decode()
185
+ if isinstance(recipient_priv.material, bytes)
186
+ else recipient_priv.material
187
+ )
188
+ if not import_result.fingerprints:
189
+ raise RuntimeError("Failed to import OpenPGP private key")
190
+
191
+ dec = gpg.decrypt(sealed, passphrase=passphrase or "")
192
+ if not dec.ok:
193
+ raise RuntimeError(f"GPG decrypt (unseal) failed: {dec.status}")
194
+ return bytes(dec.data)
195
+
196
+ # ─────────── hybrid encrypt-for-many via OpenPGP (KEM+AEAD) ───────────
197
+
198
+ async def encrypt_for_many(
199
+ self,
200
+ recipients: Iterable[KeyRef],
201
+ pt: bytes,
202
+ *,
203
+ enc_alg: Optional[Alg] = None,
204
+ recipient_wrap_alg: Optional[Alg] = None,
205
+ aad: Optional[bytes] = None,
206
+ nonce: Optional[bytes] = None,
207
+ ) -> MultiRecipientEnvelope:
208
+ # 1) Sealed-style variant (per-recipient ciphertext; no shared ct/aad)
209
+ if enc_alg == _SEAL_ALG:
210
+ recip_infos: list[RecipientInfo] = []
211
+ with tempfile.TemporaryDirectory() as gpg_home:
212
+ gpg = gnupg.GPG(gnupghome=gpg_home)
213
+ for r in recipients:
214
+ if r.public is None:
215
+ raise ValueError(
216
+ "Recipient KeyRef.public must contain ASCII-armored OpenPGP public key"
217
+ )
218
+ import_result = gpg.import_keys(
219
+ r.public.decode() if isinstance(r.public, bytes) else r.public
220
+ )
221
+ if not import_result.fingerprints:
222
+ raise RuntimeError(
223
+ "Failed to import recipient OpenPGP public key"
224
+ )
225
+ fp = import_result.fingerprints[0]
226
+
227
+ enc = gpg.encrypt(pt, fp, armor=False, always_trust=True)
228
+ if not enc.ok:
229
+ raise RuntimeError(
230
+ f"GPG encrypt (seal-for-many) failed: {enc.status}"
231
+ )
232
+
233
+ recip_infos.append(
234
+ RecipientInfo(
235
+ kid=r.kid,
236
+ version=r.version,
237
+ wrap_alg=_SEAL_ALG,
238
+ wrapped_key=bytes(enc.data),
239
+ nonce=None,
240
+ )
241
+ )
242
+
243
+ # Shared fields empty for sealed variant
244
+ return MultiRecipientEnvelope(
245
+ enc_alg=_SEAL_ALG,
246
+ nonce=b"",
247
+ ct=b"",
248
+ tag=b"",
249
+ recipients=tuple(recip_infos),
250
+ aad=None, # AAD is not bound in OpenPGP-seal mode
251
+ )
252
+
253
+ # 2) Default KEM+AEAD path (shared AES-GCM ct + PGP-wrapped session key)
254
+ enc_alg = self._normalize_aead_alg(enc_alg)
255
+ if enc_alg != _AEAD_DEFAULT:
256
+ raise UnsupportedAlgorithm(f"Unsupported enc_alg: {enc_alg}")
257
+ wrap_alg = recipient_wrap_alg or _WRAP_ALG
258
+ if wrap_alg != _WRAP_ALG:
259
+ raise UnsupportedAlgorithm(f"Unsupported wrap_alg: {wrap_alg}")
260
+
261
+ k = secrets.token_bytes(32) # 256-bit session key
262
+ iv = nonce or secrets.token_bytes(12)
263
+ aead = AESGCM(k)
264
+ ct_with_tag = aead.encrypt(iv, pt, aad)
265
+ ct, tag = ct_with_tag[:-16], ct_with_tag[-16:]
266
+
267
+ recip_infos: list[RecipientInfo] = []
268
+ with tempfile.TemporaryDirectory() as gpg_home:
269
+ gpg = gnupg.GPG(gnupghome=gpg_home)
270
+ for r in recipients:
271
+ if r.public is None:
272
+ raise ValueError(
273
+ "Recipient KeyRef.public must contain ASCII-armored OpenPGP public key"
274
+ )
275
+ import_result = gpg.import_keys(
276
+ r.public.decode() if isinstance(r.public, bytes) else r.public
277
+ )
278
+ if not import_result.fingerprints:
279
+ raise RuntimeError("Failed to import recipient OpenPGP public key")
280
+ fp = import_result.fingerprints[0]
281
+
282
+ enc = gpg.encrypt(k, fp, armor=False, always_trust=True)
283
+ if not enc.ok:
284
+ raise RuntimeError(f"GPG encrypt failed: {enc.status}")
285
+
286
+ recip_infos.append(
287
+ RecipientInfo(
288
+ kid=r.kid,
289
+ version=r.version,
290
+ wrap_alg=wrap_alg,
291
+ wrapped_key=bytes(enc.data),
292
+ nonce=None,
293
+ )
294
+ )
295
+
296
+ return MultiRecipientEnvelope(
297
+ enc_alg=enc_alg,
298
+ nonce=iv,
299
+ ct=ct,
300
+ tag=tag,
301
+ recipients=tuple(recip_infos),
302
+ aad=aad,
303
+ )
304
+
305
+ # ────────────────────────── raw OpenPGP wrap/unwrap ─────────────────
306
+
307
+ async def wrap(
308
+ self,
309
+ kek: KeyRef,
310
+ *,
311
+ dek: Optional[bytes] = None,
312
+ wrap_alg: Optional[Alg] = None,
313
+ nonce: Optional[bytes] = None,
314
+ ) -> WrappedKey:
315
+ wrap_alg = wrap_alg or _WRAP_ALG
316
+ if wrap_alg != _WRAP_ALG:
317
+ raise UnsupportedAlgorithm(f"Unsupported wrap_alg: {wrap_alg}")
318
+ if kek.public is None:
319
+ raise ValueError(
320
+ "KeyRef.public must contain ASCII-armored OpenPGP public key"
321
+ )
322
+
323
+ with tempfile.TemporaryDirectory() as gpg_home:
324
+ gpg = gnupg.GPG(gnupghome=gpg_home)
325
+ import_result = gpg.import_keys(
326
+ kek.public.decode() if isinstance(kek.public, bytes) else kek.public
327
+ )
328
+ if not import_result.fingerprints:
329
+ raise RuntimeError("Failed to import recipient OpenPGP public key")
330
+ recipient_fp = import_result.fingerprints[0]
331
+
332
+ dek = dek or secrets.token_bytes(32)
333
+ enc = gpg.encrypt(dek, recipient_fp, armor=False, always_trust=True)
334
+ if not enc.ok:
335
+ raise RuntimeError(f"GPG encrypt failed: {enc.status}")
336
+
337
+ return WrappedKey(
338
+ kek_kid=kek.kid,
339
+ kek_version=kek.version,
340
+ wrap_alg=wrap_alg,
341
+ nonce=nonce,
342
+ wrapped=bytes(enc.data),
343
+ )
344
+
345
+ async def unwrap(self, kek: KeyRef, wrapped: WrappedKey) -> bytes:
346
+ if wrapped.wrap_alg != _WRAP_ALG:
347
+ raise UnsupportedAlgorithm(f"Unsupported wrap_alg: {wrapped.wrap_alg}")
348
+ if kek.material is None:
349
+ raise ValueError(
350
+ "KeyRef.material must contain ASCII-armored OpenPGP private key"
351
+ )
352
+
353
+ passphrase = None
354
+ if kek.tags and "passphrase" in kek.tags:
355
+ passphrase = kek.tags["passphrase"]
356
+
357
+ with tempfile.TemporaryDirectory() as gpg_home:
358
+ gpg = gnupg.GPG(gnupghome=gpg_home)
359
+ import_result = gpg.import_keys(
360
+ kek.material.decode()
361
+ if isinstance(kek.material, bytes)
362
+ else kek.material
363
+ )
364
+ if not import_result.fingerprints:
365
+ raise RuntimeError("Failed to import OpenPGP private key")
366
+
367
+ dec = gpg.decrypt(wrapped.wrapped, passphrase=passphrase or "")
368
+ if not dec.ok:
369
+ raise RuntimeError(f"GPG decrypt failed: {dec.status}")
370
+
371
+ return bytes(dec.data)
@@ -0,0 +1,5 @@
1
+ from .PGPCrypto import PGPCrypto
2
+
3
+ __all__ = [
4
+ "PGPCrypto",
5
+ ]