Skip to content

Commit e699c06

Browse files
committed
feat: safest cert parsing
1 parent c7de5b2 commit e699c06

File tree

1 file changed

+23
-6
lines changed

1 file changed

+23
-6
lines changed

pyeudiw/jwk/parse.py

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -59,11 +59,18 @@ def parse_certificate(cert: str | bytes) -> JWK:
5959
:rtype: JWK
6060
"""
6161

62-
if type(cert) == bytes or type(cert) == str and not cert.startswith("-----BEGIN CERTIFICATE-----"):
63-
cert = DER_cert_to_PEM_cert(cert)
64-
65-
return parse_pem(cert)
66-
62+
parse_methods = [
63+
lambda x: parse_pem(x),
64+
lambda x: parse_pem(DER_cert_to_PEM_cert(x)),
65+
]
66+
67+
for method in parse_methods:
68+
try:
69+
return method(cert)
70+
except Exception:
71+
continue
72+
73+
raise InvalidJwk(f"unable to parse key from pem: {cert}")
6774

6875
def parse_b64der(b64der: str) -> JWK:
6976
"""
@@ -88,4 +95,14 @@ def parse_x5c_keys(x5c: list[str]) -> list[JWK]:
8895
:rtype: JWK
8996
"""
9097

91-
return [parse_pem(pem) for pem in x5c]
98+
parse_methos = [
99+
lambda x5c: [parse_pem(pem) for pem in x5c],
100+
lambda x5c: [parse_pem(DER_cert_to_PEM_cert(cert)) for cert in x5c],
101+
]
102+
103+
for method in parse_methos:
104+
try:
105+
return method(x5c)
106+
except Exception:
107+
continue
108+
raise InvalidJwk(f"unable to parse key from pem chain: {x5c}")

0 commit comments

Comments
 (0)