Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle load_pem_public_key ValueError #952

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions jwt/algorithms.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
)

try:
from cryptography.exceptions import InvalidSignature
from cryptography.exceptions import InvalidSignature, UnsupportedAlgorithm
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
Expand Down Expand Up @@ -343,7 +343,10 @@ def prepare_key(self, key: AllowedRSAKeys | str | bytes) -> AllowedRSAKeys:
RSAPrivateKey, load_pem_private_key(key_bytes, password=None)
)
except ValueError:
return cast(RSAPublicKey, load_pem_public_key(key_bytes))
try:
return cast(RSAPublicKey, load_pem_public_key(key_bytes))
except (ValueError, UnsupportedAlgorithm):
CollinEMac marked this conversation as resolved.
Show resolved Hide resolved
raise InvalidKeyError("Could not parse the provided public key.")

@overload
@staticmethod
Expand Down
11 changes: 11 additions & 0 deletions tests/test_algorithms.py
Original file line number Diff line number Diff line change
Expand Up @@ -1100,3 +1100,14 @@ def test_hmac_can_compute_digest(self):
algo = HMACAlgorithm(HMACAlgorithm.SHA256)
computed_hash = algo.compute_hash_digest(b"foo")
assert computed_hash == foo_hash

@crypto_required
def test_rsa_prepare_key_raises_invalid_key_error_on_invalid_pem(self):
algo = RSAAlgorithm(RSAAlgorithm.SHA256)
invalid_key = "invalid key"

with pytest.raises(InvalidKeyError) as excinfo:
algo.prepare_key(invalid_key)

# Check that the exception message is correct
assert "Could not parse the provided public key." in str(excinfo.value)
Loading