swarmauri_crypto_jwe 0.2.0.dev3__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- swarmauri_crypto_jwe/JweCrypto.py +424 -0
- swarmauri_crypto_jwe/__init__.py +3 -0
- swarmauri_crypto_jwe-0.2.0.dev3.dist-info/LICENSE +201 -0
- swarmauri_crypto_jwe-0.2.0.dev3.dist-info/METADATA +112 -0
- swarmauri_crypto_jwe-0.2.0.dev3.dist-info/RECORD +6 -0
- swarmauri_crypto_jwe-0.2.0.dev3.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,424 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import base64
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import zlib
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from typing import Any, Dict, Iterable, Mapping, Optional, Tuple, Union
|
|
9
|
+
|
|
10
|
+
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
|
11
|
+
from cryptography.hazmat.primitives import hashes, serialization
|
|
12
|
+
from cryptography.hazmat.primitives.kdf.concatkdf import ConcatKDFHash
|
|
13
|
+
from cryptography.hazmat.primitives.asymmetric import rsa, padding, ec, x25519
|
|
14
|
+
from cryptography.hazmat.primitives.serialization import (
|
|
15
|
+
load_pem_public_key,
|
|
16
|
+
load_pem_private_key,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
from swarmauri_core.crypto.types import JWAAlg
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _b64u(b: bytes) -> str:
|
|
23
|
+
return base64.urlsafe_b64encode(b).rstrip(b"=").decode("ascii")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _b64u_dec(s: str) -> bytes:
|
|
27
|
+
pad = "=" * ((4 - (len(s) % 4)) % 4)
|
|
28
|
+
return base64.urlsafe_b64decode(s + pad)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _json_dumps(obj: Any) -> bytes:
|
|
32
|
+
return json.dumps(
|
|
33
|
+
obj, separators=(",", ":"), ensure_ascii=False, sort_keys=False
|
|
34
|
+
).encode("utf-8")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _cek_len_for_enc(enc: JWAAlg) -> int:
|
|
38
|
+
if enc == JWAAlg.A128GCM:
|
|
39
|
+
return 16
|
|
40
|
+
if enc == JWAAlg.A192GCM:
|
|
41
|
+
return 24
|
|
42
|
+
if enc == JWAAlg.A256GCM:
|
|
43
|
+
return 32
|
|
44
|
+
raise ValueError(f"Unsupported enc '{enc.value}'. Use A128GCM/A192GCM/A256GCM.")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _hash_for_oaep(alg: JWAAlg):
|
|
48
|
+
if alg == JWAAlg.RSA_OAEP:
|
|
49
|
+
return hashes.SHA1()
|
|
50
|
+
if alg == JWAAlg.RSA_OAEP_256:
|
|
51
|
+
return hashes.SHA256()
|
|
52
|
+
raise ValueError(f"Unsupported RSA OAEP alg '{alg.value}'.")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _rand(n: int) -> bytes:
|
|
56
|
+
return os.urandom(n)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _compute_aad(protected_b64: str, aad_bytes: Optional[bytes]) -> bytes:
|
|
60
|
+
if not aad_bytes:
|
|
61
|
+
return protected_b64.encode("ascii")
|
|
62
|
+
return (protected_b64 + "." + _b64u(aad_bytes)).encode("ascii")
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _jwk_ec_public_numbers(jwk: Mapping[str, Any]) -> ec.EllipticCurvePublicNumbers:
|
|
66
|
+
crv = jwk.get("crv")
|
|
67
|
+
curve_map = {
|
|
68
|
+
"P-256": ec.SECP256R1(),
|
|
69
|
+
"P-384": ec.SECP384R1(),
|
|
70
|
+
"P-521": ec.SECP521R1(),
|
|
71
|
+
}
|
|
72
|
+
if crv not in curve_map:
|
|
73
|
+
raise ValueError(f"Unsupported EC curve in JWK: {crv}")
|
|
74
|
+
x = int.from_bytes(_b64u_dec(jwk["x"]), "big")
|
|
75
|
+
y = int.from_bytes(_b64u_dec(jwk["y"]), "big")
|
|
76
|
+
return ec.EllipticCurvePublicNumbers(x, y, curve_map[crv])
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _ec_jwk_from_public_key(pk: ec.EllipticCurvePublicKey) -> Dict[str, Any]:
|
|
80
|
+
numbers = pk.public_numbers()
|
|
81
|
+
crv = pk.curve.name
|
|
82
|
+
crv_map = {"secp256r1": "P-256", "secp384r1": "P-384", "secp521r1": "P-521"}
|
|
83
|
+
if crv not in crv_map:
|
|
84
|
+
raise ValueError(f"Unsupported EC curve: {crv}")
|
|
85
|
+
size = (pk.curve.key_size + 7) // 8
|
|
86
|
+
x = numbers.x.to_bytes(size, "big")
|
|
87
|
+
y = numbers.y.to_bytes(size, "big")
|
|
88
|
+
return {"kty": "EC", "crv": crv_map[crv], "x": _b64u(x), "y": _b64u(y)}
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _x25519_jwk_from_public_key(pk: x25519.X25519PublicKey) -> Dict[str, Any]:
|
|
92
|
+
raw = pk.public_bytes(
|
|
93
|
+
encoding=serialization.Encoding.Raw, format=serialization.PublicFormat.Raw
|
|
94
|
+
)
|
|
95
|
+
return {"kty": "OKP", "crv": "X25519", "x": _b64u(raw)}
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _load_rsa_public(key: Any) -> rsa.RSAPublicKey:
|
|
99
|
+
if isinstance(key, rsa.RSAPublicKey):
|
|
100
|
+
return key
|
|
101
|
+
if isinstance(key, (bytes, bytearray, str)):
|
|
102
|
+
data = key if isinstance(key, (bytes, bytearray)) else key.encode("utf-8")
|
|
103
|
+
pk = load_pem_public_key(data)
|
|
104
|
+
if not isinstance(pk, rsa.RSAPublicKey):
|
|
105
|
+
raise TypeError("PEM provided is not an RSA public key")
|
|
106
|
+
return pk
|
|
107
|
+
if isinstance(key, Mapping) and key.get("kty") == "RSA":
|
|
108
|
+
n = int.from_bytes(_b64u_dec(key["n"]), "big")
|
|
109
|
+
e = int.from_bytes(_b64u_dec(key["e"]), "big")
|
|
110
|
+
return rsa.RSAPublicNumbers(e, n).public_key()
|
|
111
|
+
raise TypeError("Unsupported RSA public key format.")
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _load_rsa_private(
|
|
115
|
+
key: Any, password: Optional[Union[str, bytes]] = None
|
|
116
|
+
) -> rsa.RSAPrivateKey:
|
|
117
|
+
if isinstance(key, rsa.RSAPrivateKey):
|
|
118
|
+
return key
|
|
119
|
+
pwd = None
|
|
120
|
+
if isinstance(password, str):
|
|
121
|
+
pwd = password.encode("utf-8")
|
|
122
|
+
elif isinstance(password, (bytes, bytearray)):
|
|
123
|
+
pwd = bytes(password)
|
|
124
|
+
if isinstance(key, (bytes, bytearray, str)):
|
|
125
|
+
data = key if isinstance(key, (bytes, bytearray)) else key.encode("utf-8")
|
|
126
|
+
sk = load_pem_private_key(data, password=pwd)
|
|
127
|
+
if not isinstance(sk, rsa.RSAPrivateKey):
|
|
128
|
+
raise TypeError("PEM provided is not an RSA private key")
|
|
129
|
+
return sk
|
|
130
|
+
raise TypeError("Unsupported RSA private key format.")
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _load_ecdh_recipient_public(jwk_or_pem: Any) -> Tuple[str, Any]:
|
|
134
|
+
if isinstance(jwk_or_pem, Mapping):
|
|
135
|
+
kty = jwk_or_pem.get("kty")
|
|
136
|
+
if kty == "EC":
|
|
137
|
+
pn = _jwk_ec_public_numbers(jwk_or_pem)
|
|
138
|
+
return jwk_or_pem["crv"], pn.public_key()
|
|
139
|
+
if kty == "OKP" and jwk_or_pem.get("crv") == "X25519":
|
|
140
|
+
x = _b64u_dec(jwk_or_pem["x"])
|
|
141
|
+
return "X25519", x25519.X25519PublicKey.from_public_bytes(x)
|
|
142
|
+
raise ValueError(
|
|
143
|
+
f"Unsupported JWK kty/crv for ECDH-ES: {kty}/{jwk_or_pem.get('crv')}"
|
|
144
|
+
)
|
|
145
|
+
if isinstance(jwk_or_pem, (bytes, bytearray, str)):
|
|
146
|
+
data = (
|
|
147
|
+
jwk_or_pem
|
|
148
|
+
if isinstance(jwk_or_pem, (bytes, bytearray))
|
|
149
|
+
else jwk_or_pem.encode("utf-8")
|
|
150
|
+
)
|
|
151
|
+
pk = load_pem_public_key(data)
|
|
152
|
+
if isinstance(pk, ec.EllipticCurvePublicKey):
|
|
153
|
+
crv = pk.curve.name
|
|
154
|
+
if crv == "secp256r1":
|
|
155
|
+
return "P-256", pk
|
|
156
|
+
if crv == "secp384r1":
|
|
157
|
+
return "P-384", pk
|
|
158
|
+
if crv == "secp521r1":
|
|
159
|
+
return "P-521", pk
|
|
160
|
+
raise ValueError(f"Unsupported EC curve: {crv}")
|
|
161
|
+
raise TypeError("PEM must be an EC public key for ECDH-ES.")
|
|
162
|
+
raise TypeError("Unsupported recipient public key format for ECDH-ES.")
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _concat_kdf(
|
|
166
|
+
z: bytes,
|
|
167
|
+
enc: JWAAlg,
|
|
168
|
+
hash_alg=hashes.SHA256(),
|
|
169
|
+
apu: Optional[bytes] = None,
|
|
170
|
+
apv: Optional[bytes] = None,
|
|
171
|
+
) -> bytes:
|
|
172
|
+
keydatalen_bits = _cek_len_for_enc(enc) * 8
|
|
173
|
+
alg_id = _jwe_alg_id(enc)
|
|
174
|
+
ckdf = ConcatKDFHash(
|
|
175
|
+
algorithm=hash_alg,
|
|
176
|
+
length=keydatalen_bits // 8,
|
|
177
|
+
otherinfo=alg_id + (apu or b"") + (apv or b""),
|
|
178
|
+
)
|
|
179
|
+
return ckdf.derive(z)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _jwe_alg_id(enc: JWAAlg) -> bytes:
|
|
183
|
+
enc_b = enc.value.encode("ascii")
|
|
184
|
+
return len(enc_b).to_bytes(4, "big") + enc_b
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
JWECompact = str
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
@dataclass
|
|
191
|
+
class JweDecryptResult:
|
|
192
|
+
header: Dict[str, Any]
|
|
193
|
+
plaintext: bytes
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
class JweCrypto:
|
|
197
|
+
"""Utility class for JSON Web Encryption (RFC 7516, RFC 7518)."""
|
|
198
|
+
|
|
199
|
+
async def encrypt_compact(
|
|
200
|
+
self,
|
|
201
|
+
*,
|
|
202
|
+
payload: Union[bytes, str, Mapping[str, Any]],
|
|
203
|
+
alg: JWAAlg,
|
|
204
|
+
enc: JWAAlg,
|
|
205
|
+
key: Mapping[str, Any],
|
|
206
|
+
kid: Optional[str] = None,
|
|
207
|
+
header_extra: Optional[Mapping[str, Any]] = None,
|
|
208
|
+
aad: Optional[Union[bytes, str]] = None,
|
|
209
|
+
) -> JWECompact:
|
|
210
|
+
if isinstance(payload, str):
|
|
211
|
+
pt = payload.encode("utf-8")
|
|
212
|
+
elif isinstance(payload, (bytes, bytearray)):
|
|
213
|
+
pt = bytes(payload)
|
|
214
|
+
else:
|
|
215
|
+
pt = _json_dumps(payload)
|
|
216
|
+
|
|
217
|
+
protected: Dict[str, Any] = {"alg": alg.value, "enc": enc.value}
|
|
218
|
+
if kid:
|
|
219
|
+
protected["kid"] = kid
|
|
220
|
+
if header_extra:
|
|
221
|
+
protected.update(dict(header_extra))
|
|
222
|
+
|
|
223
|
+
if protected.get("zip") == "DEF":
|
|
224
|
+
pt = zlib.compress(pt)
|
|
225
|
+
|
|
226
|
+
cek: bytes
|
|
227
|
+
encrypted_key_b64 = ""
|
|
228
|
+
epk_header: Optional[Dict[str, Any]] = None
|
|
229
|
+
|
|
230
|
+
if alg == JWAAlg.DIR:
|
|
231
|
+
secret = key.get("k")
|
|
232
|
+
secret_b = (
|
|
233
|
+
secret.encode("utf-8") if isinstance(secret, str) else bytes(secret)
|
|
234
|
+
)
|
|
235
|
+
if len(secret_b) != _cek_len_for_enc(enc):
|
|
236
|
+
raise ValueError(
|
|
237
|
+
f"'dir' key size must equal enc key size ({_cek_len_for_enc(enc)} bytes)"
|
|
238
|
+
)
|
|
239
|
+
cek = secret_b
|
|
240
|
+
elif alg in (JWAAlg.RSA_OAEP, JWAAlg.RSA_OAEP_256):
|
|
241
|
+
cek = _rand(_cek_len_for_enc(enc))
|
|
242
|
+
pk = _load_rsa_public(key.get("pub") or key)
|
|
243
|
+
hash_alg = _hash_for_oaep(alg)
|
|
244
|
+
ekey = pk.encrypt(
|
|
245
|
+
cek,
|
|
246
|
+
padding.OAEP(
|
|
247
|
+
mgf=padding.MGF1(algorithm=hash_alg),
|
|
248
|
+
algorithm=hash_alg,
|
|
249
|
+
label=None,
|
|
250
|
+
),
|
|
251
|
+
)
|
|
252
|
+
encrypted_key_b64 = _b64u(ekey)
|
|
253
|
+
elif alg == JWAAlg.ECDH_ES:
|
|
254
|
+
crv, rpk = _load_ecdh_recipient_public(key.get("pub") or key)
|
|
255
|
+
if crv == "X25519":
|
|
256
|
+
esk = x25519.X25519PrivateKey.generate()
|
|
257
|
+
epk = esk.public_key()
|
|
258
|
+
z = esk.exchange(rpk) # type: ignore[arg-type]
|
|
259
|
+
epk_header = _x25519_jwk_from_public_key(epk)
|
|
260
|
+
else:
|
|
261
|
+
curve = {
|
|
262
|
+
"P-256": ec.SECP256R1(),
|
|
263
|
+
"P-384": ec.SECP384R1(),
|
|
264
|
+
"P-521": ec.SECP521R1(),
|
|
265
|
+
}[crv]
|
|
266
|
+
esk = ec.generate_private_key(curve)
|
|
267
|
+
epk = esk.public_key()
|
|
268
|
+
z = esk.exchange(ec.ECDH(), rpk) # type: ignore[arg-type]
|
|
269
|
+
epk_header = _ec_jwk_from_public_key(epk)
|
|
270
|
+
apu_b = None
|
|
271
|
+
apv_b = None
|
|
272
|
+
if "apu" in (header_extra or {}):
|
|
273
|
+
apu_b = (
|
|
274
|
+
_b64u_dec(header_extra["apu"])
|
|
275
|
+
if isinstance(header_extra["apu"], str)
|
|
276
|
+
else header_extra["apu"]
|
|
277
|
+
)
|
|
278
|
+
if "apv" in (header_extra or {}):
|
|
279
|
+
apv_b = (
|
|
280
|
+
_b64u_dec(header_extra["apv"])
|
|
281
|
+
if isinstance(header_extra["apv"], str)
|
|
282
|
+
else header_extra["apv"]
|
|
283
|
+
)
|
|
284
|
+
cek = _concat_kdf(z, enc, hashes.SHA256(), apu_b, apv_b)
|
|
285
|
+
protected["epk"] = epk_header
|
|
286
|
+
else:
|
|
287
|
+
raise ValueError(f"Unsupported alg '{alg.value}'")
|
|
288
|
+
|
|
289
|
+
iv = _rand(12)
|
|
290
|
+
aadd = _ensure_bytes(aad) if aad is not None else None
|
|
291
|
+
|
|
292
|
+
protected_b64 = _b64u(_json_dumps(protected))
|
|
293
|
+
aead_aad = _compute_aad(protected_b64, aadd)
|
|
294
|
+
|
|
295
|
+
aesgcm = AESGCM(cek)
|
|
296
|
+
ct = aesgcm.encrypt(iv, pt, aead_aad)
|
|
297
|
+
ciphertext, tag = ct[:-16], ct[-16:]
|
|
298
|
+
|
|
299
|
+
return ".".join(
|
|
300
|
+
[
|
|
301
|
+
protected_b64,
|
|
302
|
+
encrypted_key_b64,
|
|
303
|
+
_b64u(iv),
|
|
304
|
+
_b64u(ciphertext),
|
|
305
|
+
_b64u(tag),
|
|
306
|
+
]
|
|
307
|
+
)
|
|
308
|
+
|
|
309
|
+
async def decrypt_compact(
|
|
310
|
+
self,
|
|
311
|
+
jwe: JWECompact,
|
|
312
|
+
*,
|
|
313
|
+
dir_key: Optional[Union[bytes, str]] = None,
|
|
314
|
+
rsa_private_pem: Optional[Union[str, bytes]] = None,
|
|
315
|
+
rsa_private_password: Optional[Union[str, bytes]] = None,
|
|
316
|
+
ecdh_private_key: Optional[Any] = None,
|
|
317
|
+
expected_algs: Optional[Iterable[JWAAlg]] = None,
|
|
318
|
+
expected_encs: Optional[Iterable[JWAAlg]] = None,
|
|
319
|
+
aad: Optional[Union[bytes, str]] = None,
|
|
320
|
+
) -> JweDecryptResult:
|
|
321
|
+
parts = jwe.split(".")
|
|
322
|
+
if len(parts) != 5:
|
|
323
|
+
raise ValueError("Invalid JWE compact: expected 5 dot-separated parts.")
|
|
324
|
+
b64_prot, b64_ekey, b64_iv, b64_ct, b64_tag = parts
|
|
325
|
+
|
|
326
|
+
header = json.loads(_b64u_dec(b64_prot))
|
|
327
|
+
try:
|
|
328
|
+
alg = JWAAlg(header.get("alg"))
|
|
329
|
+
enc = JWAAlg(header.get("enc"))
|
|
330
|
+
except Exception as exc:
|
|
331
|
+
raise ValueError("JWE header missing 'alg' or 'enc'.") from exc
|
|
332
|
+
if expected_algs and alg not in set(expected_algs):
|
|
333
|
+
raise ValueError(f"Unexpected alg '{alg.value}'.")
|
|
334
|
+
if expected_encs and enc not in set(expected_encs):
|
|
335
|
+
raise ValueError(f"Unexpected enc '{enc.value}'.")
|
|
336
|
+
|
|
337
|
+
iv = _b64u_dec(b64_iv)
|
|
338
|
+
if len(iv) != 12:
|
|
339
|
+
raise ValueError("Invalid IV length for AES-GCM (must be 96-bit).")
|
|
340
|
+
ciphertext = _b64u_dec(b64_ct)
|
|
341
|
+
tag = _b64u_dec(b64_tag)
|
|
342
|
+
aadd = _ensure_bytes(aad) if aad is not None else None
|
|
343
|
+
aead_aad = _compute_aad(b64_prot, aadd)
|
|
344
|
+
|
|
345
|
+
if alg == JWAAlg.DIR:
|
|
346
|
+
if dir_key is None:
|
|
347
|
+
raise ValueError("dir_key is required for alg='dir'.")
|
|
348
|
+
cek = (
|
|
349
|
+
dir_key.encode("utf-8") if isinstance(dir_key, str) else bytes(dir_key)
|
|
350
|
+
)
|
|
351
|
+
if len(cek) != _cek_len_for_enc(enc):
|
|
352
|
+
raise ValueError("dir_key length mismatch for enc.")
|
|
353
|
+
elif alg in (JWAAlg.RSA_OAEP, JWAAlg.RSA_OAEP_256):
|
|
354
|
+
if rsa_private_pem is None:
|
|
355
|
+
raise ValueError("rsa_private_pem is required for RSA-OAEP decryption.")
|
|
356
|
+
sk = _load_rsa_private(rsa_private_pem, password=rsa_private_password)
|
|
357
|
+
ekey = _b64u_dec(b64_ekey)
|
|
358
|
+
hash_alg = _hash_for_oaep(alg)
|
|
359
|
+
cek = sk.decrypt(
|
|
360
|
+
ekey,
|
|
361
|
+
padding.OAEP(
|
|
362
|
+
mgf=padding.MGF1(algorithm=hash_alg), algorithm=hash_alg, label=None
|
|
363
|
+
),
|
|
364
|
+
)
|
|
365
|
+
elif alg == JWAAlg.ECDH_ES:
|
|
366
|
+
if ecdh_private_key is None:
|
|
367
|
+
raise ValueError("ecdh_private_key is required for ECDH-ES decryption.")
|
|
368
|
+
epk = header.get("epk")
|
|
369
|
+
if not isinstance(epk, Mapping):
|
|
370
|
+
raise ValueError("Missing/invalid 'epk' in JWE header for ECDH-ES.")
|
|
371
|
+
if epk.get("kty") == "OKP" and epk.get("crv") == "X25519":
|
|
372
|
+
if not isinstance(ecdh_private_key, x25519.X25519PrivateKey):
|
|
373
|
+
raise TypeError("ECDH-ES with X25519 requires an X25519PrivateKey.")
|
|
374
|
+
z = ecdh_private_key.exchange(
|
|
375
|
+
x25519.X25519PublicKey.from_public_bytes(_b64u_dec(epk["x"]))
|
|
376
|
+
)
|
|
377
|
+
elif epk.get("kty") == "EC":
|
|
378
|
+
crv = epk.get("crv")
|
|
379
|
+
curve = {
|
|
380
|
+
"P-256": ec.SECP256R1(),
|
|
381
|
+
"P-384": ec.SECP384R1(),
|
|
382
|
+
"P-521": ec.SECP521R1(),
|
|
383
|
+
}.get(crv)
|
|
384
|
+
if curve is None:
|
|
385
|
+
raise ValueError(f"Unsupported EC curve in epk: {crv}")
|
|
386
|
+
if not isinstance(ecdh_private_key, ec.EllipticCurvePrivateKey):
|
|
387
|
+
raise TypeError(
|
|
388
|
+
"ECDH-ES with EC requires an EllipticCurvePrivateKey."
|
|
389
|
+
)
|
|
390
|
+
x = int.from_bytes(_b64u_dec(epk["x"]), "big")
|
|
391
|
+
y = int.from_bytes(_b64u_dec(epk["y"]), "big")
|
|
392
|
+
rpk = ec.EllipticCurvePublicNumbers(x, y, curve).public_key()
|
|
393
|
+
z = ecdh_private_key.exchange(ec.ECDH(), rpk)
|
|
394
|
+
else:
|
|
395
|
+
raise ValueError("Unsupported 'epk' kty/crv.")
|
|
396
|
+
apu_b = _b64u_dec(header["apu"]) if "apu" in header else None
|
|
397
|
+
apv_b = _b64u_dec(header["apv"]) if "apv" in header else None
|
|
398
|
+
cek = _concat_kdf(z, enc, hashes.SHA256(), apu_b, apv_b)
|
|
399
|
+
else:
|
|
400
|
+
raise ValueError(f"Unsupported alg '{alg.value}'")
|
|
401
|
+
|
|
402
|
+
aesgcm = AESGCM(cek)
|
|
403
|
+
try:
|
|
404
|
+
pt = aesgcm.decrypt(iv, ciphertext + tag, aead_aad)
|
|
405
|
+
except Exception as exc: # noqa: BLE001
|
|
406
|
+
raise ValueError(
|
|
407
|
+
"JWE decryption failed (invalid tag or wrong key)."
|
|
408
|
+
) from exc
|
|
409
|
+
|
|
410
|
+
if header.get("zip") == "DEF":
|
|
411
|
+
try:
|
|
412
|
+
pt = zlib.decompress(pt)
|
|
413
|
+
except Exception as exc: # noqa: BLE001
|
|
414
|
+
raise ValueError(f"Failed to decompress (zip=DEF): {exc}") from exc
|
|
415
|
+
|
|
416
|
+
return JweDecryptResult(header=header, plaintext=pt)
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
def _ensure_bytes(v: Union[str, bytes, bytearray]) -> bytes:
|
|
420
|
+
if isinstance(v, (bytes, bytearray)):
|
|
421
|
+
return bytes(v)
|
|
422
|
+
if isinstance(v, str):
|
|
423
|
+
return v.encode("utf-8")
|
|
424
|
+
raise TypeError("Expected bytes or str")
|
|
@@ -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,112 @@
|
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
|
+
Name: swarmauri_crypto_jwe
|
|
3
|
+
Version: 0.2.0.dev3
|
|
4
|
+
Summary: RFC 7516/7518 compliant JWE 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
|
+
Provides-Extra: json
|
|
20
|
+
Requires-Dist: cbor2 ; extra == "cbor"
|
|
21
|
+
Requires-Dist: cryptography (>=41)
|
|
22
|
+
Requires-Dist: swarmauri_base
|
|
23
|
+
Requires-Dist: swarmauri_core
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+

|
|
27
|
+
|
|
28
|
+
<p align="center">
|
|
29
|
+
<a href="https://pypi.org/project/swarmauri_crypto_jwe/"><img src="https://img.shields.io/pypi/dm/swarmauri_crypto_jwe" alt="PyPI - Downloads"/></a>
|
|
30
|
+
<a href="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/standards/swarmauri_crypto_jwe/"><img alt="Hits" src="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/standards/swarmauri_crypto_jwe.svg"/></a>
|
|
31
|
+
<a href="https://pypi.org/project/swarmauri_crypto_jwe/"><img src="https://img.shields.io/pypi/pyversions/swarmauri_crypto_jwe" alt="PyPI - Python Version"/></a>
|
|
32
|
+
<a href="https://pypi.org/project/swarmauri_crypto_jwe/"><img src="https://img.shields.io/pypi/l/swarmauri_crypto_jwe" alt="PyPI - License"/></a>
|
|
33
|
+
<a href="https://pypi.org/project/swarmauri_crypto_jwe/"><img src="https://img.shields.io/pypi/v/swarmauri_crypto_jwe?label=swarmauri_crypto_jwe&color=green" alt="PyPI - swarmauri_crypto_jwe"/></a>
|
|
34
|
+
</p>
|
|
35
|
+
|
|
36
|
+
---
|
|
37
|
+
|
|
38
|
+
## Swarmauri Crypto JWE
|
|
39
|
+
|
|
40
|
+
JSON Web Encryption (JWE) provider implementing RFC 7516 and RFC 7518 compliant encryption and decryption helpers.
|
|
41
|
+
|
|
42
|
+
- Supports `dir`, `RSA-OAEP`, `RSA-OAEP-256`, and `ECDH-ES`
|
|
43
|
+
- Supports `A128GCM`, `A192GCM`, and `A256GCM`
|
|
44
|
+
- Optional compression (`zip` = `DEF`) and Additional Authenticated Data (AAD)
|
|
45
|
+
|
|
46
|
+
### Installation
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
pip install swarmauri_crypto_jwe
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
### Usage
|
|
53
|
+
|
|
54
|
+
The helpers are asynchronous and return compact JWE strings that can be
|
|
55
|
+
decrypted back into their original plaintext. A typical flow is:
|
|
56
|
+
|
|
57
|
+
1. Generate or load the key material for the chosen algorithm.
|
|
58
|
+
2. Instantiate `JweCrypto`.
|
|
59
|
+
3. Call `encrypt_compact` with the payload, algorithm, and key details.
|
|
60
|
+
4. Call `decrypt_compact` with the resulting JWE and the corresponding
|
|
61
|
+
private key.
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
import asyncio
|
|
65
|
+
from cryptography.hazmat.primitives import serialization
|
|
66
|
+
from cryptography.hazmat.primitives.asymmetric import rsa
|
|
67
|
+
from swarmauri_crypto_jwe import JweCrypto
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
async def main() -> None:
|
|
71
|
+
crypto = JweCrypto()
|
|
72
|
+
|
|
73
|
+
sk = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
|
74
|
+
pk_pem = sk.public_key().public_bytes(
|
|
75
|
+
encoding=serialization.Encoding.PEM,
|
|
76
|
+
format=serialization.PublicFormat.SubjectPublicKeyInfo,
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
jwe = await crypto.encrypt_compact(
|
|
80
|
+
payload=b"secret",
|
|
81
|
+
alg="RSA-OAEP-256",
|
|
82
|
+
enc="A256GCM",
|
|
83
|
+
key={"pub": pk_pem},
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
result = await crypto.decrypt_compact(
|
|
87
|
+
jwe,
|
|
88
|
+
rsa_private_pem=sk.private_bytes(
|
|
89
|
+
encoding=serialization.Encoding.PEM,
|
|
90
|
+
format=serialization.PrivateFormat.PKCS8,
|
|
91
|
+
encryption_algorithm=serialization.NoEncryption(),
|
|
92
|
+
),
|
|
93
|
+
)
|
|
94
|
+
assert result.plaintext == b"secret"
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
asyncio.run(main())
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
**Parameters**
|
|
101
|
+
|
|
102
|
+
- `alg` – key management algorithm such as `RSA-OAEP-256` or `dir`.
|
|
103
|
+
- `enc` – content encryption algorithm like `A256GCM`.
|
|
104
|
+
- `key` – mapping containing the public key or direct symmetric key
|
|
105
|
+
material.
|
|
106
|
+
- Decryption requires the matching private key via `rsa_private_pem`,
|
|
107
|
+
`dir_key`, or `ecdh_private_key`.
|
|
108
|
+
|
|
109
|
+
## Entry point
|
|
110
|
+
|
|
111
|
+
The provider is registered under the `swarmauri.cryptos` entry point as `JweCrypto`.
|
|
112
|
+
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
swarmauri_crypto_jwe/JweCrypto.py,sha256=zvhw81ups1URUT__0czZRa-1XtQmfqTp8d2yc5NBNLc,15646
|
|
2
|
+
swarmauri_crypto_jwe/__init__.py,sha256=JLx3A6g6dynWthrpPd-F6vh9j80rPQW8Kde_8VADRJM,58
|
|
3
|
+
swarmauri_crypto_jwe-0.2.0.dev3.dist-info/LICENSE,sha256=djUXOlCxLVszShEpZXshZ7v33G-2qIC_j9KXpWKZSzQ,11359
|
|
4
|
+
swarmauri_crypto_jwe-0.2.0.dev3.dist-info/METADATA,sha256=48oxR7eQBwilkdlKYYo6w_0BOE2SnyHtXw8FXKLqsmc,4167
|
|
5
|
+
swarmauri_crypto_jwe-0.2.0.dev3.dist-info/WHEEL,sha256=b4K_helf-jlQoXBBETfwnf4B04YC67LOev0jo4fX5m8,88
|
|
6
|
+
swarmauri_crypto_jwe-0.2.0.dev3.dist-info/RECORD,,
|