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

Add functions to generate a similar key #361

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
12 changes: 12 additions & 0 deletions jwcrypto/jwk.py
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,18 @@ def generate_key(self, **params):

gen(params)

@classmethod
def generate_similar(cls, key):
return cls.generate(**key.get_generate_params())

def get_generate_params(self):
params = {param: self.get(param) for param in ["kty", "crv", "use", "key_ops"] if param in self}
if self.get("kty") == "RSA":
params["size"] = self._get_public_key().key_size
elif self.get("kty") == "oct":
params["size"] = len(base64url_decode(self.k)) * 8
return params

def _get_gen_size(self, params, default_size=None):
size = default_size
if 'size' in params:
Expand Down
52 changes: 52 additions & 0 deletions jwcrypto/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -506,6 +506,58 @@ def test_jwk_from_json(self):
y = jwk.JWK.from_json(k.export())
self.assertEqual(k.export(), y.export())

def test_generate_similar(self):
KEY_PARAMS = [
{
"kty": "oct",
"size": 192
},
{
"kty": "RSA",
"size": 3072
},
{
"kty": "EC",
"crv": "P-256"
},
{
"kty": "EC",
"crv": "P-384",
},
{
"kty": "OKP",
"crv": "Ed25519"
},
{
"kty": "OKP",
"crv": "Ed448"
},
{
"kty": "OKP",
"crv": "X25519"
},
{
"kty": "OKP",
"crv": "X448"
},
{
"kty": "RSA",
"size": 3072,
"use": "sig"
},
{
"kty": "oct",
"size": 256,
"key_ops": "sign"
},
]
for params in KEY_PARAMS:
key1 = jwk.JWK.generate(**params)
key2 = jwk.JWK.generate_similar(key1)
for prop in ["kty", "crv", "use", "key_ops"]:
self.assertEqual(key1.get(prop), key2.get(prop))
self.assertEqual(type(key1.get_op_key("sign")), type(key2.get_op_key("sign")))

def test_jwkset(self):
k = jwk.JWK(**RSAPrivateKey)
ks = jwk.JWKSet()
Expand Down