Python cryptography.x509.oid.NameOID.COMMON_NAME Examples

The following are 30 code examples of cryptography.x509.oid.NameOID.COMMON_NAME(). 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.oid.NameOID , or try the search function .
Example #1
Source File: certificates.py    From core with GNU General Public License v3.0 7 votes vote down vote up
def _scan_a_cert(id, cert_path, key_path, assigns, is_acme=False):
    with open(cert_path, "rb") as f:
        crt = x509.load_pem_x509_certificate(f.read(), default_backend())
    with open(key_path, "rb") as f:
        key = serialization.load_pem_private_key(
            f.read(),
            password=None,
            backend=default_backend()
        )
    sha1 = binascii.hexlify(crt.fingerprint(hashes.SHA1())).decode()
    md5 = binascii.hexlify(crt.fingerprint(hashes.MD5())).decode()
    sha1 = ":".join([sha1[i:i+2].upper() for i in range(0, len(sha1), 2)])
    md5 = ":".join([md5[i:i+2].upper() for i in range(0, len(md5), 2)])
    kt = "RSA" if isinstance(key.public_key(), rsa.RSAPublicKey) else "DSA"
    common_name = crt.subject.get_attributes_for_oid(NameOID.COMMON_NAME)
    return Certificate(
        id=id, cert_path=cert_path, key_path=key_path, keytype=kt,
        keylength=key.key_size, domain=common_name[0].value,
        assigns=assigns.get(id, []), expiry=crt.not_valid_after, sha1=sha1,
        md5=md5, is_acme=is_acme) 
Example #2
Source File: utils.py    From python-magnumclient with Apache License 2.0 6 votes vote down vote up
def generate_csr_and_key():
    """Return a dict with a new csr and key."""
    key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=2048,
        backend=default_backend())

    csr = x509.CertificateSigningRequestBuilder().subject_name(
        x509.Name([
            x509.NameAttribute(NameOID.COMMON_NAME, u"admin"),
            x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"system:masters")
        ])).sign(key, hashes.SHA256(), default_backend())

    result = {
        'csr': csr.public_bytes(
            encoding=serialization.Encoding.PEM).decode("utf-8"),
        'key': key.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.TraditionalOpenSSL,
            encryption_algorithm=serialization.NoEncryption()).decode("utf-8"),
    }

    return result 
Example #3
Source File: tests_subject.py    From django-ca with GNU General Public License v3.0 6 votes vote down vote up
def test_getitem(self):
        self.assertEqual(Subject('/CN=example.com')['CN'], 'example.com')
        self.assertEqual(Subject('/C=AT/CN=example.com')['C'], 'AT')
        self.assertEqual(Subject('/C=AT/CN=example.com')['CN'], 'example.com')

        # try NameOID:
        self.assertEqual(Subject('/CN=example.com')[NameOID.COMMON_NAME], 'example.com')
        self.assertEqual(Subject('/C=AT/CN=example.com')[NameOID.COUNTRY_NAME], 'AT')
        self.assertEqual(Subject('/C=AT/CN=example.com')[NameOID.COMMON_NAME], 'example.com')

        # OUs
        self.assertEqual(Subject('/C=AT/OU=foo/CN=example.com')['OU'], ['foo'])
        self.assertEqual(Subject('/C=AT/OU=foo/OU=bar/CN=example.com')['OU'], ['foo', 'bar'])

        # test keyerror
        with self.assertRaisesRegex(KeyError, r"^'L'$"):
            Subject('/C=AT/OU=foo/CN=example.com')['L']

        with self.assertRaisesRegex(KeyError, r"^'L'$"):
            Subject('/C=AT/OU=foo/CN=example.com')[NameOID.LOCALITY_NAME] 
Example #4
Source File: tests_subject.py    From django-ca with GNU General Public License v3.0 6 votes vote down vote up
def test_get(self):
        self.assertEqual(Subject('/CN=example.com').get('CN'), 'example.com')
        self.assertEqual(Subject('/C=AT/CN=example.com').get('C'), 'AT')
        self.assertEqual(Subject('/C=AT/CN=example.com').get('CN'), 'example.com')

        # try NameOID:
        self.assertEqual(Subject('/CN=example.com').get(NameOID.COMMON_NAME), 'example.com')
        self.assertEqual(Subject('/C=AT/CN=example.com').get(NameOID.COUNTRY_NAME), 'AT')
        self.assertEqual(Subject('/C=AT/CN=example.com').get(NameOID.COMMON_NAME), 'example.com')

        # OUs
        self.assertEqual(Subject('/C=AT/OU=foo/CN=example.com').get('OU'), ['foo'])
        self.assertEqual(Subject('/C=AT/OU=foo/OU=bar/CN=example.com').get('OU'), ['foo', 'bar'])

        # test that default doesn't overwrite anytying
        self.assertEqual(Subject('/CN=example.com').get('CN', 'x'), 'example.com')
        self.assertEqual(Subject('/C=AT/CN=example.com').get('C', 'x'), 'AT')
        self.assertEqual(Subject('/C=AT/CN=example.com').get('CN', 'x'), 'example.com')

        # test default value
        self.assertIsNone(Subject('/C=AT/OU=foo/CN=example.com').get('L'))
        self.assertEqual(Subject('/C=AT/OU=foo/CN=example.com').get('L', 'foo'), 'foo')
        self.assertIsNone(Subject('/C=AT/OU=foo/CN=example.com').get(NameOID.LOCALITY_NAME))
        self.assertEqual(Subject('/C=AT/OU=foo/CN=example.com').get(NameOID.LOCALITY_NAME, 'foo'), 'foo') 
Example #5
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 #6
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 #7
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 #8
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 #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: tests_subject.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def test_contains(self):
        self.assertIn('CN', Subject('/CN=example.com'))
        self.assertIn(NameOID.COMMON_NAME, Subject('/CN=example.com'))
        self.assertNotIn(NameOID.LOCALITY_NAME, Subject('/CN=example.com'))
        self.assertNotIn(NameOID.COUNTRY_NAME, Subject('/CN=example.com'))
        self.assertIn(NameOID.COUNTRY_NAME, Subject('/C=AT/CN=example.com'))
        self.assertIn(NameOID.COMMON_NAME, Subject('/C=AT/CN=example.com')) 
Example #11
Source File: default.py    From rpaas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def download_crt(self, key=None):
        one_day = datetime.timedelta(1, 0, 0)

        private_key = serialization.load_pem_private_key(
            key,
            password=None,
            backend=default_backend()
        )

        public_key = private_key.public_key()

        builder = x509.CertificateBuilder()
        builder = builder.subject_name(x509.Name([
            x509.NameAttribute(NameOID.COMMON_NAME, self.domain),
        ]))
        builder = builder.issuer_name(x509.Name([
            x509.NameAttribute(NameOID.COMMON_NAME, self.domain),
        ]))
        builder = builder.not_valid_before(datetime.datetime.today() - one_day)
        builder = builder.not_valid_after(datetime.datetime(2018, 8, 2))
        builder = builder.serial_number(int(uuid.uuid4()))
        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.public_bytes(serialization.Encoding.PEM) 
Example #12
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 #13
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 #14
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 #15
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 #16
Source File: __init__.py    From agent with MIT License 5 votes vote down vote up
def get_device_id(dev=False):
    """
    Returns the WoTT Device ID (i.e. fqdn) by reading the first subject from
    the certificate on disk.
    """

    can_read_cert()

    with open(CLIENT_CERT_PATH, 'r') as f:
        cert = x509.load_pem_x509_certificate(
            f.read().encode(), default_backend()
        )

    return cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME)[0].value 
Example #17
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 #18
Source File: ssl.py    From ripe-atlas-sagan with GNU General Public License v3.0 5 votes vote down vote up
def _parse_x509_name(name):
        cn = None
        o = None
        c = None
        for attr in name:
            if attr.oid == NameOID.COUNTRY_NAME:
                c = attr.value
            elif attr.oid == NameOID.ORGANIZATION_NAME:
                o = attr.value
            elif attr.oid == NameOID.COMMON_NAME:
                cn = attr.value
        return cn, o, c 
Example #19
Source File: __init__.py    From agent with MIT License 5 votes vote down vote up
def generate_cert(device_id):
    private_key = ec.generate_private_key(
        ec.SECP256R1(), default_backend()
    )
    builder = x509.CertificateSigningRequestBuilder()

    builder = builder.subject_name(x509.Name([
        x509.NameAttribute(NameOID.COMMON_NAME, u'{}'.format(device_id)),
        x509.NameAttribute(NameOID.COUNTRY_NAME, u'UK'),
        x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u'London'),
        x509.NameAttribute(NameOID.ORGANIZATION_NAME, u'Web of Trusted Things, Ltd'),
    ]))

    builder = builder.add_extension(
        x509.SubjectAlternativeName(
            [x509.DNSName(u'{}'.format(device_id))]
        ),
        critical=False
    )

    csr = builder.sign(private_key, hashes.SHA256(), default_backend())

    serialized_private_key = private_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.PKCS8,
        encryption_algorithm=serialization.NoEncryption(),
    )
    serialized_csr = csr.public_bytes(serialization.Encoding.PEM)

    return {
        'csr': serialized_csr.decode(),
        'key': serialized_private_key.decode()
    } 
Example #20
Source File: tls.py    From dcos-e2e with Apache License 2.0 5 votes vote down vote up
def common_names(cert):
    return [x.value for x in cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME)] 
Example #21
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 #22
Source File: crypto.py    From python-eduvpn-client with GNU General Public License v3.0 5 votes vote down vote up
def common_name_from_cert(pem_data):  # type: (bytes) -> str
    """
    Extract common name from client certificate.

    args:
        pem_data (str): PEM encoded certificate
    returns:
        str: the common name of the client certificate.
    """
    cert = x509.load_pem_x509_certificate(pem_data, default_backend())
    return cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME)[0].value 
Example #23
Source File: tls.py    From dcos-e2e with Apache License 2.0 5 votes vote down vote up
def common_names(cert):
    return [x.value for x in cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME)] 
Example #24
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 #25
Source File: certificatemanager.py    From confidant with Apache License 2.0 5 votes vote down vote up
def get_csr_common_name(self, csr):
        """
        From the provided csr object, return the string value of the common
        name attribute.
        """
        cns = csr.subject.get_attributes_for_oid(NameOID.COMMON_NAME)
        if cns:
            # get_attributes_for_oid returns a list, but there should only be a
            # single cn attribute, so just return the first item.
            return cns[0].value
        return None 
Example #26
Source File: certificatemanager.py    From confidant with Apache License 2.0 5 votes vote down vote up
def generate_x509_name(self, cn):
        """
        For the given common name string, generate and return an x509.Name, with
        attributes configured in the settings.
        """
        name_attributes = [
            x509.NameAttribute(NameOID.COMMON_NAME, cn),
        ]
        if self.settings['csr_country_name']:
            name_attributes.append(
                x509.NameAttribute(
                    NameOID.COUNTRY_NAME,
                    self.settings['csr_country_name'],
                )
            )
        if self.settings['csr_state_or_province_name']:
            name_attributes.append(
                x509.NameAttribute(
                    NameOID.STATE_OR_PROVINCE_NAME,
                    self.settings['csr_state_or_province_name'],
                )
            )
        if self.settings['csr_locality_name']:
            name_attributes.append(
                x509.NameAttribute(
                    NameOID.LOCALITY_NAME,
                    self.settings['csr_locality_name'],
                )
            )
        if self.settings['csr_organization_name']:
            name_attributes.append(
                x509.NameAttribute(
                    NameOID.ORGANIZATION_NAME,
                    self.settings['csr_organization_name'],
                )
            )
        return x509.Name(name_attributes) 
Example #27
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 #28
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 #29
Source File: tests_subject.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def test_fields(self):
        s = Subject('')
        self.assertEqual(list(s.fields), [])

        s = Subject('/C=AT')
        self.assertEqual(list(s.fields), [(NameOID.COUNTRY_NAME, 'AT')])

        s = Subject('/C=AT/CN=example.com')
        self.assertEqual(list(s.fields), [(NameOID.COUNTRY_NAME, 'AT'), (NameOID.COMMON_NAME, 'example.com')])

        s = Subject('/C=AT/OU=foo/CN=example.com')
        self.assertEqual(list(s.fields), [(NameOID.COUNTRY_NAME, 'AT'),
                                          (NameOID.ORGANIZATIONAL_UNIT_NAME, 'foo'),
                                          (NameOID.COMMON_NAME, 'example.com')])
        s = Subject('/C=AT/OU=foo/OU=bar/CN=example.com')
        self.assertEqual(list(s.fields), [(NameOID.COUNTRY_NAME, 'AT'),
                                          (NameOID.ORGANIZATIONAL_UNIT_NAME, 'foo'),
                                          (NameOID.ORGANIZATIONAL_UNIT_NAME, 'bar'),
                                          (NameOID.COMMON_NAME, 'example.com')])

        # Also test order
        s = Subject('/CN=example.com/C=AT/OU=foo/OU=bar')
        self.assertEqual(list(s.fields), [(NameOID.COUNTRY_NAME, 'AT'),
                                          (NameOID.ORGANIZATIONAL_UNIT_NAME, 'foo'),
                                          (NameOID.ORGANIZATIONAL_UNIT_NAME, 'bar'),
                                          (NameOID.COMMON_NAME, 'example.com')]) 
Example #30
Source File: requestor.py    From pypi-infra with Apache License 2.0 5 votes vote down vote up
def generate_csr(common_name, dnsnames, ips, keysize):
    key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=keysize,
        backend=default_backend()
    )

    key_pem = key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=serialization.NoEncryption(),
    )

    csr = x509.CertificateSigningRequestBuilder()
    csr = csr.subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, common_name)]))
    csr = csr.add_extension(
        x509.SubjectAlternativeName(dnsnames + ips),
        critical=False,
    )
    csr = csr.sign(key, hashes.SHA256(), default_backend())

    csr_pem = csr.public_bytes(serialization.Encoding.PEM)

    return key_pem, csr_pem