PyOpenSSL creating pem file

I 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)
  • Now, how can I create private and public key .pem files from a key object?
  • If there is any tutorial, please let me know. I have not found anyone. This is hard to understand from the manual, as I am new to OpenSSL.
  • What are the chances that the same code will create two identical key pairs, is there no specific unique key that is used in RSA?
+4
source share
3 answers

I hope this helps people in the future because I had the same need and could not find an answer, so I did it myself. I 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)

. , :

_bio_to_string(bio_pub), _bio_to_string(bio_priv)

"private" OpenSSL.crypto:

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

, , , , , .

Python 3.x - PyCryptodome.

Python ( 2048- ):

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)

(Linux), :

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

.pem, :

https://help.ubuntu.com/community/OpenSSL

, CA (), , CA - .

ssl connection it .

then make sure you install openssl first and you have CN (Common Name) permission on your service. without this, it will be difficult for you to use the generated certificate.

for Self-sign certificate use this command line:

$ openssl genrsa -des3 -passout pass:x -out server.pass.key 2048
$ openssl rsa -passin pass:x -in server.pass.key -out server.key
$ rm server.pass.key
$ openssl req -new -key server.key -out server.csr (list of question to answer)
$ openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt 

after you have created the certificate, you need to activate server mod-ssl and add the line where your certificate is located. later you need to insert this certificate into your IE certificate in order to make it work with you, namely apache ssl connection daemon.

0
source

All Articles