Skip to content

Commit

Permalink
Generate PublicKey from PrivateKey
Browse files Browse the repository at this point in the history
  • Loading branch information
bliepp committed Jan 11, 2022
1 parent 5b377fb commit ca15a6b
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 0 deletions.
13 changes: 13 additions & 0 deletions doc/usage.rst
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,19 @@ Alternatively you can use :py:meth:`rsa.PrivateKey.load_pkcs1` and
... keydata = privatefile.read()
>>> privkey = rsa.PrivateKey.load_pkcs1(keydata)

As public keys can be derived from private keys it is sufficient to
have only the private one. The :py:class:`rsa.PrivateKey` class
has the dedicated method :py:meth:`rsa.PrivateKey.public_key` to
retrieve the corresponding :py:class:`rsa.PublicKey` from it:

>>> import rsa
>>> with open('private.pem', mode='rb') as privatefile:
... keydata = privatefile.read()
>>> privkey = rsa.PrivateKey.load_pkcs1(keydata)
>>> pubkey = privkey.public_key()




Time to generate a key
++++++++++++++++++++++
Expand Down
12 changes: 12 additions & 0 deletions rsa/key.py
Original file line number Diff line number Diff line change
Expand Up @@ -499,6 +499,18 @@ def blinded_encrypt(self, message: int) -> int:
encrypted = rsa.core.encrypt_int(blinded, self.d, self.n)
return self.unblind(encrypted, blindfac_inverse)

def public_key(self) -> PublicKey:
"""Generates the corresponding PublicKey from the PrivateKey.
Equivalent to
>>> pubkey = PublicKey(privkey.n, privkey.e)
:returns: the public key that belongs to the private key
:rtype: PublicKey
"""

return PublicKey(self.n, self.e)

@classmethod
def _load_pkcs1_der(cls, keyfile: bytes) -> "PrivateKey":
"""Loads a key in PKCS#1 DER format.
Expand Down
6 changes: 6 additions & 0 deletions tests/test_key.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,12 @@ def getprime(_):
)
self.assertEqual(39317, p)
self.assertEqual(33107, q)

def test_generate_public_from_private(self):
pub, priv = rsa.key.newkeys(16)
pub_generated = priv.public_key()

self.assertEqual(pub, pub_generated)


class HashTest(unittest.TestCase):
Expand Down

0 comments on commit ca15a6b

Please sign in to comment.