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 _extra_extensions( self, builder: x509.CertificateBuilder, extra_extensions: Iterable[Union["x509.Extension[x509.ExtensionType]", "Extension[Any, Any, Any]"]], ) -> x509.CertificateBuilder: for ext in extra_extensions: if isinstance(ext, x509.Extension): builder = builder.add_extension(ext.value, critical=ext.critical) elif isinstance(ext, Extension): builder = builder.add_extension(*ext.for_builder()) else: raise ValueError(f"Cannot add extension of type {type(ext).__name__}") return builder
def sign_csr( csr: CertificateSigningRequest, ca_cert: Certificate, key: EllipticCurvePrivateKey, expiration_date: date, custom_extensions: Iterable[Union[KeyUsage, UnrecognizedExtension, BasicConstraints]] ) -> Certificate: """ Sign a CSR with CA credentials. :param csr: the CSR :param ca_cert: the CA certificate :param key: the CA private key :param expiration_date: expiration date :param custom_extensions: custom extensions to be added to the certificate :return: a certificate object """ issuer = ca_cert.subject now = datetime.utcnow() cert_builder = CertificateBuilder().issuer_name(issuer).subject_name( csr.subject).public_key(csr.public_key()).serial_number( x509.random_serial_number()).not_valid_before(now).not_valid_after( datetime.combine(expiration_date, time(), None)).add_extension( extension=AuthorityKeyIdentifier.from_issuer_public_key( ca_cert.public_key()), critical=False) try: cert_builder = cert_builder.add_extension( csr.extensions.get_extension_for_class( SubjectAlternativeName).value, critical=False) except ExtensionNotFound: pass for extension in custom_extensions: if isinstance(extension, UnrecognizedExtension): critical = False else: critical = True # pyre-fixme[6]: Expected `ExtensionType` for 1st param but got # `Union[BasicConstraints, KeyUsage, UnrecognizedExtension]`. cert_builder = cert_builder.add_extension(extension, critical=critical) return cert_builder.sign(key, SHA256(), backends.default_backend())
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(), )