![Python RSA Generate](https://devrescue.com/wp-content/uploads/2022/01/RSA2.png)
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:
- 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.
- 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.
- 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.
- 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.
- 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.
- 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
4m12PBplqkYZH221Ype7FYu82K7nJo3GUixvIrLQtsrn4kOasTOvB0r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3K/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! 👌👌👌