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 RSAJwk.from_prime_factors() #16

Merged
merged 1 commit into from
Jul 24, 2023
Merged
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
22 changes: 22 additions & 0 deletions jwskate/jwk/rsa.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,28 @@ def private(
)
)

@classmethod
def from_prime_factors(cls, p: int, q: int, e: int = 65537) -> RSAJwk:
"""Initialise a `RSAJwk` from its prime factors and exponent.
Modulus and Private Exponent are mathematically calculated based on those factors.
Exponent is usually 65537 (default).
Args:
p: first prime factor
q: second prime factor
e: exponent
Returns:
a `RSAJwk`
"""
n = p * q
phi = (p - 1) * (q - 1)
d = pow(e, -1, phi)
return cls.private(n=n, e=e, d=d)

@cached_property
def key_size(self) -> int:
"""Key size, in bits."""
Expand Down
13 changes: 13 additions & 0 deletions tests/test_jwk/test_rsa.py
Original file line number Diff line number Diff line change
Expand Up @@ -278,3 +278,16 @@ def test_public_private() -> None:
)
== jwk
)


def test_init_from_prime_factors() -> None:
p = 398075086424064937397125500550386491199064362342526708406385189575946388957261768583317
q = 472772146107435302536223071973048224632914695302097116459852171130520711256363590397527
jwk = RSAJwk.from_prime_factors(p, q)
assert jwk.first_prime_factor == p
assert jwk.second_prime_factor == q
assert (
jwk.modulus
== 188198812920607963838697239461650439807163563379417382700763356422988859715234665485319060606504743045317388011303396716199692321205734031879550656996221305168759307650257059
)
assert jwk.exponent == 65537