Debian Codegraph @

jwt/utils.py

raw ◀ ▶
1 Debian patch touch this file
1 import base64
2 import binascii
3 import re
4 from typing import Optional, Union
5
6 try:
7 from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurve
8 from cryptography.hazmat.primitives.asymmetric.utils import (
9 decode_dss_signature,
10 encode_dss_signature,
11 )
12 except ModuleNotFoundError:
13 pass
14
15
16 def force_bytes(value: Union[bytes, str]) -> bytes:
17 if isinstance(value, str):
18 return value.encode("utf-8")
19 elif isinstance(value, bytes):
20 return value
21 else:
22 raise TypeError("Expected a string value")
23
•24 # Translate the standard Base64 alphabet to the URL-safe alphabet so that
25 # callers passing standard-alphabet data (``+`` / ``/``) are normalised before
26 # the decode. From Python 3.15 ``base64.urlsafe_b64decode`` emits a
27 # ``FutureWarning`` for ``+`` / ``/`` and has announced it will eventually
28 # discard those characters, which would silently corrupt the decoded bytes.
29 # Normalising up front keeps valid URL-safe input warning-free and keeps the
30 # historical lenient handling of standard-alphabet input deterministic.
31 _STD_TO_URLSAFE = bytes.maketrans(b"+/", b"-_")
32
33
34 def base64url_decode(input: Union[bytes, str]) -> bytes:
•35 input_bytes = force_bytes(input).translate(_STD_TO_URLSAFE)
36
37 rem = len(input_bytes) % 4
38
39 if rem > 0:
40 input_bytes += b"=" * (4 - rem)
41
42 return base64.urlsafe_b64decode(input_bytes)
43
44
45 def base64url_encode(input: bytes) -> bytes:
46 return base64.urlsafe_b64encode(input).replace(b"=", b"")
47
48
49 def to_base64url_uint(val: int, *, bit_length: Optional[int] = None) -> bytes:
50 if val < 0:
51 raise ValueError("Must be a positive integer")
52
53 int_bytes = bytes_from_int(val, bit_length=bit_length)
54
55 if len(int_bytes) == 0:
56 int_bytes = b"\x00"
57
58 return base64url_encode(int_bytes)
59
60
61 def from_base64url_uint(val: Union[bytes, str]) -> int:
62 data = base64url_decode(force_bytes(val))
63 return int.from_bytes(data, byteorder="big")
64
65
66 def number_to_bytes(num: int, num_bytes: int) -> bytes:
67 padded_hex = "%0*x" % (2 * num_bytes, num)
68 return binascii.a2b_hex(padded_hex.encode("ascii"))
69
70
71 def bytes_to_number(string: bytes) -> int:
72 return int(binascii.b2a_hex(string), 16)
73
74
75 def bytes_from_int(val: int, *, bit_length: Optional[int] = None) -> bytes:
76 if bit_length is None:
77 bit_length = val.bit_length()
78 byte_length = (bit_length + 7) // 8
79
80 return val.to_bytes(byte_length, "big", signed=False)
81
82
83 def der_to_raw_signature(der_sig: bytes, curve: "EllipticCurve") -> bytes:
84 num_bits = curve.key_size
85 num_bytes = (num_bits + 7) // 8
86
87 r, s = decode_dss_signature(der_sig)
88
89 return number_to_bytes(r, num_bytes) + number_to_bytes(s, num_bytes)
90
91
92 def raw_to_der_signature(raw_sig: bytes, curve: "EllipticCurve") -> bytes:
93 num_bits = curve.key_size
94 num_bytes = (num_bits + 7) // 8
95
96 if len(raw_sig) != 2 * num_bytes:
97 raise ValueError("Invalid signature")
98
99 r = bytes_to_number(raw_sig[:num_bytes])
100 s = bytes_to_number(raw_sig[num_bytes:])
101
102 return bytes(encode_dss_signature(r, s))
103
104
105 # Based on https://github.com/hynek/pem/blob/7ad94db26b0bc21d10953f5dbad3acfdfacf57aa/src/pem/_core.py#L224-L252
106 _PEMS = {
107 b"CERTIFICATE",
108 b"TRUSTED CERTIFICATE",
109 b"PRIVATE KEY",
110 b"PUBLIC KEY",
111 b"ENCRYPTED PRIVATE KEY",
112 b"OPENSSH PRIVATE KEY",
113 b"DSA PRIVATE KEY",
114 b"RSA PRIVATE KEY",
115 b"RSA PUBLIC KEY",
116 b"EC PRIVATE KEY",
117 b"DH PARAMETERS",
118 b"NEW CERTIFICATE REQUEST",
119 b"CERTIFICATE REQUEST",
120 b"SSH2 PUBLIC KEY",
121 b"SSH2 ENCRYPTED PRIVATE KEY",
122 b"X509 CRL",
123 }
124
125 # Accept PEM formatting variants that the cryptography loader accepts, while
126 # retaining the explicit asymmetric-key marker check.
127 _PEM_MARKER_RE = re.compile(
128 b"(?=(----[- ](BEGIN|END) (" + b"|".join(_PEMS) + b")[- ]----))"
129 )
130
131
132 def is_pem_format(key: bytes) -> bool:
133 begin_markers: dict[bytes, int] = {}
134 for marker in _PEM_MARKER_RE.finditer(key):
135 marker_type, label = marker.group(2), marker.group(3)
136 if marker_type == b"BEGIN":
137 begin_markers[label] = marker.start(1) + len(marker.group(1))
138 elif label in begin_markers and begin_markers[label] < marker.start(1):
139 return True
140 return False
141
142
143 # Based on https://github.com/pyca/cryptography/blob/bcb70852d577b3f490f015378c75cba74986297b/src/cryptography/hazmat/primitives/serialization/ssh.py#L40-L46
144 _SSH_KEY_FORMATS = (
145 b"ssh-ed25519",
146 b"ssh-rsa",
147 b"ssh-dss",
148 b"ecdsa-sha2-nistp256",
149 b"ecdsa-sha2-nistp384",
150 b"ecdsa-sha2-nistp521",
151 )
152
153
154 def is_ssh_key(key: bytes) -> bool:
155 return key.startswith(_SSH_KEY_FORMATS)