def _create_x509_certificate( key_der, subject_name ): #type(Union[EllipticCurvePrivateKey,RSAPrivateKey], str) -> Certificate signing_key = serialization.load_der_private_key( key_der, password=None, backend=default_backend()) builder = CertificateBuilder() builder = builder.subject_name( x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, subject_name), ])) builder = builder.issuer_name( x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, subject_name), ])) one_day = datetime.timedelta(1, 0, 0) builder = builder.not_valid_before(datetime.datetime.today() - one_day) builder = builder.not_valid_after(datetime.datetime.today() + (one_day * 30)) builder = builder.serial_number(x509.random_serial_number()) builder = builder.public_key(signing_key.public_key()) builder = builder.add_extension(SubjectAlternativeName( [x509.DNSName(subject_name)]), critical=False) builder = builder.add_extension(BasicConstraints(ca=False, path_length=None), critical=True) return builder.sign(private_key=signing_key, algorithm=hashes.SHA256(), backend=default_backend()).public_bytes( serialization.Encoding.DER)
def create_x509_certificate(key_pem, subject_name): # type: (str, str) -> str """ Given an RSA or ECDS private key, create a self-signed X.509 certificate with the specified subject name signed with that key. """ signing_key = serialization.load_pem_private_key(key_pem.encode("ascii"), password=None, backend=default_backend()) builder = CertificateBuilder() builder = builder.subject_name( x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, subject_name), ])) builder = builder.issuer_name( x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, subject_name), ])) one_day = datetime.timedelta(1, 0, 0) builder = builder.not_valid_before(datetime.datetime.today() - one_day) builder = builder.not_valid_after(datetime.datetime.today() + (one_day * 30)) builder = builder.serial_number(x509.random_serial_number()) builder = builder.public_key(signing_key.public_key()) builder = builder.add_extension(SubjectAlternativeName( [x509.DNSName(subject_name)]), critical=False) builder = builder.add_extension(BasicConstraints(ca=False, path_length=None), critical=True) return (builder.sign( private_key=signing_key, algorithm=hashes.SHA256(), backend=default_backend(), ).public_bytes(serialization.Encoding.PEM).decode("ascii"))
def cert(issuer, subject, pubkey, privkey, ca): builder = CertificateBuilder().issuer_name( Name([NameAttribute(NameOID.COMMON_NAME, issuer)]), ).subject_name( Name([NameAttribute(NameOID.COMMON_NAME, subject)]), ).add_extension( SubjectAlternativeName([DNSName(subject)]), critical=False, ) if ca: builder = builder.add_extension( BasicConstraints(True, None), critical=True, ) return builder.public_key( pubkey, ).serial_number(random_serial_number(), ).not_valid_before( datetime.utcnow(), ).not_valid_after( datetime.utcnow() + timedelta(seconds=1), ).sign( privkey, SHA256(), default_backend(), )