No Result
View All Result
DevRescue
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us
DevRescue
Home Blog Python

Python RSA Generate Certificate

by Khaleel O.
January 19, 2022
in Python
Reading Time: 4 mins read
A A
Python RSA Generate
Python RSA Generate

Hi! Let’s use Python to generate an RSA Certificate and save to disk. We will be using Python 3.8.10. Let’s go! 🔥⚡

If you haven’t already, please check our previous RSA Encrypt/Decrypt example where we examined the complete RSA algorithm and encrypted/decrypted some data. It lays a good foundation for your understanding of the inner workings of the RSA algorithm. Find it HERE.

First, install the Pycryptodomex library with the following command:

pip install pycryptodomex

Now let’s write some code:

from Crypto.PublicKey import RSA

new_key = RSA.generate(2048)

private_key = new_key.exportKey("PEM")
public_key = new_key.publickey().exportKey("PEM")

print(private_key.decode("utf-8"))
fd = open("private_key.pem", "wb")
fd.write(private_key)
fd.close()

print(public_key.decode("utf-8"))
fd = open("public_key.pem", "wb")
fd.write(public_key)
fd.close()

Let’s explain what is happening here:

  1. First, we import the Crypto.PublicKey method. This is what we will use to generate a new RSA keypair. Recall that the RSA algorithm is an asymmetric cryptography algorithm that uses a public key and a private key. Hence, they are generated in pairs.
  2. The method RSA.generate() will create a new RSA keypair. It accepts 3 parameters but we give only 1 here: bits. We give it a value of 2048 bits. This is the key length or size and must be at least 1024. The method returns an RSA key object, new_key.
  3. The method new_key.exportKey() will export the RSA key. We supply only one argument here which is the format. The format in this case is PEM, which is text encoding. The method returns the encoded private key in bytes, private_key.
  4. The method new_key.publickey().exportKey(), the same as above except that it exports the public key. It returns the public key in bytes as public_key.
  5. We print the private_key to the screen decoded as text and we also save it to disk as RSA certificate name private_key.pem. This certificate file will be generated to the same folder as your script.
  6. Similarly, we print the public_key to the screen decoded as text and we also save it to the disk as RSA certificate name public_key.pem. The certificate will be generated to the same folder as your script.

Easy right? If all goes well, when the code executes you should have two brand new certificate files generated to the same folder as your script named public_key.pem and private_key.pem and you should also see something similar to the following output on your screen:

""" 
-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAofLBodN739ltqbubpCQ47rW6F0sL4HAJNFcdCE6+XjdxtJYF
4m12PBplqkYZH221Ype7FYu82K7nJo3GUixvIrLQtsrn4kOasTOvB0rxrMEBU5LM
FmqMLrIzPoIr/IGJ4o2X+NUxlsCo9uKHXfSOB9aysYePOIfQdfd9YA1T8E9eioFZ
CFcWm+LEzb5+YkGnepmExPZjiqHb0lzrzJzjwXGh+OWimw9N4ubMCx6TxWIHulwm
tXAEW4CO8HWizCbbXqrl9ak6HEL4UWbmZkb14y/3Bs+I3qGhqXTJv7owW/Io4PRF
nACgQ5B9XQHPJwwGG0p9AMhCitQy3N5TIu75SQIDAQABAoIBABKJCGy/RJdvY76V
ndqGA3bIGYHj/CUrvX9I6dDobkpgmc97jOCIUGF6+0rR62XY9nXP0ZZFiuTZSSnK
TToHeDrQ8NQTBMI1TvBcGXrCCEdnmawZNOmV4psk7c+IMi+cGzjGUEVRup4QnpC5
3ENpI5O1w3hP1cO4a6gCHk6O3Ui3e4lICXkNZ0u0nimlsvQrEbsa034WzmiyWBeb
XwII0e/iBrvO9C+2k4uXjyH9/bfu9lZMeyCBw27J8dUNOJWP4e8ius0wmWvxA8oc
a4DazTC4264D1qR2XQAyDvueCIMjHMhaKfP8D2y/rOCJehMF9ScttoNLQWB8opo/
+ZzRHBcCgYEAyYx36MzXRE5e8oPGEq+s1yntPUuTuG/snPSNkDBEtAX4Hqx8Y+ev
qYaiQdCgJuQu7XCDR9Sx6Plx2S209PBLHDfJDro6oiNdMd/BzSyPH0ujVidD6mnx
SIYlFsSEvpTRcobyKGRTroCKkSqqMc8F+DrxF8wy+bLey1kS4LXLOTcCgYEAzbNw
Rf562uqyH2a6sDM54/B6FqBVh1BPqRczN4tx4ZvK1Xt8hclsd0Z2CYS/89j33gkE
w4SOiE5BUHVuLAmWYOcMdZWoJjkI6j9JCqSM3KelO8TPWW+Enj4YZcNMYATbsZjw
c/soYfUzluB+QzUtIdfbA0aw6v8DhnZ+MCXuoX8CgYEAyLTAaC0spZHhzWFaKxuU
ZEQVQzfy5/VVTEvgeVkH4bocBve/e4GqFYjEJgRKp9ANx1eG9E4jyRw2uo5gqJZu
RbBr4OWlI/dRhCwOA3K/J+wbwNyjLlnH9G/ZmV2jz2HFXWZy2bRm/Nx2oO86wxUl
HbgchJVNogj1As02Fl4S/WsCgYAF93eBQEF2CirCiGtP4xyBxR71ew8gDq9Q21Bs
Awp5ndhDWwKgqtgPmaag3g3nV9rQwPg3Z6fuwj5YxB8+/cQz6V/OJVosSak9ijpn
KaDAYciENFBDat2w7WItyX10p49r1mDbLGTeeotVjAt9jZRSj/1VWf6VwnHqu5Mr
eF40pwKBgHQB+GTyOgZHseuO4Gmnk8Y1l4SNCli2XESpcdsnDImpmZH5z4nZ3/J8
FJytT8jDTDgDLqierXg0ICVNCJqD2HC/V5IQQGLp6Xj/hyeFLrDCvA6VOqLtYvwb
Scbon2VqiMDqUk/c6Kx+4rAumV3HPq7LrL4W7EPnu6ZFTzcshnn/
-----END RSA PRIVATE KEY-----
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAofLBodN739ltqbubpCQ4
7rW6F0sL4HAJNFcdCE6+XjdxtJYF4m12PBplqkYZH221Ype7FYu82K7nJo3GUixv
IrLQtsrn4kOasTOvB0rxrMEBU5LMFmqMLrIzPoIr/IGJ4o2X+NUxlsCo9uKHXfSO
B9aysYePOIfQdfd9YA1T8E9eioFZCFcWm+LEzb5+YkGnepmExPZjiqHb0lzrzJzj
wXGh+OWimw9N4ubMCx6TxWIHulwmtXAEW4CO8HWizCbbXqrl9ak6HEL4UWbmZkb1
4y/3Bs+I3qGhqXTJv7owW/Io4PRFnACgQ5B9XQHPJwwGG0p9AMhCitQy3N5TIu75
SQIDAQAB
-----END PUBLIC KEY----- """

Above, we have the text of our public and private certificates. The certificates contains the keys that will be used to encrypt or decrypt the data. Anyone can use the public key to encrypt data but only the private key can decrypt data so the private_key.pem file needs to be kept secret and safe at all times!

Now that we have generated our certificates, we can use the certificates to encrypt and then decrypt data. This is what we will do in our next tutorial which you can find HERE.

Thanks for reading and good luck! 👌👌👌

Tags: encryptionRSA
Previous Post

Automate WhatsApp with Python pywhatkit

Next Post

Python RSA Encrypt with Public Key

Khaleel O.

Khaleel O.

I love to share, educate and help developers. I have 14+ years experience in IT. Currently transitioning from Systems Administration to DevOps. Avid reader, intellectual and dreamer. Enter Freely, Go safely, And leave something of the happiness you bring.

Related Posts

Python

Python Fibonacci Recursive Solution

by Khaleel O.
January 16, 2024
0
0

Let's do a Python Fibonacci Recursive Solution. Let's go! 🔥🔥🔥 The Fibonacci sequence is a series of numbers in which...

Read moreDetails
Python

Python Slice String List Tuple

by Khaleel O.
January 16, 2024
0
0

Let's do a Python Slice string list tuple how-to tutorial. Let's go! 🔥🔥🔥 In Python, a slice is a feature...

Read moreDetails
Python

Python Blowfish Encryption Example

by Khaleel O.
January 14, 2024
0
0

Let's do a Python Blowfish Encryption example. Let's go! 🔥 🔥 Blowfish is a symmetric-key block cipher algorithm designed for...

Read moreDetails
Python

Python Deque Methods

by Khaleel O.
January 14, 2024
0
0

In this post we'll list Python Deque Methods. Ready? Let's go! 🔥🔥🔥 A deque (double-ended queue) in Python is a...

Read moreDetails

DevRescue © 2021 All Rights Reserved. Privacy Policy. Cookie Policy

Manage your privacy

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Statistics

Marketing

Features
Always active

Always active
  • Manage options
  • Manage services
  • Manage {vendor_count} vendors
  • Read more about these purposes
Manage options
  • {title}
  • {title}
  • {title}
Manage your privacy
To provide the best experiences, DevRescue.com will use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Statistics

Marketing

Features
Always active

Always active
  • Manage options
  • Manage services
  • Manage {vendor_count} vendors
  • Read more about these purposes
Manage options
  • {title}
  • {title}
  • {title}
No Result
View All Result
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us

DevRescue © 2022 All Rights Reserved Privacy Policy