Python cryptography.x509.NameAttribute() Examples

The following are 30 code examples of cryptography.x509.NameAttribute(). 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: certrequest.py    From custodia with GNU General Public License v3.0 7 votes vote down vote up
def build_csr(self, hostname, **kwargs):
        realm = self.plugin.ipa.env.realm
        builder = x509.CertificateSigningRequestBuilder()
        builder = builder.subject_name(
            x509.Name([
                x509.NameAttribute(oid.NameOID.COMMON_NAME, hostname),
                x509.NameAttribute(oid.NameOID.ORGANIZATION_NAME, realm),
            ])
        )
        build = builder.add_extension(
            x509.BasicConstraints(ca=False, path_length=None), critical=True,
        )
        build = builder.add_extension(
            x509.ExtendedKeyUsage([TLS_SERVERAUTH]), critical=True
        )
        builder = build.add_extension(
            x509.SubjectAlternativeName([x509.DNSName(hostname)]),
            critical=False
        )
        return builder

    # pylint: disable=arguments-differ 
Example #2
Source File: utils.py    From django-ca with GNU General Public License v3.0 6 votes vote down vote up
def x509_relative_name(name):
    """Parse a relative name (RDN) into a :py:class:`~cg:cryptography.x509.RelativeDistinguishedName`.

    >>> x509_relative_name('/CN=example.com')
    <RelativeDistinguishedName(CN=example.com)>
    >>> x509_relative_name([('CN', 'example.com')])
    <RelativeDistinguishedName(CN=example.com)>
    """
    if isinstance(name, x509.RelativeDistinguishedName):
        return name
    elif isinstance(name, str):
        name = parse_name(name)

    return x509.RelativeDistinguishedName([
        x509.NameAttribute(NAME_OID_MAPPINGS[typ], force_text(value)) for typ, value in name
    ]) 
Example #3
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 #4
Source File: crypto.py    From manuale with MIT License 6 votes vote down vote up
def create_csr(key, domains, must_staple=False):
    """
    Creates a CSR in DER format for the specified key and domain names.
    """
    assert domains
    name = x509.Name([
        x509.NameAttribute(NameOID.COMMON_NAME, domains[0]),
    ])
    san = x509.SubjectAlternativeName([x509.DNSName(domain) for domain in domains])
    csr = x509.CertificateSigningRequestBuilder().subject_name(name) \
        .add_extension(san, critical=False)
    if must_staple:
        ocsp_must_staple = x509.TLSFeature(features=[x509.TLSFeatureType.status_request])
        csr = csr.add_extension(ocsp_must_staple, critical=False)
    csr = csr.sign(key, hashes.SHA256(), default_backend())
    return export_csr_for_acme(csr) 
Example #5
Source File: utils.py    From django-ca with GNU General Public License v3.0 6 votes vote down vote up
def format_relative_name(name):
    """Convert a relative name (RDN) into a canonical form.

    Examples::

        >>> format_relative_name([('C', 'AT'), ('CN', 'example.com')])
        '/C=AT/CN=example.com'
        >>> format_relative_name(x509.RelativeDistinguishedName([
        ...     x509.NameAttribute(NameOID.COMMON_NAME, u'example.com')
        ... ]))
        '/CN=example.com'
    """
    if isinstance(name, x509.RelativeDistinguishedName):
        name = [(OID_NAME_MAPPINGS[s.oid], s.value) for s in name]

    return '/%s' % ('/'.join(['%s=%s' % (force_text(k), force_text(v)) for k, v in name])) 
Example #6
Source File: test_crypto.py    From pyopenssl with Apache License 2.0 6 votes vote down vote up
def test_export_pem(self):
        """
        If not passed a format, ``CRL.export`` returns a "PEM" format string
        representing a serial number, a revoked reason, and certificate issuer
        information.
        """
        # PEM format
        dumped_crl = self._get_crl().export(
            self.cert, self.pkey, days=20, digest=b"sha256"
        )
        crl = x509.load_pem_x509_crl(dumped_crl, backend)
        revoked = crl.get_revoked_certificate_by_serial_number(0x03AB)
        assert revoked is not None
        assert crl.issuer == x509.Name([
            x509.NameAttribute(x509.NameOID.COUNTRY_NAME, u"US"),
            x509.NameAttribute(x509.NameOID.STATE_OR_PROVINCE_NAME, u"IL"),
            x509.NameAttribute(x509.NameOID.LOCALITY_NAME, u"Chicago"),
            x509.NameAttribute(x509.NameOID.ORGANIZATION_NAME, u"Testing"),
            x509.NameAttribute(x509.NameOID.COMMON_NAME, u"Testing Root CA"),
        ]) 
Example #7
Source File: test_crypto.py    From pyopenssl with Apache License 2.0 6 votes vote down vote up
def test_export_der(self):
        """
        If passed ``FILETYPE_ASN1`` for the format, ``CRL.export`` returns a
        "DER" format string representing a serial number, a revoked reason, and
        certificate issuer information.
        """
        crl = self._get_crl()

        # DER format
        dumped_crl = self._get_crl().export(
            self.cert, self.pkey, FILETYPE_ASN1, digest=b"md5"
        )
        crl = x509.load_der_x509_crl(dumped_crl, backend)
        revoked = crl.get_revoked_certificate_by_serial_number(0x03AB)
        assert revoked is not None
        assert crl.issuer == x509.Name([
            x509.NameAttribute(x509.NameOID.COUNTRY_NAME, u"US"),
            x509.NameAttribute(x509.NameOID.STATE_OR_PROVINCE_NAME, u"IL"),
            x509.NameAttribute(x509.NameOID.LOCALITY_NAME, u"Chicago"),
            x509.NameAttribute(x509.NameOID.ORGANIZATION_NAME, u"Testing"),
            x509.NameAttribute(x509.NameOID.COMMON_NAME, u"Testing Root CA"),
        ])

    # Flaky because we compare the output of running commands which sometimes
    # varies by 1 second 
Example #8
Source File: conftest.py    From commandment with MIT License 6 votes vote down vote up
def ca_certificate(private_key: rsa.RSAPrivateKey) -> x509.Certificate:
    b = x509.CertificateBuilder()
    name = 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"Commandment"),
        x509.NameAttribute(NameOID.COMMON_NAME, u"CA-CERTIFICATE"),
    ])

    cert = b.serial_number(1).issuer_name(
        name
    ).subject_name(
        name
    ).public_key(
        private_key.public_key()
    ).not_valid_before(
        datetime.datetime.utcnow()
    ).not_valid_after(
        datetime.datetime.utcnow() + datetime.timedelta(days=10)
    ).add_extension(
        x509.BasicConstraints(ca=True, path_length=None), True
    ).sign(private_key, hashes.SHA256(), default_backend())

    return cert 
Example #9
Source File: test_mdmcert.py    From commandment with MIT License 6 votes vote down vote up
def csr(private_key: rsa.RSAPrivateKey) -> x509.CertificateSigningRequest:
    b = x509.CertificateSigningRequestBuilder()
    req = b.subject_name(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"Commandment"),
        x509.NameAttribute(NameOID.COMMON_NAME, u"Commandment"),
    ])).sign(private_key, hashes.SHA256(), default_backend())

    return req 
Example #10
Source File: sslutils.py    From rpaas with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def generate_csr(key, domainname):
    private_key = serialization.load_pem_private_key(key, password=None,
                                                     backend=default_backend())
    csr = x509.CertificateSigningRequestBuilder().subject_name(x509.Name([
        # Provide various details about who we are.
        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"globo.com"),
        x509.NameAttribute(NameOID.COMMON_NAME, domainname),
    ])).add_extension(
        x509.SubjectAlternativeName([x509.DNSName(domainname)]),
        critical=False,
    ).sign(private_key, hashes.SHA256(), default_backend())

    return csr.public_bytes(serialization.Encoding.PEM) 
Example #11
Source File: conftest.py    From commandment with MIT License 6 votes vote down vote up
def certificate(private_key: rsa.RSAPrivateKey) -> x509.Certificate:
    b = x509.CertificateBuilder()
    name = 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"Commandment"),
        x509.NameAttribute(NameOID.COMMON_NAME, u"CA-CERTIFICATE"),
    ])

    cer = b.subject_name(name).issuer_name(name).public_key(
        private_key.public_key()
    ).serial_number(1).not_valid_before(
        datetime.datetime.utcnow()
    ).not_valid_after(
        datetime.datetime.utcnow() + datetime.timedelta(days=10)
    ).add_extension(
        x509.BasicConstraints(ca=False, path_length=None), True
    ).sign(private_key, hashes.SHA256(), default_backend())

    return cer 
Example #12
Source File: tests_utils.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def test_dirname(self):
        name = x509.DirectoryName(x509.Name([
            x509.NameAttribute(NameOID.COUNTRY_NAME, 'AT'),
            x509.NameAttribute(NameOID.COMMON_NAME, 'example.com'),
        ]))
        self.assertEqual(format_general_name(name), 'dirname:/C=AT/CN=example.com') 
Example #13
Source File: decode_asn1.py    From quickstart-redhat-openshift with Apache License 2.0 5 votes vote down vote up
def _decode_x509_name_entry(backend, x509_name_entry):
    obj = backend._lib.X509_NAME_ENTRY_get_object(x509_name_entry)
    backend.openssl_assert(obj != backend._ffi.NULL)
    data = backend._lib.X509_NAME_ENTRY_get_data(x509_name_entry)
    backend.openssl_assert(data != backend._ffi.NULL)
    value = _asn1_string_to_utf8(backend, data)
    oid = _obj2txt(backend, obj)
    type = _ASN1_TYPE_TO_ENUM[data.type]

    return x509.NameAttribute(x509.ObjectIdentifier(oid), value, type) 
Example #14
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 #15
Source File: decode_asn1.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _decode_x509_name_entry(backend, x509_name_entry):
    obj = backend._lib.X509_NAME_ENTRY_get_object(x509_name_entry)
    backend.openssl_assert(obj != backend._ffi.NULL)
    data = backend._lib.X509_NAME_ENTRY_get_data(x509_name_entry)
    backend.openssl_assert(data != backend._ffi.NULL)
    value = _asn1_string_to_utf8(backend, data)
    oid = _obj2txt(backend, obj)
    type = _ASN1_TYPE_TO_ENUM[data.type]

    return x509.NameAttribute(x509.ObjectIdentifier(oid), value, type) 
Example #16
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 #17
Source File: tls.py    From dcos-e2e with Apache License 2.0 5 votes vote down vote up
def cert_name(common_name):
    """
    Create x509.Name
    """
    return x509.Name([
        x509.NameAttribute(NameOID.COUNTRY_NAME, "US"),
        x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, "CA"),
        x509.NameAttribute(NameOID.LOCALITY_NAME, "San Francisco"),
        x509.NameAttribute(NameOID.ORGANIZATION_NAME, "D2iQ, Inc."),
        x509.NameAttribute(NameOID.COMMON_NAME, common_name),
        ]) 
Example #18
Source File: tls.py    From dcos-e2e with Apache License 2.0 5 votes vote down vote up
def cert_name(common_name):
    """
    Create x509.Name
    """
    return x509.Name([
        x509.NameAttribute(NameOID.COUNTRY_NAME, "US"),
        x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, "CA"),
        x509.NameAttribute(NameOID.LOCALITY_NAME, "San Francisco"),
        x509.NameAttribute(NameOID.ORGANIZATION_NAME, "D2iQ, Inc."),
        x509.NameAttribute(NameOID.COMMON_NAME, common_name),
        ]) 
Example #19
Source File: test_ssl.py    From pyopenssl with Apache License 2.0 5 votes vote down vote up
def ca_file(tmpdir):
    """
    Create a valid PEM file with CA certificates and return the path.
    """
    key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=2048,
        backend=default_backend()
    )
    public_key = key.public_key()

    builder = x509.CertificateBuilder()
    builder = builder.subject_name(x509.Name([
        x509.NameAttribute(NameOID.COMMON_NAME, u"pyopenssl.org"),
    ]))
    builder = builder.issuer_name(x509.Name([
        x509.NameAttribute(NameOID.COMMON_NAME, u"pyopenssl.org"),
    ]))
    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)
    builder = builder.serial_number(int(uuid.uuid4()))
    builder = builder.public_key(public_key)
    builder = builder.add_extension(
        x509.BasicConstraints(ca=True, path_length=None), critical=True,
    )

    certificate = builder.sign(
        private_key=key, algorithm=hashes.SHA256(),
        backend=default_backend()
    )

    ca_file = tmpdir.join("test.pem")
    ca_file.write_binary(
        certificate.public_bytes(
            encoding=serialization.Encoding.PEM,
        )
    )

    return str(ca_file).encode("ascii") 
Example #20
Source File: cert.py    From lxd-image-server with Apache License 2.0 5 votes vote down vote up
def generate_cert(path):
    key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=2048,
        backend=default_backend()
    )

    name = x509.Name([
        x509.NameAttribute(NameOID.COMMON_NAME, u"lxd-image-server.localhost")])

    now = datetime.utcnow()
    basic_contraints = x509.BasicConstraints(ca=True, path_length=0)
    ip_address = get_address()
    cert = (
        x509.CertificateBuilder()
        .subject_name(name)
        .issuer_name(name)
        .public_key(key.public_key())
        .serial_number(1000)
        .not_valid_before(now - timedelta(days=10))
        .not_valid_after(now + timedelta(days=10 * 365))
        .add_extension(basic_contraints, False)
        .add_extension(
            x509.SubjectAlternativeName([
                x509.DNSName(u"lxd.localhost")]),
            critical=False,)
        .sign(key, hashes.SHA256(), default_backend()))

    with open(join(path, KEY_FILE), 'wb') as f:
        f.write(key.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.TraditionalOpenSSL,
            encryption_algorithm=serialization.NoEncryption(),))

    with open(join(path, CERT_FILE), 'wb') as f:
        f.write(cert.public_bytes(serialization.Encoding.PEM)) 
Example #21
Source File: base.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def rdn(r):  # just a shortcut
    return x509.RelativeDistinguishedName([x509.NameAttribute(*t) for t in r]) 
Example #22
Source File: tests_subject.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def test_init_name(self):
        name = x509.Name(attributes=[
            x509.NameAttribute(oid=NameOID.COUNTRY_NAME, value=u'AT'),
            x509.NameAttribute(oid=NameOID.COMMON_NAME, value=u'example.com'),
        ])
        self.assertEqual(str(Subject(name)), '/C=AT/CN=example.com') 
Example #23
Source File: tests_utils.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def test_parse(self):
        expected = x509.RelativeDistinguishedName([x509.NameAttribute(NameOID.COMMON_NAME, u'example.com')])
        self.assertEqual(x509_relative_name('/CN=example.com'), expected)
        self.assertEqual(x509_relative_name([('CN', 'example.com')]), expected) 
Example #24
Source File: tests_utils.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def test_format(self):
        rdn = x509.RelativeDistinguishedName([x509.NameAttribute(NameOID.COMMON_NAME, u'example.com')])
        self.assertEqual(format_relative_name([('C', 'AT'), ('CN', 'example.com')]), '/C=AT/CN=example.com')
        self.assertEqual(format_relative_name(rdn), '/CN=example.com') 
Example #25
Source File: ssl.py    From commandment with MIT License 5 votes vote down vote up
def generate_signing_request(cn: str, dnsname: Optional[str] = None) -> (rsa.RSAPrivateKey, x509.CertificateSigningRequest):
    """Generate a Private Key + Certificate Signing Request using the given dnsname as the CN and SAN dNSName.
    
    Args:
            cn (str): The certificate common name
          dnsname (str): The public facing dns name of the MDM server.
    Returns:
          Tuple of rsa private key, csr
    """
    private_key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=2048,
        backend=default_backend(),
    )

    name = x509.Name([
        x509.NameAttribute(NameOID.COMMON_NAME, cn),
        x509.NameAttribute(NameOID.ORGANIZATION_NAME, 'commandment')
    ])

    builder = x509.CertificateSigningRequestBuilder()
    builder = builder.subject_name(name)

    if dnsname is not None:
        san = x509.SubjectAlternativeName([
            x509.DNSName(dnsname)
        ])
        builder = builder.add_extension(san, critical=True)

    builder = builder.add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True)
    
    request = builder.sign(
        private_key,
        hashes.SHA256(),
        default_backend()
    )

    return private_key, request 
Example #26
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 #27
Source File: utils.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def x509_name(name):
    """Parses a subject into a :py:class:`x509.Name <cg:cryptography.x509.Name>`.

    If ``name`` is a string, :py:func:`parse_name` is used to parse it.

    >>> x509_name('/C=AT/CN=example.com')
    <Name(C=AT,CN=example.com)>
    >>> x509_name([('C', 'AT'), ('CN', 'example.com')])
    <Name(C=AT,CN=example.com)>
    """
    if isinstance(name, str):
        name = parse_name(name)

    return x509.Name([x509.NameAttribute(NAME_OID_MAPPINGS[typ], force_text(value)) for typ, value in name]) 
Example #28
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 #29
Source File: crypto_test.py    From fabric-sdk-py with Apache License 2.0 5 votes vote down vote up
def test_ecies_generate_csr(self):
        """Test case for generate certificate signing request."""
        ecies256 = ecies()
        private_key = ecies256.generate_private_key()
        csr = ecies256.generate_csr(private_key, x509.Name(
            [x509.NameAttribute(NameOID.COMMON_NAME, u"test")]))
        csr_pem = csr.public_bytes(Encoding.PEM)
        self.assertTrue(csr_pem.startswith(
            b"-----BEGIN CERTIFICATE REQUEST-----")) 
Example #30
Source File: conftest.py    From commandment with MIT License 5 votes vote down vote up
def csr(private_key: rsa.RSAPrivateKey) -> x509.CertificateSigningRequest:
    b = x509.CertificateSigningRequestBuilder()
    req = b.subject_name(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"Commandment"),
        x509.NameAttribute(NameOID.COMMON_NAME, u"Commandment"),
    ])).sign(private_key, hashes.SHA256(), default_backend())

    return req