Python cryptography.x509.oid.NameOID.ORGANIZATION_NAME Examples

The following are 22 code examples of cryptography.x509.oid.NameOID.ORGANIZATION_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: 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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
Source File: __init__.py    From lokey with GNU General Public License v3.0 5 votes vote down vote up
def serialize(self,
                  # password=None,
                  country=u"US",
                  state=u"CA",
                  city=u"San Francisco",
                  company=u"Lokey Examle",
                  common_name=u"example.com"):
        # This should be handled already
        # if not password:
        #     password = None
        key = serialization.load_pem_private_key(
            self.to('pem'),
            password=None,
            backend=default_backend())

        subject = x509.Name([
            x509.NameAttribute(NameOID.COUNTRY_NAME, country),
            x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, state),
            x509.NameAttribute(NameOID.LOCALITY_NAME, city),
            x509.NameAttribute(NameOID.ORGANIZATION_NAME, company),
            x509.NameAttribute(NameOID.COMMON_NAME, common_name),
        ])
        cert = x509.CertificateSigningRequestBuilder().subject_name(
            subject
        ).sign(key, hashes.SHA256(), default_backend())
        return cert.public_bytes(serialization.Encoding.PEM) 
Example #16
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 
Example #17
Source File: utils.py    From zentral with Apache License 2.0 5 votes vote down vote up
def build_name_attributes_update_dict_from_name(name):
    update_dict = {}
    for oid, ztl_attr, is_list in ((NameOID.COMMON_NAME, "common_name", False),
                                   (NameOID.ORGANIZATION_NAME, "organization", False),
                                   (NameOID.ORGANIZATIONAL_UNIT_NAME, "organizational_unit", False),
                                   (NameOID.DOMAIN_COMPONENT, "domain", True)):
        name_attributes = name.get_attributes_for_oid(oid)
        if name_attributes:
            if is_list:
                value = ".".join(na.value for na in name_attributes[::-1])
            else:
                value = name_attributes[-1].value
            update_dict[ztl_attr] = value
    return update_dict 
Example #18
Source File: ca_certs.py    From rally-openstack with Apache License 2.0 5 votes vote down vote up
def _generate_csr_and_key(self):
        """Return a dict with a new csr and key."""
        from cryptography.hazmat import backends
        from cryptography.hazmat.primitives.asymmetric import rsa
        from cryptography.hazmat.primitives import hashes
        from cryptography.hazmat.primitives import serialization
        from cryptography import x509
        from cryptography.x509.oid import NameOID

        key = rsa.generate_private_key(
            public_exponent=65537,
            key_size=2048,
            backend=backends.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(), backends.default_backend())

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

        return result 
Example #19
Source File: detect.py    From roca with MIT License 5 votes vote down vote up
def try_get_dn_string(subject, shorten=False):
    """
    Returns DN as a string
    :param subject:
    :param shorten:
    :return:
    """
    try:
        from cryptography.x509.oid import NameOID
        from cryptography.x509 import ObjectIdentifier
        oid_names = {
            getattr(NameOID, 'COMMON_NAME', ObjectIdentifier("2.5.4.3")): "CN",
            getattr(NameOID, 'COUNTRY_NAME', ObjectIdentifier("2.5.4.6")): "C",
            getattr(NameOID, 'LOCALITY_NAME', ObjectIdentifier("2.5.4.7")): "L",
            getattr(NameOID, 'STATE_OR_PROVINCE_NAME', ObjectIdentifier("2.5.4.8")): "ST",
            getattr(NameOID, 'STREET_ADDRESS', ObjectIdentifier("2.5.4.9")): "St",
            getattr(NameOID, 'ORGANIZATION_NAME', ObjectIdentifier("2.5.4.10")): "O",
            getattr(NameOID, 'ORGANIZATIONAL_UNIT_NAME', ObjectIdentifier("2.5.4.11")): "OU",
            getattr(NameOID, 'SERIAL_NUMBER', ObjectIdentifier("2.5.4.5")): "SN",
            getattr(NameOID, 'USER_ID', ObjectIdentifier("0.9.2342.19200300.100.1.1")): "userID",
            getattr(NameOID, 'DOMAIN_COMPONENT', ObjectIdentifier("0.9.2342.19200300.100.1.25")): "domainComponent",
            getattr(NameOID, 'EMAIL_ADDRESS', ObjectIdentifier("1.2.840.113549.1.9.1")): "emailAddress",
            getattr(NameOID, 'POSTAL_CODE', ObjectIdentifier("2.5.4.17")): "ZIP",
        }

        ret = []
        try:
            for attribute in subject:
                oid = attribute.oid
                dot = oid.dotted_string
                oid_name = oid_names[oid] if shorten and oid in oid_names else oid._name
                val = attribute.value
                ret.append('%s: %s' % (oid_name, val))
        except:
            pass
        return ', '.join(ret)

    except Exception as e:
        logger.warning('Unexpected error: %s' % e)
        return 'N/A' 
Example #20
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 #21
Source File: cert_manager.py    From SROS-grpc-services with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def subject_name(self):
        attribute_list = []
        if self.common_name:
            attribute_list.append(
                x509.NameAttribute(
                    NameOID.COMMON_NAME, text_type(self.common_name)
                )
            )
        if self.organization:
            attribute_list.append(
                x509.NameAttribute(
                    NameOID.ORGANIZATION_NAME, text_type(self.organization)
                )
            )
        if self.organizational_unit:
            attribute_list.append(
                x509.NameAttribute(
                    NameOID.ORGANIZATIONAL_UNIT_NAME,
                    text_type(self.organizational_unit),
                )
            )
        if self.country:
            attribute_list.append(
                x509.NameAttribute(
                    NameOID.COUNTRY_NAME, text_type(self.country)
                )
            )
        if self.state:
            attribute_list.append(
                x509.NameAttribute(
                    NameOID.STATE_OR_PROVINCE_NAME, text_type(self.state)
                )
            )
        if self.city:
            attribute_list.append(
                x509.NameAttribute(NameOID.LOCALITY_NAME, text_type(self.city))
            )
        if self.email_id:
            attribute_list.append(
                x509.NameAttribute(
                    NameOID.EMAIL_ADDRESS, text_type(self.email_id)
                )
            )
        return x509.Name(attribute_list) 
Example #22
Source File: detect.py    From roca with MIT License 4 votes vote down vote up
def process_x509(self, x509, name, idx=None, data=None, pem=True, source='', aux=None):
        """
        Processing parsed X509 certificate
        :param x509:
        :param name:
        :param idx:
        :param data:
        :param pem:
        :param source:
        :param aux:
        :return:
        """
        if x509 is None:
            return

        from cryptography.hazmat.primitives import hashes
        from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey
        from cryptography.x509.oid import NameOID

        pub = x509.public_key()
        if not isinstance(pub, RSAPublicKey):
            return

        self.num_rsa += 1
        pubnum = x509.public_key().public_numbers()

        js = collections.OrderedDict()
        js['type'] = source
        js['fname'] = name
        js['idx'] = idx
        js['fprint'] = binascii.hexlify(x509.fingerprint(hashes.SHA256()))
        js['subject'] = utf8ize(try_get_dn_string(x509.subject, shorten=True))
        js['issuer'] = utf8ize(try_get_dn_string(x509.issuer, shorten=True))
        js['issuer_org'] = utf8ize(try_get_dn_part(x509.issuer, NameOID.ORGANIZATION_NAME))
        js['created_at'] = self.strtime(x509.not_valid_before)
        js['created_at_utc'] = unix_time(x509.not_valid_before)
        js['not_valid_after_utc'] = unix_time(x509.not_valid_after)
        js['pem'] = data if pem else None
        js['aux'] = aux
        js['e'] = '0x%x' % pubnum.e
        js['n'] = '0x%x' % pubnum.n

        if self.has_fingerprint(pubnum.n):
            logger.warning('Fingerprint found in the Certificate %s idx %s ' % (name, idx))
            self.mark_and_add_effort(pubnum.n, js)

            if self.do_print:
                print(json.dumps(js))

        return TestResult(js)