Search code examples
pythonpyopenssl

pyOpenSSL creating a pem file


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?

Solution

  • I hope this will help people in the future, because I had this same need and couldn't find an answer so I did it myself. Thought I would share it with you.

    1. Creating a PEM file

    bio_pub = _new_mem_buf()  # Memory buffers to write to
    bio_priv = _new_mem_buf()
    
    helper = OpenSSL.crypto._PassphraseHelper(OpenSSL.crypto.FILETYPE_PEM, None)
    
    pk = OpenSSL.crypto.PKey()
    pk.generate_key(OpenSSL.crypto.TYPE_RSA, n)
    
    # Convert from EVP_PKEY type to RSA type
    rsa_pkey = _lib.EVP_PKEY_get1_RSA(pk._pkey)
    
    
    result_code = _lib.PEM_write_bio_RSAPublicKey(bio_pub, rsa_pkey)
    result_code = _lib.PEM_write_bio_RSAPrivateKey(
        bio_priv, rsa_pkey, _ffi.NULL, _ffi.NULL, 0,
        helper.callback, helper.callback_args)
    

    After this part you will have the public and private keys in your buffers. To get it as a string you can call the functions:

    _bio_to_string(bio_pub), _bio_to_string(bio_priv)
    

    I used these imports for the special "private" functions of OpenSSL.crypto:

    import OpenSSL
    from OpenSSL._util import lib as _lib, ffi as _ffi
    from OpenSSL.crypto import _new_mem_buf, _bio_to_string