From 309247241cd7180307aa05cef9015fadc1ba216d Mon Sep 17 00:00:00 2001 From: Jakob Schlyter Date: Mon, 16 Mar 2026 10:24:29 +0100 Subject: [PATCH] Improve SYMKey init (allow setting k and/or key) --- pyproject.toml | 2 +- src/cryptojwt/jwk/hmac.py | 5 +++++ tests/test_02_jwk.py | 19 +++++++++++++++++++ 3 files changed, 25 insertions(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index d4356dd..255c552 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -74,7 +74,7 @@ select = [ # isort "I", ] -ignore = ["E501", "I001", "SIM102", "UP006", "UP035", "UP045", "UP007"] +ignore = ["E501", "I001", "SIM102", "UP006", "UP035", "UP045", "UP007", "UP038"] exclude = ["examples/*"] [tool.ruff.lint.isort] diff --git a/src/cryptojwt/jwk/hmac.py b/src/cryptojwt/jwk/hmac.py index a170744..996751e 100644 --- a/src/cryptojwt/jwk/hmac.py +++ b/src/cryptojwt/jwk/hmac.py @@ -59,6 +59,11 @@ def __init__( if isinstance(self.k, str): self.k = self.k.encode("utf-8") self.key = b64d(bytes(self.k)) + elif self.key and not self.k: + self.k = b64e(self.key) + + if self.k and self.key and self.k != b64e(self.key): + raise JWKException("k and key don't match") if len(self.key) < 16: raise UnsupportedAlgorithm("client_secret too short, it should be at least 16 digits") diff --git a/tests/test_02_jwk.py b/tests/test_02_jwk.py index 6e83f3d..387008f 100755 --- a/tests/test_02_jwk.py +++ b/tests/test_02_jwk.py @@ -11,6 +11,7 @@ from cryptojwt.exception import ( DeSerializationNotPossible, + JWKException, UnsupportedAlgorithm, WrongUsage, ) @@ -660,6 +661,24 @@ def test_dump_load(): assert key.use == "sig" +def test_key_init(): + # init with only key + secret1 = os.urandom(16) + k1 = SYMKey(key=secret1, alg="HS256") + assert k1.k == b64e(secret1) + + # init with only k (base64 encoded key) + secret2 = os.urandom(16) + k2 = SYMKey(k=b64e(secret2), alg="HS256") + assert k2.key == secret2 + + # init with different key and k should fail + secret3a = os.urandom(16) + secret3b = os.urandom(16) + with pytest.raises(JWKException): + _ = SYMKey(k=b64e(secret3a), key=secret3b, alg="HS256") + + def test_key_ops(): sk = SYMKey( key="df34db91c16613deba460752522d28f6ebc8a73d0d9185836270c26b",