Debian Codegraph @

tests/keys/__init__.py

raw
1 import json
2 import os
3 from typing import Union
4
5 from jwt.algorithms import has_crypto, AllowedRSAKeys
6 from jwt.utils import base64url_decode
7
8 BASE_PATH = os.path.dirname(os.path.abspath(__file__))
9
10
11 def decode_value(val: Union[str, bytes]) -> int:
12 decoded = base64url_decode(val)
13 return int.from_bytes(decoded, byteorder="big")
14
15
16 def load_hmac_key() -> bytes:
17 with open(os.path.join(BASE_PATH, "jwk_hmac.json")) as infile:
18 keyobj = json.load(infile)
19
20 return base64url_decode(keyobj["k"])
21
22
23 if has_crypto:
24 from cryptography.hazmat.primitives.asymmetric import ec
25 from jwt.algorithms import RSAAlgorithm
26
27 def load_rsa_pub_key() -> AllowedRSAKeys:
28 with open(os.path.join(BASE_PATH, "jwk_rsa_pub.json")) as infile:
29 return RSAAlgorithm.from_jwk(infile.read())
30
31 def load_ec_pub_key_p_521() -> ec.EllipticCurvePublicKey:
32 with open(os.path.join(BASE_PATH, "jwk_ec_pub_P-521.json")) as infile:
33 keyobj = json.load(infile)
34
35 return ec.EllipticCurvePublicNumbers(
36 x=decode_value(keyobj["x"]),
37 y=decode_value(keyobj["y"]),
38 curve=ec.SECP521R1(),
39 ).public_key()
40 else:
41 import sys
42
43 if sys.version_info >= (3, 11):
44 from typing import Never
45 else:
46 from typing_extensions import Never
47
48 def load_rsa_pub_key() -> AllowedRSAKeys:
49 raise RuntimeError("cryptography is not available")
50
51 def load_ec_pub_key_p_521() -> Never: # type: ignore[misc]
52 raise RuntimeError("cryptography is not available")