Creating a self-signed certificate with CA.crt

133 Views Asked by At

im trying now make code to create certificate. In openssl its make like openssl x509 -req -CAkey key.pem -CA CA.CRT -CAcreateserial -in csr.csr -req -days 365 -out cert.CRT -extfile config.conf -extensions v3_req I dont know how set this options -CAkey key.pem, -CA CA.CRT and -CAcreateserial and edit in code below.

For this code openssl x509 -req -signkey priv.pem -in csr.csr -req -days 365 -out crt.crt -extfile config.conf -extensions v3_req im using next func:

def crtGen(path, name, key):     
    subject = issuer = x509.Name([
    x509.NameAttribute(NameOID.COUNTRY_NAME, ""),
    x509.NameAttribute(NameOID.ORGANIZATION_NAME, ""),
    x509.NameAttribute(NameOID.COMMON_NAME, ""),
    ])
    cert = x509.CertificateBuilder().subject_name( 
        subject 
    ).issuer_name( 
        issuer
    ).add_extension(
        x509.BasicConstraints(ca=False,path_length=None),critical=False,
    ).add_extension(
        x509.KeyUsage(digital_signature=True,
                      key_encipherment=True,
                      content_commitment=True,
                      data_encipherment=False,
                      key_agreement=False,
                      key_cert_sign=False,
                      crl_sign=False,
                      encipher_only=False,
                      decipher_only=False),
        critical=False,
    ).public_key( 
        key.public_key() 
    ).serial_number( 
        x509.random_serial_number() 
    ).not_valid_before( 
        datetime.utcnow() 
    ).not_valid_after( 
        datetime.utcnow() + timedelta(days=365) 
    ).sign(key, hashes.SHA256())
    with open(f"{path}{name}.crt", "wb") as f:
        f.write(cert.public_bytes(serialization.Encoding.PEM)
1

There are 1 best solutions below

2
Pedro Santos On

If what you want to do is generate a self-signed openssl certificate, you can call the command to do it with the subprocess module.

Example (tweak settings to your preference):

import subprocess

def generate_self_signed_certificate(cert_path, key_path):
    openssl_cmd = [
        'openssl', 'req', '-x509', '-newkey', 'rsa:4096',
        '-keyout', key_path, '-out', cert_path, '-days', '365'
    ]

    try:
        subprocess.run(openssl_cmd, check=True)
        print(f"Certificate generated successfully: {cert_path} and {key_path}")
    except subprocess.CalledProcessError as e:
        print(f"Error generating certificate: {e}")

if __name__ == "__main__":
    cert_path = "path/to/your/certificate.crt"
    key_path = "path/to/your/private_key.key"
    
    generate_self_signed_certificate(cert_path, key_path)

This is a much more clearer and simpler way to do what you're trying to do.