|
9 | 9 | import pytest |
10 | 10 | from cryptography.hazmat.primitives.asymmetric import ec, ed25519, rsa |
11 | 11 |
|
12 | | -from cryptojwt.exception import DeSerializationNotPossible, UnsupportedAlgorithm, WrongUsage |
| 12 | +from cryptojwt.exception import ( |
| 13 | + DeSerializationNotPossible, |
| 14 | + JWKException, |
| 15 | + UnsupportedAlgorithm, |
| 16 | + WrongUsage, |
| 17 | +) |
13 | 18 | from cryptojwt.jwk import JWK, certificate_fingerprint, pem_hash, pems_to_x5c |
14 | 19 | from cryptojwt.jwk.ec import ECKey, new_ec_key |
15 | 20 | from cryptojwt.jwk.hmac import SYMKey, new_sym_key, sha256_digest |
@@ -656,6 +661,29 @@ def test_dump_load(): |
656 | 661 | assert key.use == "sig" |
657 | 662 |
|
658 | 663 |
|
| 664 | +def test_key_init(): |
| 665 | + # init with only key |
| 666 | + secret1 = os.urandom(16) |
| 667 | + k1 = SYMKey(key=secret1, alg="HS256") |
| 668 | + assert k1.k == b64e(secret1) |
| 669 | + |
| 670 | + # init with only k (base64 encoded key) |
| 671 | + secret2 = os.urandom(16) |
| 672 | + k2 = SYMKey(k=b64e(secret2), alg="HS256") |
| 673 | + assert k2.key == secret2 |
| 674 | + |
| 675 | + # init with different key and k should fail |
| 676 | + secret3a = os.urandom(16) |
| 677 | + secret3b = os.urandom(16) |
| 678 | + with pytest.raises(JWKException): |
| 679 | + _ = SYMKey(k=b64e(secret3a), key=secret3b, alg="HS256") |
| 680 | + |
| 681 | + # init with both matching (k as str) - should succeed |
| 682 | + secret4 = os.urandom(16) |
| 683 | + k4 = SYMKey(k=b64e(secret4).decode("utf-8"), key=secret4, alg="HS256") |
| 684 | + assert k4.k == b64e(secret4) or bytes(k4.k, encoding="utf-8") == b64e(secret4) |
| 685 | + |
| 686 | + |
659 | 687 | def test_key_ops(): |
660 | 688 | sk = SYMKey( |
661 | 689 | key="df34db91c16613deba460752522d28f6ebc8a73d0d9185836270c26b", |
|
0 commit comments