Python cryptography.x509.random_serial_number() Examples

The following are 20 code examples of cryptography.x509.random_serial_number(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module cryptography.x509 , or try the search function .
Example #1
Source File: create_certificates.py    From PyKMIP with Apache License 2.0 6 votes vote down vote up
def create_self_signed_certificate(subject_name, private_key, days_valid=365):
    subject = x509.Name([
        x509.NameAttribute(x509.NameOID.ORGANIZATION_NAME, u"Test, Inc."),
        x509.NameAttribute(x509.NameOID.COMMON_NAME, subject_name)
    ])
    certificate = x509.CertificateBuilder().subject_name(
        subject
    ).issuer_name(
        subject
    ).public_key(
        private_key.public_key()
    ).serial_number(
        x509.random_serial_number()
    ).add_extension(
        x509.BasicConstraints(ca=True, path_length=None), critical=True
    ).not_valid_before(
        datetime.datetime.utcnow()
    ).not_valid_after(
        datetime.datetime.utcnow() + datetime.timedelta(days=days_valid)
    ).sign(private_key, hashes.SHA256(), backends.default_backend())

    return certificate 
Example #2
Source File: hooks_test.py    From dnsrobocert with MIT License 5 votes vote down vote up
def test_pfx(_autorestart, _autocmd, _fix_permissions, fake_env, fake_config):
    archive_path = fake_env["archive"]
    key = rsa.generate_private_key(
        public_exponent=65537, key_size=2048, backend=default_backend()
    )
    with open(archive_path / "privkey.pem", "wb") as f:
        f.write(
            key.private_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PrivateFormat.TraditionalOpenSSL,
                encryption_algorithm=serialization.NoEncryption(),
            )
        )

    subject = issuer = x509.Name(
        [x509.NameAttribute(NameOID.COMMON_NAME, u"example.com")]
    )
    cert = (
        x509.CertificateBuilder()
        .subject_name(subject)
        .issuer_name(issuer)
        .public_key(key.public_key())
        .serial_number(x509.random_serial_number())
        .not_valid_before(datetime.datetime.utcnow())
        .not_valid_after(datetime.datetime.utcnow() + datetime.timedelta(days=10))
        .sign(key, hashes.SHA256(), default_backend())
    )

    with open(archive_path / "cert.pem", "wb") as f:
        f.write(cert.public_bytes(serialization.Encoding.PEM))
    with open(archive_path / "chain.pem", "wb") as f:
        f.write(cert.public_bytes(serialization.Encoding.PEM))

    hooks.deploy(config.load(fake_config), LINEAGE)

    assert os.path.exists(archive_path / "cert.pfx")
    assert os.stat(archive_path / "cert.pfx").st_size != 0 
Example #3
Source File: test_session_resumption.py    From rpaas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def generate_ca(cls):
        key = rsa.generate_private_key(
            public_exponent=65537,
            key_size=2048,
            backend=default_backend()
        )
        subject = issuer = x509.Name([
            x509.NameAttribute(NameOID.COUNTRY_NAME, u"BR"),
            x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u"RJ"),
            x509.NameAttribute(NameOID.LOCALITY_NAME, u"Rio de Janeiro"),
            x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"Tsuru Inc"),
            x509.NameAttribute(NameOID.COMMON_NAME, u"tsuru.io"),
        ])
        cert = x509.CertificateBuilder().subject_name(
            subject
        ).issuer_name(
            issuer
        ).public_key(
            key.public_key()
        ).serial_number(
            x509.random_serial_number()
        ).not_valid_before(
            datetime.datetime.utcnow()
        ).not_valid_after(
            datetime.datetime.utcnow() + datetime.timedelta(days=10)
        ).add_extension(
            x509.SubjectAlternativeName([x509.DNSName(u"tsuru.io")]),
            critical=False,
        ).sign(key, hashes.SHA256(), default_backend())

        key = key.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.TraditionalOpenSSL,
            encryption_algorithm=serialization.NoEncryption(),
        )
        cert = cert.public_bytes(serialization.Encoding.PEM)
        return key, cert 
Example #4
Source File: sslutils.py    From rpaas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def generate_admin_crt(config, host):
    private_key = generate_key()
    public_key = private_key.public_key()
    one_day = datetime.timedelta(1, 0, 0)
    ca_cert = config.get("CA_CERT", None)
    ca_key = config.get("CA_KEY", None)
    cert_expiration = config.get("CERT_ADMIN_EXPIRE", 1825)
    if not ca_cert or not ca_key:
        raise Exception('CA_CERT or CA_KEY not defined')
    ca_key = serialization.load_pem_private_key(str(ca_key), password=None, backend=default_backend())
    ca_cert = x509.load_pem_x509_certificate(str(ca_cert), backend=default_backend())
    builder = x509.CertificateBuilder()
    builder = builder.subject_name(x509.Name([
        x509.NameAttribute(NameOID.COMMON_NAME, host),
    ]))
    builder = builder.issuer_name(ca_cert.subject)
    builder = builder.not_valid_before(datetime.datetime.today() - one_day)
    builder = builder.not_valid_after(datetime.datetime.today() + datetime.timedelta(days=cert_expiration))
    builder = builder.serial_number(x509.random_serial_number())
    builder = builder.public_key(public_key)
    builder = builder.add_extension(
        x509.SubjectAlternativeName(
            [x509.IPAddress(ipaddress.IPv4Address(host))]
        ),
        critical=False
    )
    builder = builder.add_extension(
        x509.BasicConstraints(ca=False, path_length=None), critical=True,
    )
    certificate = builder.sign(
        private_key=ca_key, algorithm=hashes.SHA256(),
        backend=default_backend()
    )
    private_key = private_key.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.TraditionalOpenSSL,
            encryption_algorithm=serialization.NoEncryption(),
        )
    certificate = certificate.public_bytes(serialization.Encoding.PEM)
    return private_key, certificate 
Example #5
Source File: test_verifier.py    From alexa-skills-kit-sdk-for-python with Apache License 2.0 5 votes vote down vote up
def create_certificate(self):
        self.private_key = self.generate_private_key()

        subject = issuer = x509.Name([
            x509.NameAttribute(NameOID.COUNTRY_NAME, u"US"),
            x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u"WA"),
            x509.NameAttribute(NameOID.LOCALITY_NAME, u"Seattle"),
            x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"Amazon Alexa"),
            x509.NameAttribute(
                NameOID.COMMON_NAME, u"{}".format(self.PREPOPULATED_CERT_URL)),
            ])

        self.mock_certificate = x509.CertificateBuilder().subject_name(
            name=subject).issuer_name(
            name=issuer).public_key(
            key=self.private_key.public_key()).serial_number(
            number=x509.random_serial_number()).not_valid_before(
            time=datetime.utcnow() - timedelta(minutes=1)).not_valid_after(
            time=datetime.utcnow() + timedelta(minutes=1)).add_extension(
            extension=x509.SubjectAlternativeName(
                [x509.DNSName(u"{}".format(CERT_CHAIN_DOMAIN))]),
            critical=False).sign(
            private_key=self.private_key,
            algorithm=SHA1(),
            backend=default_backend()
        )

        self.request_verifier._cert_cache[
            self.PREPOPULATED_CERT_URL] = self.mock_certificate 
Example #6
Source File: utils.py    From django-auth-adfs with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def generate_key_and_cert():
    signing_key = rsa.generate_private_key(
        backend=crypto_default_backend(),
        public_exponent=65537,
        key_size=2048
    )
    subject = issuer = x509.Name([
        x509.NameAttribute(NameOID.COUNTRY_NAME, u"US"),
        x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u"CA"),
        x509.NameAttribute(NameOID.LOCALITY_NAME, u"San Francisco"),
        x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"My Company"),
        x509.NameAttribute(NameOID.COMMON_NAME, u"example.com"),
    ])
    signing_cert = x509.CertificateBuilder().subject_name(
        subject
    ).issuer_name(
        issuer
    ).public_key(
        signing_key.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(
        signing_key, hashes.SHA256(), crypto_default_backend()
    ).public_bytes(crypto_serialization.Encoding.DER)
    return signing_key, signing_cert 
Example #7
Source File: _utilities.py    From sros2 with Apache License 2.0 5 votes vote down vote up
def build_key_and_cert(subject_name, *, ca=False, ca_key=None, issuer_name=''):
    if not issuer_name:
        issuer_name = subject_name

    # DDS-Security section 9.3.1 calls for prime256v1, for which SECP256R1 is an alias
    private_key = ec.generate_private_key(ec.SECP256R1, cryptography_backend())
    if not ca_key:
        ca_key = private_key

    if ca:
        extension = x509.BasicConstraints(ca=True, path_length=1)
    else:
        extension = x509.BasicConstraints(ca=False, path_length=None)

    utcnow = datetime.datetime.utcnow()
    builder = x509.CertificateBuilder(
        ).issuer_name(
            issuer_name
        ).serial_number(
            x509.random_serial_number()
        ).not_valid_before(
            # Using a day earlier here to prevent Connext (5.3.1) from complaining
            # when extracting it from the permissions file and thinking it's in the future
            # https://github.com/ros2/ci/pull/436#issuecomment-624874296
            utcnow - datetime.timedelta(days=1)
        ).not_valid_after(
            # TODO: This should not be hard-coded
            utcnow + datetime.timedelta(days=3650)
        ).public_key(
            private_key.public_key()
        ).subject_name(
            subject_name
        ).add_extension(
            extension, critical=ca
        )
    cert = builder.sign(ca_key, hashes.SHA256(), cryptography_backend())

    return (cert, private_key) 
Example #8
Source File: certificatemanager.py    From confidant with Apache License 2.0 5 votes vote down vote up
def generate_self_signed_certificate(self, key, cn, validity, san=None):
        """
        Using the provided rsa key, a string common name, a validity (in number
        of days), and a list of subject alternative names (as strings), generate
        and return a signed certificate object.
        """
        _validity = min(validity, self.settings['max_validity_days'])
        subject = self.generate_x509_name(cn)
        issuer = subject
        # x509.CertificateBuilder functions return modified versions of the
        # object, so it's weirdly meant to be chained as function calls, making
        # this look weirdly javascript-like.
        cert = x509.CertificateBuilder(
        ).subject_name(
            subject,
        ).issuer_name(
            issuer,
        ).public_key(
            key.public_key(),
        ).serial_number(
            x509.random_serial_number(),
        ).not_valid_before(
            datetime.datetime.utcnow(),
        ).not_valid_after(
            datetime.datetime.utcnow() + datetime.timedelta(days=_validity),
        )
        if san:
            dns_names = self.encode_san_dns_names(san)
            cert = cert.add_extension(
                x509.SubjectAlternativeName(dns_names),
                critical=False,
            )
        return cert.sign(key, hashes.SHA256(), default_backend()) 
Example #9
Source File: test_config.py    From python-tripleoclient with Apache License 2.0 5 votes vote down vote up
def get_certificate_and_private_key(self):
        private_key = rsa.generate_private_key(public_exponent=3,
                                               key_size=1024,
                                               backend=default_backend())
        issuer = x509.Name([
            x509.NameAttribute(NameOID.COUNTRY_NAME, u"FI"),
            x509.NameAttribute(NameOID.LOCALITY_NAME, u"Helsinki"),
            x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"Some Company"),
            x509.NameAttribute(NameOID.COMMON_NAME, u"Test Certificate"),
        ])
        cert_builder = x509.CertificateBuilder(
            issuer_name=issuer, subject_name=issuer,
            public_key=private_key.public_key(),
            serial_number=x509.random_serial_number(),
            not_valid_before=datetime.utcnow(),
            not_valid_after=datetime.utcnow() + timedelta(days=10)
        )
        cert = cert_builder.sign(private_key,
                                 hashes.SHA256(),
                                 default_backend())
        cert_pem = cert.public_bytes(encoding=serialization.Encoding.PEM)
        key_pem = private_key.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.TraditionalOpenSSL,
            encryption_algorithm=serialization.NoEncryption())
        return cert_pem, key_pem 
Example #10
Source File: model.py    From skein with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def new_credentials(cls):
        """Create a new Security object with a new certificate/key pair."""
        from cryptography import x509
        from cryptography.hazmat.backends import default_backend
        from cryptography.hazmat.primitives import hashes
        from cryptography.hazmat.primitives import serialization
        from cryptography.hazmat.primitives.asymmetric import rsa
        from cryptography.x509.oid import NameOID

        key = rsa.generate_private_key(public_exponent=65537,
                                       key_size=2048,
                                       backend=default_backend())
        key_bytes = key.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.PKCS8,
            encryption_algorithm=serialization.NoEncryption())

        subject = issuer = x509.Name(
            [x509.NameAttribute(NameOID.COMMON_NAME, u'skein-internal')])
        now = datetime.utcnow()
        cert = (x509.CertificateBuilder()
                    .subject_name(subject)
                    .issuer_name(issuer)
                    .public_key(key.public_key())
                    .serial_number(x509.random_serial_number())
                    .not_valid_before(now)
                    .not_valid_after(now + timedelta(days=365))
                    .sign(key, hashes.SHA256(), default_backend()))

        cert_bytes = cert.public_bytes(serialization.Encoding.PEM)

        return cls(cert_bytes=cert_bytes, key_bytes=key_bytes) 
Example #11
Source File: utils.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def get_cert_builder(expires, serial=None):
    """Get a basic X509 cert builder object.

    .. TODO:: deprecate support for passing datetime as expires

    Parameters
    ----------

    expires : datetime or timedelta
        When this certificate will expire.
    serial : int, optional
        Serial number to set for this certificate. Use :py:func:`~cg:cryptography.x509.random_serial_number`
        to generate such a value. By default, a value will be generated.
    """
    now = datetime.utcnow().replace(second=0, microsecond=0)

    if serial is None:
        serial = x509.random_serial_number()
    if expires is None:
        expires = now + ca_settings.CA_DEFAULT_EXPIRES
    elif isinstance(expires, timedelta):
        expires = now + expires
    else:
        expires = expires.replace(second=0, microsecond=0)

    builder = x509.CertificateBuilder()
    builder = builder.not_valid_before(now)
    builder = builder.not_valid_after(expires)
    builder = builder.serial_number(serial)

    return builder 
Example #12
Source File: ssl.py    From commandment with MIT License 5 votes vote down vote up
def generate_self_signed_certificate(cn: str) -> (rsa.RSAPrivateKey, x509.Certificate):
    """Generate an X.509 Certificate with the given Common Name.
    
    Args:
          cn (string): 
    """
    name = x509.Name([
        x509.NameAttribute(NameOID.COMMON_NAME, cn),
        x509.NameAttribute(NameOID.ORGANIZATION_NAME, 'commandment')
    ])

    private_key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=2048,
        backend=default_backend(),
    )

    certificate = x509.CertificateBuilder().subject_name(
        name
    ).issuer_name(
        name
    ).public_key(
        private_key.public_key()
    ).serial_number(
        x509.random_serial_number()
    ).not_valid_before(
        datetime.datetime.utcnow()
    ).not_valid_after(
        datetime.datetime.utcnow() + datetime.timedelta(days=365)
    ).add_extension(
        x509.SubjectAlternativeName([
            DNSName(cn)
        ]), False
    ).sign(private_key, hashes.SHA256(), default_backend())

    return private_key, certificate 
Example #13
Source File: models.py    From commandment with MIT License 5 votes vote down vote up
def create(cls, common_name: str = 'COMMANDMENT-CA', key_size=2048):
        ca = cls()
        ca.common_name = common_name
        name = x509.Name([
            x509.NameAttribute(NameOID.COMMON_NAME, common_name),
            x509.NameAttribute(NameOID.ORGANIZATION_NAME, 'commandment')
        ])

        private_key = rsa.generate_private_key(
            public_exponent=65537,
            key_size=key_size,
            backend=default_backend(),
        )
        ca.rsa_private_key = RSAPrivateKey.from_crypto(private_key)
        db.session.add(ca.rsa_private_key)

        certificate = x509.CertificateBuilder().subject_name(
            name
        ).issuer_name(
            name
        ).public_key(
            private_key.public_key()
        ).serial_number(
            x509.random_serial_number()
        ).not_valid_before(
            datetime.datetime.utcnow()
        ).not_valid_after(
            datetime.datetime.utcnow() + datetime.timedelta(days=365)
        ).add_extension(
            x509.BasicConstraints(ca=True, path_length=None), True
        ).sign(private_key, hashes.SHA256(), default_backend())

        ca_certificate_model = CACertificate.from_crypto(certificate)
        ca_certificate_model.rsa_private_key = ca.rsa_private_key
        ca.certificate = ca_certificate_model

        db.session.add(ca)
        db.session.commit()

        return ca 
Example #14
Source File: dep.py    From zentral with Apache License 2.0 5 votes vote down vote up
def build_dep_token_certificate(dep_token):
    private_key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=2048,
        backend=default_backend()
    )
    public_key = private_key.public_key()
    builder = x509.CertificateBuilder()
    builder = builder.subject_name(x509.Name([
        x509.NameAttribute(NameOID.COMMON_NAME, u'zentral-dep-token-{}'.format(dep_token.pk)),
    ]))
    builder = builder.issuer_name(x509.Name([
        x509.NameAttribute(NameOID.COMMON_NAME, u'zentral'),
    ]))
    now = timezone.now()
    one_day = datetime.timedelta(days=1)
    builder = builder.not_valid_before(now - one_day)
    builder = builder.not_valid_after(now + 2 * one_day)
    builder = builder.serial_number(x509.random_serial_number())
    builder = builder.public_key(public_key)
    builder = builder.add_extension(
        x509.BasicConstraints(ca=False, path_length=None), critical=True,
    )
    certificate = builder.sign(
        private_key=private_key, algorithm=hashes.SHA256(),
        backend=default_backend()
    )
    return certificate, private_key 
Example #15
Source File: util.py    From CPU-Manager-for-Kubernetes with Apache License 2.0 5 votes vote down vote up
def generate_cert(service, namespace, private_key):
    name = x509.Name([
        x509.NameAttribute(x509.oid.NameOID.COMMON_NAME,
                           "{0}.{1}.svc".format(service, namespace))
    ])

    subj_alternative_names = x509.SubjectAlternativeName([
        x509.DNSName("{0}".format(service)),
        x509.DNSName("{0}.{1}".format(service, namespace)),
        x509.DNSName("{0}.{1}.svc".format(service, namespace)),
    ])

    constraints = x509.BasicConstraints(ca=True, path_length=None)

    now = datetime.now()

    cert_builder = x509.CertificateBuilder()
    cert_builder = (cert_builder.subject_name(name)
                                .issuer_name(name)
                                .add_extension(subj_alternative_names, False)
                                .add_extension(constraints, False)
                                .not_valid_before(now)
                                .not_valid_after(now + timedelta(days=36500))
                                .public_key(private_key.public_key())
                                .serial_number(x509.random_serial_number()))

    cert = cert_builder.sign(private_key, hashes.SHA256(), default_backend())
    return cert 
Example #16
Source File: create_certificates.py    From PyKMIP with Apache License 2.0 5 votes vote down vote up
def create_certificate(subject_name,
                       private_key,
                       signing_certificate,
                       signing_key,
                       days_valid=365,
                       client_auth=False):
    subject = x509.Name([
        x509.NameAttribute(x509.NameOID.ORGANIZATION_NAME, u"Test, Inc."),
        x509.NameAttribute(x509.NameOID.COMMON_NAME, subject_name)
    ])
    builder = x509.CertificateBuilder().subject_name(
        subject
    ).issuer_name(
        signing_certificate.subject
    ).public_key(
        private_key.public_key()
    ).serial_number(
        x509.random_serial_number()
    ).not_valid_before(
        datetime.datetime.utcnow()
    ).not_valid_after(
        datetime.datetime.utcnow() + datetime.timedelta(days=days_valid)
    )

    if client_auth:
        builder = builder.add_extension(
            x509.ExtendedKeyUsage([x509.ExtendedKeyUsageOID.CLIENT_AUTH]),
            critical=True
        )

    certificate = builder.sign(
        signing_key,
        hashes.SHA256(),
        backends.default_backend()
    )
    return certificate 
Example #17
Source File: _certificate_generator.py    From webviz-config with MIT License 5 votes vote down vote up
def certificate_template(
    subject: x509.name.Name,
    issuer: x509.name.Name,
    public_key: x509.name.Name,
    certauthority: bool = False,
) -> x509.base.CertificateBuilder:

    if certauthority:
        not_valid_after = datetime.datetime.utcnow() + datetime.timedelta(days=365 * 10)

    else:  # shorter valid length for on-the-fly certificates
        not_valid_after = datetime.datetime.utcnow() + datetime.timedelta(days=7)

    return (
        x509.CertificateBuilder()
        .subject_name(subject)
        .issuer_name(issuer)
        .public_key(public_key)
        .serial_number(x509.random_serial_number())
        .not_valid_before(datetime.datetime.utcnow())
        .not_valid_after(not_valid_after)
        .add_extension(
            x509.SubjectAlternativeName([x509.DNSName("localhost")]), critical=True
        )
        .add_extension(
            x509.BasicConstraints(ca=certauthority, path_length=None), critical=True
        )
    ) 
Example #18
Source File: mkcerts.py    From postfix-mta-sts-resolver with MIT License 4 votes vote down vote up
def ensure_end_entity_cert(output_dir, names, ca_private_key, ca_cert, end_entity_public_key):
    name = names[0]
    end_entity_cert_filename = os.path.join(output_dir, name + '.' + CERT_EXT)
    if os.path.exists(end_entity_cert_filename):
        return
    ca_public_key = ca_private_key.public_key()
    end_entity_cert = x509.CertificateBuilder().\
        subject_name(x509.Name([
            x509.NameAttribute(NameOID.COMMON_NAME, name),
        ])).\
        issuer_name(ca_cert.subject).\
        not_valid_before(datetime.datetime.today() - DAY).\
        not_valid_after(datetime.datetime.today() + 3650 * DAY).\
        serial_number(x509.random_serial_number()).\
        public_key(end_entity_public_key).\
        add_extension(
            x509.BasicConstraints(ca=False, path_length=None),
            critical=True).\
        add_extension(
            x509.KeyUsage(digital_signature=True,
                          content_commitment=False,
                          key_encipherment=True,
                          data_encipherment=False,
                          key_agreement=False,
                          key_cert_sign=False,
                          crl_sign=False,
                          encipher_only=False,
                          decipher_only=False),
            critical=True).\
        add_extension(
            x509.ExtendedKeyUsage([
                ExtendedKeyUsageOID.SERVER_AUTH,
                ExtendedKeyUsageOID.CLIENT_AUTH,
            ]), critical=False).\
        add_extension(
            x509.AuthorityKeyIdentifier.from_issuer_public_key(ca_public_key),
            critical=False).\
        add_extension(
            x509.SubjectKeyIdentifier.from_public_key(end_entity_public_key),
            critical=False).\
        add_extension(
            x509.SubjectAlternativeName(
                [x509.DNSName(name) for name in names]
            ),
            critical=False
        ).\
        sign(
            private_key=ca_private_key,
            algorithm=hashes.SHA256(),
            backend=default_backend()
        )
    with open(end_entity_cert_filename, "wb") as end_entity_cert_file:
        end_entity_cert_file.write(
            end_entity_cert.public_bytes(encoding=serialization.Encoding.PEM))
    return end_entity_cert 
Example #19
Source File: mkcerts.py    From postfix-mta-sts-resolver with MIT License 4 votes vote down vote up
def ensure_ca_cert(output_dir, ca_private_key):
    ca_cert_filename = os.path.join(output_dir, CA_FILENAME + '.' + CERT_EXT)
    ca_public_key = ca_private_key.public_key()
    if os.path.exists(ca_cert_filename):
        with open(ca_cert_filename, "rb") as ca_cert_file:
            ca_cert = x509.load_pem_x509_certificate(
                ca_cert_file.read(),
                backend=default_backend())
    else:
        iname = x509.Name([
            x509.NameAttribute(NameOID.COMMON_NAME, 'Test CA'),
            x509.NameAttribute(NameOID.ORGANIZATION_NAME,
                'postfix-mta-sts-resolver dev'),
            x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME,
                'postfix-mta-sts-resolver testsuite'),
        ])
        ca_cert = x509.CertificateBuilder().\
            subject_name(iname).\
            issuer_name(iname).\
            not_valid_before(datetime.datetime.today() - DAY).\
            not_valid_after(datetime.datetime.today() + 3650 * DAY).\
            serial_number(x509.random_serial_number()).\
            public_key(ca_public_key).\
            add_extension(
                x509.BasicConstraints(ca=True, path_length=None),
                critical=True).\
            add_extension(
                x509.KeyUsage(digital_signature=False,
                              content_commitment=False,
                              key_encipherment=False,
                              data_encipherment=False,
                              key_agreement=False,
                              key_cert_sign=True,
                              crl_sign=True,
                              encipher_only=False,
                              decipher_only=False),
                critical=True).\
            add_extension(
                x509.SubjectKeyIdentifier.from_public_key(ca_public_key),
                critical=False).\
            sign(
                private_key=ca_private_key,
                algorithm=hashes.SHA256(),
                backend=default_backend()
            )
        with open(ca_cert_filename, "wb") as ca_cert_file:
            ca_cert_file.write(
                ca_cert.public_bytes(encoding=serialization.Encoding.PEM))
    assert isinstance(ca_cert, x509.Certificate)
    return ca_cert 
Example #20
Source File: tls.py    From dask-gateway with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def new_keypair(sni):
    """Create a new self-signed certificate & key pair with the given SNI.

    Parameters
    ----------
    sni : str
        The SNI name to use.

    Returns
    -------
    cert_bytes : bytes
    key_bytes :  bytes
    """
    key = rsa.generate_private_key(
        public_exponent=65537, key_size=2048, backend=default_backend()
    )
    key_bytes = key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.PKCS8,
        encryption_algorithm=serialization.NoEncryption(),
    )

    dask_internal = x509.Name(
        [x509.NameAttribute(NameOID.COMMON_NAME, "dask-internal")]
    )
    altnames = x509.SubjectAlternativeName(
        [
            x509.DNSName(sni),
            x509.DNSName("dask-internal"),
            # allow skein appmaster and dask to share credentials
            x509.DNSName("skein-internal"),
        ]
    )
    now = datetime.utcnow()
    cert = (
        x509.CertificateBuilder()
        .subject_name(dask_internal)
        .issuer_name(dask_internal)
        .add_extension(altnames, critical=False)
        .public_key(key.public_key())
        .serial_number(x509.random_serial_number())
        .not_valid_before(now)
        .not_valid_after(now + timedelta(days=365))
        .sign(key, hashes.SHA256(), default_backend())
    )

    cert_bytes = cert.public_bytes(serialization.Encoding.PEM)

    return cert_bytes, key_bytes