Sign CSR from client using CA root certificate in python

I am new to python and still learning it, so my question might be a bit naive. Please keep this in mind;)

The problem is that the client will send the CSR, and I want to sign it using my root CA certificate and return the signed certificate back to the client.

I use this command to do this using the command line

openssl x509 -req -in device.csr -CA root.pem -CAkey root.key -CAcreateserial -out device.crt -days 500

The same thing I want to achieve with python. I came across python library for openssl pyopenssl

Can I use this library? How? or shoudl I'm going to M2Crypto?

+7
openssl ssl-certificate pyopenssl m2crypto
source share
1 answer

You can really go with pyOpenSSL. Since you say that you already have the CA root certificate and private key, and the CSR will be sent by the client, you can use the cryptography functions to read all of these (CA cert, private key and Device CSR) from the file or to manage them in the buffer.

To get started, use the features below. Check dir(crypto) and crypto.function_name.__doc__ on the python interpreter for more information :) You need to import cryptography from pyOpenSSL

  • crypto.load_certificate_request () - to receive a CSR obj device
  • crypto.load_privatekey () - to get the obj private key for the CA private key
  • crypto.load_certificate () - get the root CA certificate

then you can write a simple function to return a certificate

 def create_cert(): cert = crypto.X509() cert.set_serial_number(serial_no) cert.gmtime_adj_notBefore(notBeforeVal) cert.gmtime_adj_notAfter(notAfterVal) cert.set_issuer(caCert.get_subject()) cert.set_subject(deviceCsr.get_subject()) cert.set_pubkey(deviceCsr.get_pubkey()) cert.sign(CAprivatekey, digest) return cert 

where caCert , deviceCsr, and CAprivatekey are the values ​​of the three functions. Now that you have the certificate, you can write it to a file using crypto.dump_certificate(crypto.FILETYPE_PEM, cert) with the file name of your choice.

You can change this function according to your requirement. After that, you can verify the generated device certificate using the CA root certificate using the openssl command, for example. openssl verify -CApath <CA cert path> <name of device cert file>

You can also view some examples from github. M2Crypto example, pyOpenSSL example

Hope this gives you an idea of ​​implementation

+8
source share

All Articles