pyOpenSSL creating a pem file

RatDon picture RatDon · Oct 29, 2013 · Viewed 12.8k times · Source

I've created a key pair using the following code in python with pyOpenSSL:

from OpenSSL import crypto
k = crypto.PKey()
k.generate_key(crypto.TYPE_RSA, 2048)
  1. Now how can I create the private and public key .pem files from the key object?
  2. If there is any tutorial available please let me know. I found none. From the manual, it's difficult to know as I'm new to OpenSSL.
  3. What are the chances that the same code will create two same key pairs is there is no specific unique key is being used in RSA?

Answer

AJ Poulter picture AJ Poulter · Aug 25, 2017

I know this is an old question - but as I've just found it I thought I'd add an answer.

The easiest way to do this with Python 3.x is to use PyCryptodome.

The in Python (for a 2048-bit key):

from Cryptodome.PublicKey import RSA
key = RSA.generate(2048)
pv_key_string = key.exportKey()
with open ("private.pem", "w") as prv_file:
    print("{}".format(pv_key_string.decode()), file=prv_file)

pb_key_string = key.publickey().exportKey()
 with open ("public.pem", "w") as pub_file:
    print("{}".format(pb_key_string.decode()), file=pub_file)

If you want to check the private key on the (Linux) command-line use:

$ openssl rsa -check -inform pem -noout -in private.pem 
RSA key ok
...