|
1 | | -import re |
2 | 1 | import math |
3 | 2 | import warnings |
4 | 3 |
|
|
18 | 17 | from ..constants import ALGORITHMS |
19 | 18 | from ..exceptions import JWEError, JWKError |
20 | 19 | from ..utils import base64_to_long, base64url_decode, base64url_encode, ensure_binary, long_to_base64 |
| 20 | +from ..utils import is_pem_format, is_ssh_key |
21 | 21 | from .base import Key |
22 | 22 |
|
23 | 23 | _binding = None |
24 | 24 |
|
25 | 25 |
|
26 | | -# Based on https://github.com/jpadilla/pyjwt/commit/9c528670c455b8d948aff95ed50e22940d1ad3fc |
27 | | -# Based on https://github.com/hynek/pem/blob/7ad94db26b0bc21d10953f5dbad3acfdfacf57aa/src/pem/_core.py#L224-L252 |
28 | | -_PEMS = { |
29 | | - b"CERTIFICATE", |
30 | | - b"TRUSTED CERTIFICATE", |
31 | | - b"PRIVATE KEY", |
32 | | - b"PUBLIC KEY", |
33 | | - b"ENCRYPTED PRIVATE KEY", |
34 | | - b"OPENSSH PRIVATE KEY", |
35 | | - b"DSA PRIVATE KEY", |
36 | | - b"RSA PRIVATE KEY", |
37 | | - b"RSA PUBLIC KEY", |
38 | | - b"EC PRIVATE KEY", |
39 | | - b"DH PARAMETERS", |
40 | | - b"NEW CERTIFICATE REQUEST", |
41 | | - b"CERTIFICATE REQUEST", |
42 | | - b"SSH2 PUBLIC KEY", |
43 | | - b"SSH2 ENCRYPTED PRIVATE KEY", |
44 | | - b"X509 CRL", |
45 | | -} |
46 | | - |
47 | | - |
48 | | -_PEM_RE = re.compile( |
49 | | - b"----[- ]BEGIN (" |
50 | | - + b"|".join(_PEMS) |
51 | | - + b""")[- ]----\r? |
52 | | -.+?\r? |
53 | | -----[- ]END \\1[- ]----\r?\n?""", |
54 | | - re.DOTALL, |
55 | | -) |
56 | | - |
57 | | - |
58 | | -def is_pem_format(key): |
59 | | - """ |
60 | | - Return True if the key is PEM format |
61 | | - This function uses the list of valid PEM headers defined in |
62 | | - _PEMS dict. |
63 | | - """ |
64 | | - return bool(_PEM_RE.search(key)) |
65 | | - |
66 | | - |
67 | | -# Based on https://github.com/pyca/cryptography/blob/bcb70852d577b3f490f015378c75cba74986297b/src/cryptography/hazmat/primitives/serialization/ssh.py#L40-L46 |
68 | | -_CERT_SUFFIX = b"-cert-v01@openssh.com" |
69 | | -_SSH_PUBKEY_RC = re.compile(br"\A(\S+)[ \t]+(\S+)") |
70 | | -_SSH_KEY_FORMATS = [ |
71 | | - b"ssh-ed25519", |
72 | | - b"ssh-rsa", |
73 | | - b"ssh-dss", |
74 | | - b"ecdsa-sha2-nistp256", |
75 | | - b"ecdsa-sha2-nistp384", |
76 | | - b"ecdsa-sha2-nistp521", |
77 | | -] |
78 | | - |
79 | | - |
80 | | -def is_ssh_key(key): |
81 | | - """ |
82 | | - Return True if the key is a SSH key |
83 | | - This function uses the list of valid SSH key format defined in |
84 | | - _SSH_KEY_FORMATS dict. |
85 | | - """ |
86 | | - if any(string_value in key for string_value in _SSH_KEY_FORMATS): |
87 | | - return True |
88 | | - |
89 | | - ssh_pubkey_match = _SSH_PUBKEY_RC.match(key) |
90 | | - if ssh_pubkey_match: |
91 | | - key_type = ssh_pubkey_match.group(1) |
92 | | - if _CERT_SUFFIX == key_type[-len(_CERT_SUFFIX) :]: |
93 | | - return True |
94 | | - |
95 | | - return False |
96 | | - |
97 | | - |
98 | 26 | def get_random_bytes(num_bytes): |
99 | 27 | """ |
100 | 28 | Get random bytes |
|
0 commit comments