Skip to content
This repository was archived by the owner on Apr 20, 2025. It is now read-only.

Generate PublicKey from PrivateKey #187

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
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