Debian Codegraph @

jwt/utils.py

raw
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
25 def base64url_decode(input: Union[bytes, str]) -> bytes:
26 input_bytes = force_bytes(input)
27
28 rem = len(input_bytes) % 4
29
30 if rem > 0:
31 input_bytes += b"=" * (4 - rem)
32
33 return base64.urlsafe_b64decode(input_bytes)
34
35
36 def base64url_encode(input: bytes) -> bytes:
37 return base64.urlsafe_b64encode(input).replace(b"=", b"")
38
39
40 def to_base64url_uint(val: int, *, bit_length: Optional[int] = None) -> bytes:
41 if val < 0:
42 raise ValueError("Must be a positive integer")
43
44 int_bytes = bytes_from_int(val, bit_length=bit_length)
45
46 if len(int_bytes) == 0:
47 int_bytes = b"\x00"
48
49 return base64url_encode(int_bytes)
50
51
52 def from_base64url_uint(val: Union[bytes, str]) -> int:
53 data = base64url_decode(force_bytes(val))
54 return int.from_bytes(data, byteorder="big")
55
56
57 def number_to_bytes(num: int, num_bytes: int) -> bytes:
58 padded_hex = "%0*x" % (2 * num_bytes, num)
59 return binascii.a2b_hex(padded_hex.encode("ascii"))
60
61
62 def bytes_to_number(string: bytes) -> int:
63 return int(binascii.b2a_hex(string), 16)
64
65
66 def bytes_from_int(val: int, *, bit_length: Optional[int] = None) -> bytes:
67 if bit_length is None:
68 bit_length = val.bit_length()
69 byte_length = (bit_length + 7) // 8
70
71 return val.to_bytes(byte_length, "big", signed=False)
72
73
74 def der_to_raw_signature(der_sig: bytes, curve: "EllipticCurve") -> bytes:
75 num_bits = curve.key_size
76 num_bytes = (num_bits + 7) // 8
77
78 r, s = decode_dss_signature(der_sig)
79
80 return number_to_bytes(r, num_bytes) + number_to_bytes(s, num_bytes)
81
82
83 def raw_to_der_signature(raw_sig: bytes, curve: "EllipticCurve") -> bytes:
84 num_bits = curve.key_size
85 num_bytes = (num_bits + 7) // 8
86
87 if len(raw_sig) != 2 * num_bytes:
88 raise ValueError("Invalid signature")
89
90 r = bytes_to_number(raw_sig[:num_bytes])
91 s = bytes_to_number(raw_sig[num_bytes:])
92
93 return bytes(encode_dss_signature(r, s))
94
95
96 # Based on https://github.com/hynek/pem/blob/7ad94db26b0bc21d10953f5dbad3acfdfacf57aa/src/pem/_core.py#L224-L252
97 _PEMS = {
98 b"CERTIFICATE",
99 b"TRUSTED CERTIFICATE",
100 b"PRIVATE KEY",
101 b"PUBLIC KEY",
102 b"ENCRYPTED PRIVATE KEY",
103 b"OPENSSH PRIVATE KEY",
104 b"DSA PRIVATE KEY",
105 b"RSA PRIVATE KEY",
106 b"RSA PUBLIC KEY",
107 b"EC PRIVATE KEY",
108 b"DH PARAMETERS",
109 b"NEW CERTIFICATE REQUEST",
110 b"CERTIFICATE REQUEST",
111 b"SSH2 PUBLIC KEY",
112 b"SSH2 ENCRYPTED PRIVATE KEY",
113 b"X509 CRL",
114 }
115
116 _PEM_RE = re.compile(
117 b"----[- ]BEGIN ("
118 + b"|".join(_PEMS)
119 + b""")[- ]----\r?
120 .+?\r?
121 ----[- ]END \\1[- ]----\r?\n?""",
122 re.DOTALL,
123 )
124
125
126 def is_pem_format(key: bytes) -> bool:
127 return bool(_PEM_RE.search(key))
128
129
130 # Based on https://github.com/pyca/cryptography/blob/bcb70852d577b3f490f015378c75cba74986297b/src/cryptography/hazmat/primitives/serialization/ssh.py#L40-L46
131 _SSH_KEY_FORMATS = (
132 b"ssh-ed25519",
133 b"ssh-rsa",
134 b"ssh-dss",
135 b"ecdsa-sha2-nistp256",
136 b"ecdsa-sha2-nistp384",
137 b"ecdsa-sha2-nistp521",
138 )
139
140
141 def is_ssh_key(key: bytes) -> bool:
142 return key.startswith(_SSH_KEY_FORMATS)