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

Commit ca15a6b

Browse files
committed
Generate PublicKey from PrivateKey
1 parent 5b377fb commit ca15a6b

File tree

3 files changed

+31
-0
lines changed

3 files changed

+31
-0
lines changed

doc/usage.rst

+13
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,19 @@ Alternatively you can use :py:meth:`rsa.PrivateKey.load_pkcs1` and
4040
... keydata = privatefile.read()
4141
>>> privkey = rsa.PrivateKey.load_pkcs1(keydata)
4242

43+
As public keys can be derived from private keys it is sufficient to
44+
have only the private one. The :py:class:`rsa.PrivateKey` class
45+
has the dedicated method :py:meth:`rsa.PrivateKey.public_key` to
46+
retrieve the corresponding :py:class:`rsa.PublicKey` from it:
47+
48+
>>> import rsa
49+
>>> with open('private.pem', mode='rb') as privatefile:
50+
... keydata = privatefile.read()
51+
>>> privkey = rsa.PrivateKey.load_pkcs1(keydata)
52+
>>> pubkey = privkey.public_key()
53+
54+
55+
4356

4457
Time to generate a key
4558
++++++++++++++++++++++

rsa/key.py

+12
Original file line numberDiff line numberDiff line change
@@ -499,6 +499,18 @@ def blinded_encrypt(self, message: int) -> int:
499499
encrypted = rsa.core.encrypt_int(blinded, self.d, self.n)
500500
return self.unblind(encrypted, blindfac_inverse)
501501

502+
def public_key(self) -> PublicKey:
503+
"""Generates the corresponding PublicKey from the PrivateKey.
504+
505+
Equivalent to
506+
>>> pubkey = PublicKey(privkey.n, privkey.e)
507+
508+
:returns: the public key that belongs to the private key
509+
:rtype: PublicKey
510+
"""
511+
512+
return PublicKey(self.n, self.e)
513+
502514
@classmethod
503515
def _load_pkcs1_der(cls, keyfile: bytes) -> "PrivateKey":
504516
"""Loads a key in PKCS#1 DER format.

tests/test_key.py

+6
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,12 @@ def getprime(_):
7474
)
7575
self.assertEqual(39317, p)
7676
self.assertEqual(33107, q)
77+
78+
def test_generate_public_from_private(self):
79+
pub, priv = rsa.key.newkeys(16)
80+
pub_generated = priv.public_key()
81+
82+
self.assertEqual(pub, pub_generated)
7783

7884

7985
class HashTest(unittest.TestCase):

0 commit comments

Comments
 (0)