Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sign CSR from client using CA root certificate in python

I am new to python and still learning it so my question can be little naive. Please bear with it ;)

The problem is client will be sending CSR and I want to sign it with my CA root certificate and return the signed certificate back to client.

I have been using this command to do it using command line

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

same thing I want achieve using python. I have come across python library for openssl pyopenssl

is it possible using this library ? How ? or shoudl I go for M2Crypto ?

like image 919
nishi Avatar asked Apr 16 '14 08:04

nishi


People also ask

How do I get CSR signed by CA?

To sign a CSR with your Windows Server CAOn your Windows server, start Server Manager. In the Server Manager dashboard, in the top right corner, choose Tools, Certification Authority. In the Certification Authority window, choose your computer name. From the Action menu, choose All Tasks, Submit new request.


1 Answers

The maintainer of pyOpenSSL recommends to use cryptography module for X509 manipulation (see note on top of the documentation page: https://www.pyopenssl.org/en/stable/api/crypto.html).

Here is the code to create a certificate from a CSR signed by a CA:

def sign_certificate_request(csr_cert, ca_cert, private_ca_key):
    cert = x509.CertificateBuilder().subject_name(
        csr_cert.subject
    ).issuer_name(
        ca_cert.subject
    ).public_key(
        csr_cert.public_key()
    ).serial_number(
        x509.random_serial_number()
    ).not_valid_before(
        datetime.utcnow()
    ).not_valid_after(
        # Our certificate will be valid for 10 days
        datetime.utcnow() + timedelta(days=10)
    # Sign our certificate with our private key
    ).sign(private_ca_key, hashes.SHA256())

    # return DER certificate
    return cert.public_bytes(serialization.Encoding.DER)
  • csr_cert is the cryptography CSR certificate object - can be loaded from a file with x509.load_der_x509_csr()
  • ca_cert is the cryptography certificate object - can be loaded from a file with x509.load_pem_x509_certificate()
  • private_ca_key is the cryptography private key object - can be loaded from a file with serialization.load_pem_private_key()
like image 55
OlivierM Avatar answered Sep 25 '22 03:09

OlivierM