Skip to content

Commit

Permalink
Explicit check the key for ECAlgorithm (#713)
Browse files Browse the repository at this point in the history
* Explicit check the key for ECAlgorithm

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
estin and pre-commit-ci[bot] committed Dec 12, 2021
1 parent 43d38a0 commit aabeb06
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
6 changes: 6 additions & 0 deletions jwt/algorithms.py
Expand Up @@ -417,6 +417,12 @@ def prepare_key(self, key):
except ValueError:
key = load_pem_private_key(key, password=None)

# Explicit check the key to prevent confusing errors from cryptography
if not isinstance(key, (EllipticCurvePrivateKey, EllipticCurvePublicKey)):
raise InvalidKeyError(
"Expecting a EllipticCurvePrivateKey/EllipticCurvePublicKey. Wrong key provided for ECDSA algorithms"
)

return key

def sign(self, msg, key):
Expand Down
12 changes: 12 additions & 0 deletions tests/test_algorithms.py
Expand Up @@ -494,6 +494,18 @@ def test_ec_verify_should_return_false_if_signature_wrong_length(self):
result = algo.verify(message, pub_key, sig)
assert not result

@crypto_required
def test_ec_should_throw_exception_on_wrong_key(self):
algo = ECAlgorithm(ECAlgorithm.SHA256)

with pytest.raises(InvalidKeyError):
with open(key_path("testkey_rsa.priv")) as keyfile:
algo.prepare_key(keyfile.read())

with pytest.raises(InvalidKeyError):
with open(key_path("testkey2_rsa.pub.pem")) as pem_key:
algo.prepare_key(pem_key.read())

@crypto_required
def test_rsa_pss_sign_then_verify_should_return_true(self):
algo = RSAPSSAlgorithm(RSAPSSAlgorithm.SHA256)
Expand Down

0 comments on commit aabeb06

Please sign in to comment.