Skip to content

Commit

Permalink
add RSAJwk.from_prime_factors() to initialize a RSAJwk from 2 pri…
Browse files Browse the repository at this point in the history
…me numbers (and an exponent).
  • Loading branch information
guillaume-pujol committed Jul 24, 2023
1 parent 8a8e9ed commit 643d33d
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
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

0 comments on commit 643d33d

Please sign in to comment.