|
12 | 12 | from .utils import crypto_required, key_path |
13 | 13 |
|
14 | 14 | if has_crypto: |
| 15 | + from cryptography import x509 |
15 | 16 | from cryptography.hazmat.primitives.asymmetric.ec import ( |
16 | 17 | EllipticCurvePrivateKey, |
17 | 18 | EllipticCurvePublicKey, |
|
28 | 29 | RSAPrivateKey, |
29 | 30 | RSAPublicKey, |
30 | 31 | ) |
| 32 | + from cryptography.hazmat.primitives.serialization import ( |
| 33 | + Encoding, |
| 34 | + PublicFormat, |
| 35 | + ) |
31 | 36 |
|
32 | 37 | from jwt.algorithms import ECAlgorithm, OKPAlgorithm, RSAAlgorithm, RSAPSSAlgorithm |
33 | 38 |
|
@@ -259,6 +264,40 @@ def test_hmac_prepare_key_rejects_deep_jwk_with_surrogate( |
259 | 264 | with pytest.raises(InvalidKeyError, match="looks like a JWK"): |
260 | 265 | algo.prepare_key(key) |
261 | 266 |
|
| 267 | + @crypto_required |
| 268 | + @pytest.mark.parametrize( |
| 269 | + "key_format_name", |
| 270 | + ("SubjectPublicKeyInfo", "PKCS1"), |
| 271 | + ) |
| 272 | + def test_hmac_prepare_key_rejects_der_public_key( |
| 273 | + self, key_format_name: str |
| 274 | + ) -> None: |
| 275 | + algo = HMACAlgorithm(HMACAlgorithm.SHA256) |
| 276 | + public_key = cast(RSAPublicKey, load_rsa_pub_key()) |
| 277 | + der_key = public_key.public_bytes( |
| 278 | + Encoding.DER, getattr(PublicFormat, key_format_name) |
| 279 | + ) |
| 280 | + |
| 281 | + with pytest.raises(InvalidKeyError, match="asymmetric key"): |
| 282 | + algo.prepare_key(der_key) |
| 283 | + |
| 284 | + @crypto_required |
| 285 | + def test_hmac_prepare_key_rejects_der_certificate(self) -> None: |
| 286 | + algo = HMACAlgorithm(HMACAlgorithm.SHA256) |
| 287 | + with open(key_path("testkey_rsa.cer"), "rb") as certificate_file: |
| 288 | + certificate = x509.load_pem_x509_certificate(certificate_file.read()) |
| 289 | + der_certificate = certificate.public_bytes(Encoding.DER) |
| 290 | + |
| 291 | + with pytest.raises(InvalidKeyError, match="x509 certificate"): |
| 292 | + algo.prepare_key(der_certificate) |
| 293 | + |
| 294 | + @crypto_required |
| 295 | + def test_hmac_prepare_key_accepts_non_key_binary_secret(self) -> None: |
| 296 | + algo = HMACAlgorithm(HMACAlgorithm.SHA256) |
| 297 | + secret = b"\x30\x82not-a-der-key" |
| 298 | + |
| 299 | + assert algo.prepare_key(secret) == secret |
| 300 | + |
262 | 301 | @crypto_required |
263 | 302 | def test_rsa_should_parse_pem_public_key(self) -> None: |
264 | 303 | algo = RSAAlgorithm(RSAAlgorithm.SHA256) |
|
0 commit comments