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

Commit decaaa2

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

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-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.

0 commit comments

Comments
 (0)