当前位置: 首页>>代码示例>>Python>>正文


Python x509.random_serial_number方法代码示例

本文整理汇总了Python中cryptography.x509.random_serial_number方法的典型用法代码示例。如果您正苦于以下问题:Python x509.random_serial_number方法的具体用法?Python x509.random_serial_number怎么用?Python x509.random_serial_number使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在cryptography.x509的用法示例。


在下文中一共展示了x509.random_serial_number方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: create_self_signed_certificate

# 需要导入模块: from cryptography import x509 [as 别名]
# 或者: from cryptography.x509 import random_serial_number [as 别名]
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 
开发者ID:OpenKMIP,项目名称:PyKMIP,代码行数:24,代码来源:create_certificates.py

示例2: certificate_template

# 需要导入模块: from cryptography import x509 [as 别名]
# 或者: from cryptography.x509 import random_serial_number [as 别名]
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
        )
    ) 
开发者ID:equinor,项目名称:webviz-config,代码行数:30,代码来源:_certificate_generator.py

示例3: test_pfx

# 需要导入模块: from cryptography import x509 [as 别名]
# 或者: from cryptography.x509 import random_serial_number [as 别名]
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 
开发者ID:adferrand,项目名称:dnsrobocert,代码行数:39,代码来源:hooks_test.py

示例4: create_certificate

# 需要导入模块: from cryptography import x509 [as 别名]
# 或者: from cryptography.x509 import random_serial_number [as 别名]
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 
开发者ID:OpenKMIP,项目名称:PyKMIP,代码行数:38,代码来源:create_certificates.py

示例5: generate_cert

# 需要导入模块: from cryptography import x509 [as 别名]
# 或者: from cryptography.x509 import random_serial_number [as 别名]
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 
开发者ID:intel,项目名称:CPU-Manager-for-Kubernetes,代码行数:30,代码来源:util.py

示例6: build_dep_token_certificate

# 需要导入模块: from cryptography import x509 [as 别名]
# 或者: from cryptography.x509 import random_serial_number [as 别名]
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 
开发者ID:zentralopensource,项目名称:zentral,代码行数:30,代码来源:dep.py

示例7: create

# 需要导入模块: from cryptography import x509 [as 别名]
# 或者: from cryptography.x509 import random_serial_number [as 别名]
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 
开发者ID:cmdmnt,项目名称:commandment,代码行数:42,代码来源:models.py

示例8: generate_self_signed_certificate

# 需要导入模块: from cryptography import x509 [as 别名]
# 或者: from cryptography.x509 import random_serial_number [as 别名]
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 
开发者ID:cmdmnt,项目名称:commandment,代码行数:38,代码来源:ssl.py

示例9: get_cert_builder

# 需要导入模块: from cryptography import x509 [as 别名]
# 或者: from cryptography.x509 import random_serial_number [as 别名]
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 
开发者ID:mathiasertl,项目名称:django-ca,代码行数:33,代码来源:utils.py

示例10: new_credentials

# 需要导入模块: from cryptography import x509 [as 别名]
# 或者: from cryptography.x509 import random_serial_number [as 别名]
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) 
开发者ID:jcrist,项目名称:skein,代码行数:34,代码来源:model.py

示例11: get_certificate_and_private_key

# 需要导入模块: from cryptography import x509 [as 别名]
# 或者: from cryptography.x509 import random_serial_number [as 别名]
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 
开发者ID:openstack,项目名称:python-tripleoclient,代码行数:28,代码来源:test_config.py

示例12: generate_self_signed_certificate

# 需要导入模块: from cryptography import x509 [as 别名]
# 或者: from cryptography.x509 import random_serial_number [as 别名]
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()) 
开发者ID:lyft,项目名称:confidant,代码行数:35,代码来源:certificatemanager.py

示例13: build_key_and_cert

# 需要导入模块: from cryptography import x509 [as 别名]
# 或者: from cryptography.x509 import random_serial_number [as 别名]
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) 
开发者ID:ros2,项目名称:sros2,代码行数:40,代码来源:_utilities.py

示例14: generate_key_and_cert

# 需要导入模块: from cryptography import x509 [as 别名]
# 或者: from cryptography.x509 import random_serial_number [as 别名]
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 
开发者ID:jobec,项目名称:django-auth-adfs,代码行数:33,代码来源:utils.py

示例15: create_certificate

# 需要导入模块: from cryptography import x509 [as 别名]
# 或者: from cryptography.x509 import random_serial_number [as 别名]
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 
开发者ID:alexa,项目名称:alexa-skills-kit-sdk-for-python,代码行数:31,代码来源:test_verifier.py


注:本文中的cryptography.x509.random_serial_number方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。