Python cryptography.hazmat.primitives.serialization.Encoding.PEM Examples

The following are 30 code examples of cryptography.hazmat.primitives.serialization.Encoding.PEM(). 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.hazmat.primitives.serialization.Encoding , or try the search function .
Example #1
Source File: user_test.py    From fabric-sdk-py with Apache License 2.0 6 votes vote down vote up
def test_user_state(self):
        store = file_key_value_store(self.path)
        user = User('test_user', 'peerOrg1', store)
        user.roles = ['test']

        ec = ecies()

        enrollment = Enrollment(ec.generate_private_key(), "dasdasdasdasdasd")
        user.enrollment = enrollment

        user1 = User('test_user', 'peerOrg1', store)
        self.assertTrue(user1.roles == ['test'])
        self.assertTrue(user1.enrollment.cert == "dasdasdasdasdasd")
        pub_key = user1.enrollment.private_key.public_key()
        self.assertTrue(pub_key.public_bytes(
            encoding=Encoding.PEM,
            format=serialization.PublicFormat.SubjectPublicKeyInfo)
            .startswith(b'-----BEGIN PUBLIC KEY')) 
Example #2
Source File: caservice.py    From fabric-sdk-py with Apache License 2.0 6 votes vote down vote up
def get_cainfo(self):
        """Query the ca service information.

        :return: The base64 encoded CA PEM file content for the caname
        """
        if self._ca_name != "":
            body_data = {"caname": self._ca_name}
        else:
            body_data = {}
        res, st = self._send_ca_post(path="cainfo", json=body_data,
                                     verify=self._ca_certs_path)
        _logger.debug("Response status {0}".format(st))
        _logger.debug("Raw response json {0}".format(res))

        if res['success'] and res['result']['CAName'] == self._ca_name:
            return base64.b64decode(res['result']['CAChain'])
        else:
            raise ValueError("get_cainfo failed with errors {0}"
                             .format(res['errors'])) 
Example #3
Source File: import_ca.py    From django-ca with GNU General Public License v3.0 6 votes vote down vote up
def add_arguments(self, parser):
        self.add_ca(parser, '--parent',
                    help='''Make the CA an intermediate CA of the named CA. By default, this is a
                    new root CA.''', no_default=True)
        self.add_password(
            parser, help='Password used to encrypt the private key. Pass no argument to be prompted.')
        parser.add_argument('--import-password', nargs='?', action=PasswordAction, metavar='PASSWORD',
                            prompt='Password to import CA: ',
                            help='Password for the private key.')

        self.add_ca_args(parser)

        parser.add_argument('name', help='Human-readable name of the CA')
        parser.add_argument('key', help='Path to the private key (PEM or DER format).',
                            type=argparse.FileType('rb'))
        parser.add_argument('pem', help='Path to the public key (PEM or DER format).',
                            type=argparse.FileType('rb')) 
Example #4
Source File: idontspeakssl_scanner.py    From IDontSpeakSSL with GNU General Public License v3.0 6 votes vote down vote up
def run_certificate_command(self, server_info, synchronous_scanner):
		certificate_chain = {}
		command = CertificateInfoScanCommand()
		scan_result = synchronous_scanner.run_scan_command(server_info, command)
		i=0
		for certificate in scan_result.received_certificate_chain:
			certificate_chain[i] = {"pem":certificate.public_bytes(Encoding.PEM).decode("ascii")}
			if(i > 0):
				certificate_chain[i]['is_CA'] = True
			else:
				certificate_chain[i]['is_CA'] = False
			i += 1
		trusted_chain = False
		if(scan_result.verified_certificate_chain):
			trusted_chain = True
		result_by_trusted_store = {}
		for store_result in scan_result.path_validation_result_list:
			store_name  = store_result.trust_store.name  + store_result.trust_store.version
			result_by_trusted_store[store_name] = store_result.was_validation_successful
		return {"certificate_chain":certificate_chain,
			"is_chain_trusted": trusted_chain,
			"oscp_response":scan_result.ocsp_response_is_trusted,
			"result_by_trusted_store": result_by_trusted_store} 
Example #5
Source File: test_sslverify.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def pathContainingDumpOf(testCase, *dumpables):
    """
    Create a temporary file to store some serializable-as-PEM objects in, and
    return its name.

    @param testCase: a test case to use for generating a temporary directory.
    @type testCase: L{twisted.trial.unittest.TestCase}

    @param dumpables: arguments are objects from pyOpenSSL with a C{dump}
        method, taking a pyOpenSSL file-type constant, such as
        L{OpenSSL.crypto.FILETYPE_PEM} or L{OpenSSL.crypto.FILETYPE_ASN1}.
    @type dumpables: L{tuple} of L{object} with C{dump} method taking L{int}
        returning L{bytes}

    @return: the path to a file where all of the dumpables were dumped in PEM
        format.
    @rtype: L{str}
    """
    fname = testCase.mktemp()
    with open(fname, "wb") as f:
        for dumpable in dumpables:
            f.write(dumpable.dump(FILETYPE_PEM))
    return fname 
Example #6
Source File: views.py    From django-ca with GNU General Public License v3.0 6 votes vote down vote up
def get(self, request, serial):
        encoding = parse_encoding(request.GET.get('encoding', self.type))
        cache_key = get_crl_cache_key(serial, algorithm=self.digest, encoding=encoding, scope=self.scope)

        crl = cache.get(cache_key)
        if crl is None:
            ca = self.get_object()
            encoding = parse_encoding(self.type)
            crl = ca.get_crl(expires=self.expires, algorithm=self.digest, password=self.password,
                             scope=self.scope)
            crl = crl.public_bytes(encoding)
            cache.set(cache_key, crl, self.expires)

        content_type = self.content_type
        if content_type is None:
            if self.type == Encoding.DER:
                content_type = 'application/pkix-crl'
            elif self.type == Encoding.PEM:
                content_type = 'text/plain'
            else:  # pragma: no cover
                # DER/PEM are all known encoding types, so this shouldn't happen
                return HttpResponseServerError()

        return HttpResponse(crl, content_type=content_type) 
Example #7
Source File: test_sslverify.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def pathContainingDumpOf(testCase, *dumpables):
    """
    Create a temporary file to store some serializable-as-PEM objects in, and
    return its name.

    @param testCase: a test case to use for generating a temporary directory.
    @type testCase: L{twisted.trial.unittest.TestCase}

    @param dumpables: arguments are objects from pyOpenSSL with a C{dump}
        method, taking a pyOpenSSL file-type constant, such as
        L{OpenSSL.crypto.FILETYPE_PEM} or L{OpenSSL.crypto.FILETYPE_ASN1}.
    @type dumpables: L{tuple} of L{object} with C{dump} method taking L{int}
        returning L{bytes}

    @return: the path to a file where all of the dumpables were dumped in PEM
        format.
    @rtype: L{str}
    """
    fname = testCase.mktemp()
    with open(fname, "wb") as f:
        for dumpable in dumpables:
            f.write(dumpable.dump(FILETYPE_PEM))
    return fname 
Example #8
Source File: defaults.py    From lemur with Apache License 2.0 6 votes vote down vote up
def common_name(cert):
    """
    Attempts to get a sane common name from a given certificate.

    :param cert:
    :return: Common name or None
    """
    try:
        subject_oid = cert.subject.get_attributes_for_oid(x509.OID_COMMON_NAME)
        if len(subject_oid) > 0:
            return subject_oid[0].value.strip()
        return None
    except Exception as e:
        sentry.captureException()
        current_app.logger.error(
            {
                "message": "Unable to get common name",
                "error": e,
                "public_key": cert.public_bytes(Encoding.PEM).decode("utf-8")
            },
            exc_info=True
        ) 
Example #9
Source File: tests_admin.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def test_wrong_csr(self):
        ca = self.cas['root']
        cn = 'test-add-wrong-csr.example.com'

        with self.assertSignal(pre_issue_cert) as pre, self.assertSignal(post_issue_cert) as post:
            response = self.client.post(self.add_url, data={
                'csr': 'whatever',
                'ca': ca.pk,
                'profile': 'webserver',
                'subject_0': 'US',
                'subject_5': cn,
                'subject_alternative_name_1': True,
                'algorithm': 'SHA256',
                'expires': ca.expires.strftime('%Y-%m-%d'),
                'key_usage_0': ['digitalSignature', 'keyAgreement', ],
                'key_usage_1': True,
                'extended_key_usage_0': ['clientAuth', 'serverAuth', ],
                'extended_key_usage_1': False,
            })
        self.assertFalse(pre.called)
        self.assertFalse(post.called)
        self.assertEqual(response.status_code, 200)
        self.assertIn("Enter a valid CSR (in PEM format).", response.content.decode('utf-8'))
        self.assertFalse(response.context['adminform'].form.is_valid())
        self.assertEqual(response.context['adminform'].form.errors,
                         {'csr': ['Enter a valid CSR (in PEM format).']})

        with self.assertRaises(Certificate.DoesNotExist):
            Certificate.objects.get(cn=cn) 
Example #10
Source File: tests_admin.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def test_anonymous(self):
        # Try an anonymous download
        client = Client()
        response = client.get('%s?format=PEM' % self.url)
        self.assertRequiresLogin(response) 
Example #11
Source File: tests_admin.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def test_basic(self):
        filename = 'root-cert_example_com.pem'
        response = self.client.get('%s?format=PEM' % self.url)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response['Content-Type'], 'application/pkix-cert')
        self.assertEqual(response['Content-Disposition'], 'attachment; filename=%s' % filename)
        self.assertEqual(force_text(response.content), self.cert.pub) 
Example #12
Source File: tests_admin.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def test_fields(self):
        subject = [(f, 'AT' if f == 'C' else 'test-%s' % f) for f in SUBJECT_FIELDS]
        key, csr = self.create_csr(subject)
        csr_pem = csr.public_bytes(Encoding.PEM).decode('utf-8')

        response = self.client.post(self.url, data={'csr': csr_pem})
        self.assertEqual(response.status_code, 200)
        self.assertEqual(json.loads(response.content.decode('utf-8')), {'subject': {
            'C': 'AT', 'CN': 'test-CN', 'L': 'test-L', 'O': 'test-O', 'OU': 'test-OU', 'ST':
            'test-ST', 'emailAddress': 'test-emailAddress'}}) 
Example #13
Source File: tests_models.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def test_no_idp(self):
        # CRLs require a full name (or only_some_reasons) if it's a full CRL
        ca = self.cas['child']
        ca.crl_url = ''
        ca.save()
        crl = ca.get_crl().public_bytes(Encoding.PEM)
        self.assertCRL(crl, idp=None) 
Example #14
Source File: tests_models.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def test_crl_invalid_scope(self):
        ca = self.cas['child']
        with self.assertRaisesRegex(ValueError, r'^Scope must be either None, "ca", "user" or "attribute"$'):
            ca.get_crl(scope='foobar').public_bytes(Encoding.PEM) 
Example #15
Source File: tests_models.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def test_no_auth_key_identifier(self):
        # All CAs have a authority key identifier, so we mock that this exception is not present
        def side_effect(cls):
            raise x509.ExtensionNotFound('mocked', x509.AuthorityKeyIdentifier.oid)

        ca = self.cas['child']
        full_name = 'http://localhost/crl'
        idp = self.get_idp(full_name=[x509.UniformResourceIdentifier(value=full_name)])

        with mock.patch('cryptography.x509.extensions.Extensions.get_extension_for_oid',
                        side_effect=side_effect):
            crl = ca.get_crl(full_name=[full_name]).public_bytes(Encoding.PEM)
        self.assertCRL(crl, idp=idp, signer=ca, skip_authority_key_identifier=True) 
Example #16
Source File: tests_models.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def test_counter(self):
        ca = self.cas['child']
        idp = self.get_idp(full_name=self.get_idp_full_name(ca))
        crl = ca.get_crl(counter='test').public_bytes(Encoding.PEM)
        self.assertCRL(crl, idp=idp, crl_number=0)
        crl = ca.get_crl(counter='test').public_bytes(Encoding.PEM)
        self.assertCRL(crl, idp=idp, crl_number=1)

        crl = ca.get_crl().public_bytes(Encoding.PEM)  # test with no counter
        self.assertCRL(crl, idp=idp, crl_number=0) 
Example #17
Source File: x509.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def create_ssl_context(cert_byes, pk_bytes, password=None,
                       encoding=Encoding.PEM):
    """Create an SSL Context with the supplied cert/password.

    :param cert_bytes array of bytes containing the cert encoded
           using the method supplied in the ``encoding`` parameter
    :param pk_bytes array of bytes containing the private key encoded
           using the method supplied in the ``encoding`` parameter
    :param password array of bytes containing the passphrase to be used
           with the supplied private key. None if unencrypted.
           Defaults to None.
    :param encoding ``cryptography.hazmat.primitives.serialization.Encoding``
            details the encoding method used on the ``cert_bytes``  and
            ``pk_bytes`` parameters. Can be either PEM or DER.
            Defaults to PEM.
    """
    backend = default_backend()

    cert = None
    key = None
    if encoding == Encoding.PEM:
        cert = x509.load_pem_x509_certificate(cert_byes, backend)
        key = load_pem_private_key(pk_bytes, password, backend)
    elif encoding == Encoding.DER:
        cert = x509.load_der_x509_certificate(cert_byes, backend)
        key = load_der_private_key(pk_bytes, password, backend)
    else:
        raise ValueError('Invalid encoding provided: Must be PEM or DER')

    if not (cert and key):
        raise ValueError('Cert and key could not be parsed from '
                         'provided data')
    check_cert_dates(cert)
    ssl_context = PyOpenSSLContext(PROTOCOL)
    ssl_context._ctx.use_certificate(X509.from_cryptography(cert))
    ssl_context._ctx.use_privatekey(PKey.from_cryptography_key(key))
    return ssl_context 
Example #18
Source File: tests_admin.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def test_plain_user(self):
        # User isn't staff and has no permissions
        client = Client()
        User.objects.create_user(username='plain', password='password', email='user@example.com')
        self.assertTrue(client.login(username='plain', password='password'))
        response = client.get('%s?format=PEM' % self.url)
        self.assertRequiresLogin(response) 
Example #19
Source File: tests_admin.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def test_no_staff(self):
        # User isn't staff but has permissions
        client = Client()
        response = client.get('%s?format=PEM' % self.url)

        # create a user
        user = User.objects.create_user(username='no_perms', password='password', email='user@example.com')
        p = Permission.objects.get(codename='change_certificate')
        user.user_permissions.add(p)
        self.assertTrue(client.login(username='no_perms', password='password'))

        self.assertRequiresLogin(response) 
Example #20
Source File: tests_admin.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def test_cert(self):
        filename = 'root-cert_example_com_bundle.pem'
        response = self.client.get('%s?format=PEM' % self.url)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response['Content-Type'], 'application/pkix-cert')
        self.assertEqual(response['Content-Disposition'], 'attachment; filename=%s' % filename)
        self.assertEqual(force_text(response.content),
                         '%s\n%s' % (self.cert.pub.strip(), self.cert.ca.pub.strip()))
        self.assertEqual(self.cas['root'], self.cert.ca)  # just to be sure we test the right thing 
Example #21
Source File: base.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def assertCRL(self, crl, certs=None, signer=None, expires=86400, algorithm=None, encoding=Encoding.PEM,
                  idp=None, extensions=None, crl_number=0, skip_authority_key_identifier=False):
        certs = certs or []
        signer = signer or self.cas['child']
        algorithm = algorithm or ca_settings.CA_DIGEST_ALGORITHM
        extensions = extensions or []
        expires = datetime.utcnow() + timedelta(seconds=expires)

        if idp is not None:  # pragma: no branch
            extensions.append(idp)
        extensions.append(x509.Extension(
            value=x509.CRLNumber(crl_number=crl_number),
            critical=False, oid=ExtensionOID.CRL_NUMBER
        ))
        if not skip_authority_key_identifier:
            extensions.append(signer.authority_key_identifier.as_extension())

        if encoding == Encoding.PEM:
            crl = x509.load_pem_x509_crl(crl, default_backend())
        else:
            crl = x509.load_der_x509_crl(crl, default_backend())

        self.assertIsInstance(crl.signature_hash_algorithm, type(algorithm))
        self.assertTrue(crl.is_signature_valid(signer.x509.public_key()))
        self.assertEqual(crl.issuer, signer.x509.subject)
        self.assertEqual(crl.last_update, datetime.utcnow())
        self.assertEqual(crl.next_update, expires)
        self.assertCountEqual(list(crl.extensions), extensions)

        entries = {e.serial_number: e for e in crl}
        expected = {c.x509.serial_number: c for c in certs}
        self.assertCountEqual(entries, expected)
        for serial, entry in entries.items():
            self.assertEqual(entry.revocation_date, datetime.utcnow())
            self.assertEqual(list(entry.extensions), []) 
Example #22
Source File: tests_management_base.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def test_basic(self):
        ns = self.parser.parse_args(['--action=DER'])
        self.assertEqual(ns.action, Encoding.DER)

        ns = self.parser.parse_args(['--action=ASN1'])
        self.assertEqual(ns.action, Encoding.DER)

        ns = self.parser.parse_args(['--action=PEM'])
        self.assertEqual(ns.action, Encoding.PEM) 
Example #23
Source File: admin.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def _download_response(self, request, pk, bundle=False):
        if not request.user.is_staff or not self.has_change_permission(request):
            # NOTE: is_staff is already assured by ModelAdmin, but just to be sure
            raise PermissionDenied

        # get object in question
        try:
            obj = self.model.objects.get(pk=pk)
        except self.model.DoesNotExist:
            raise Http404

        # get filetype
        filetype = request.GET.get('format', 'PEM').upper().strip()

        if filetype == 'PEM':
            if bundle is True:
                data = '\n'.join([cert.pub.strip() for cert in obj.bundle])
            else:
                data = obj.pub
        elif filetype == 'DER':
            if bundle is True:
                return HttpResponseBadRequest(_('DER/ASN.1 certificates cannot be downloaded as a bundle.'))
            data = obj.x509.public_bytes(encoding=Encoding.DER)
        else:
            return HttpResponseBadRequest()

        filename = obj.get_filename(ext=filetype, bundle=bundle)
        response = HttpResponse(data, content_type='application/pkix-cert')
        response['Content-Disposition'] = 'attachment; filename=%s' % filename
        return response 
Example #24
Source File: admin.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def download_bundle_view(self, request, pk):
        """A view that allows the user to download a certificate bundle in PEM format."""

        return self._download_response(request, pk, bundle=True) 
Example #25
Source File: admin.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def save_model(self, request, obj, form, change):
        data = form.cleaned_data

        # If this is a new certificate, initialize it.
        if change is False:
            profile = profiles[data['profile']]

            if hasattr(request, '_resign_obj'):
                csr = getattr(request, '_resign_obj').csr
                obj.csr = csr
            else:
                # Note: CSR is set by model form already
                csr = data['csr']

            parsed_csr = Certificate.objects.parse_csr(csr, Encoding.PEM)
            expires = datetime.combine(data['expires'], datetime.min.time())

            extensions = {}
            san, cn_in_san = data['subject_alternative_name']
            san = SubjectAlternativeName({'value': [e.strip() for e in san.split(',') if e.strip()]})
            if san:
                extensions[SubjectAlternativeName.key] = san
            for ext_key in [KeyUsage.key, ExtendedKeyUsage.key, TLSFeature.key]:
                if data[ext_key].value:
                    extensions[ext_key] = data[ext_key]
                else:
                    extensions[ext_key] = None

            obj.profile = profile.name
            obj.x509 = profile.create_cert(data['ca'], parsed_csr, subject=data['subject'], expires=expires,
                                           algorithm=data['algorithm'], cn_in_san=cn_in_san,
                                           password=data['password'], extensions=extensions)
            obj.save()
            post_issue_cert.send(sender=self.model, cert=obj)
        else:
            obj.save() 
Example #26
Source File: plugin_x509.py    From deen with Apache License 2.0 5 votes vote down vote up
def _clone(self, original_cert, self_sign, signature_algo):
        """Create a 1:1 clone of original_cert. If self_sign is False,
        the new_certificate will not yet be signed."""
        cert = OpenSSL.crypto.X509()
        cert.set_version(original_cert.get_version())
        cert.set_serial_number(original_cert.get_serial_number())
        cert.set_notBefore(original_cert.get_notBefore())
        cert.set_notAfter(original_cert.get_notAfter())
        pkey = OpenSSL.crypto.PKey()
        if original_cert.get_pubkey().type() == OpenSSL.crypto.TYPE_RSA:
            pkey.generate_key(OpenSSL.crypto.TYPE_RSA,
                              original_cert.get_pubkey().bits())
        elif original_cert.get_pubkey().type() == OpenSSL.crypto.TYPE_EC:
            ec_key = original_cert.get_pubkey().to_cryptography_key()
            curve = ec_key.curve
            key = ec.generate_private_key(curve, default_backend())
            key_pem = key.private_bytes(encoding=Encoding.PEM, format=PrivateFormat.TraditionalOpenSSL, encryption_algorithm=NoEncryption())
            pkey = OpenSSL.crypto.load_privatekey(OpenSSL.crypto.FILETYPE_PEM, key_pem)
        else:
            self.error = Exception('Unsupported certificate type ' + str(original_cert.get_pubkey().type()))
            self.log.error(self.error)
            self.log.debug(self.error, exc_info=True)
            return
        cert.set_pubkey(pkey)
        cert.set_issuer(original_cert.get_issuer())
        cert.set_subject(original_cert.get_subject())
        extensions = []
        for extid in range(original_cert.get_extension_count()):
            extensions.append(original_cert.get_extension(extid))
        cert.add_extensions(extensions)
        if self_sign:
            if not signature_algo:
                signature_algo = original_cert.get_signature_algorithm().decode()
            # evp_get_digestbyname_ex() might fail for signature
            # definition in ECDSA certs. Just take the actual
            # signature algorithm from the string. E. g. extract
            # "SHA256" from "ecdsa-with-SHA256".
            if '-' in signature_algo:
                signature_algo = signature_algo.split('-')[-1]
            cert.sign(pkey, signature_algo)
        return cert, pkey 
Example #27
Source File: x509.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        self._check_version()
        cert_bytes = kwargs.pop('cert_bytes', None)
        pk_bytes = kwargs.pop('pk_bytes', None)
        password = kwargs.pop('password', None)
        encoding = kwargs.pop('encoding', Encoding.PEM)

        password_bytes = None

        if cert_bytes is None or not isinstance(cert_bytes, bytes):
            raise ValueError('Invalid cert content provided. '
                             'You must provide an X.509 cert '
                             'formatted as a byte array.')
        if pk_bytes is None or not isinstance(pk_bytes, bytes):
            raise ValueError('Invalid private key content provided. '
                             'You must provide a private key '
                             'formatted as a byte array.')

        if isinstance(password, bytes):
            password_bytes = password
        elif password:
            password_bytes = password.encode('utf8')

        self.ssl_context = create_ssl_context(cert_bytes, pk_bytes,
                                              password_bytes, encoding)

        super(X509Adapter, self).__init__(*args, **kwargs) 
Example #28
Source File: _json_output.py    From sslyze with GNU Affero General Public License v3.0 5 votes vote down vote up
def _monkeypatch_to_fix_certificate_asdict() -> None:
    # H4ck: monkeypatch the _Certificate class to add __deepcopy__() so that when we call asdict() on a dataclass
    # that contains a _Certificate, asdict() succeeds. Without this, generating JSON for the certinfo scan command
    # will crash because the asdict() function uses deepcopy(), but certificates returned by cryptography.x509
    # don't support it so SSLyze would crash. This class is a workaround to fix JSON output.
    # I opened an issue about it in the cryptography repo at https://github.com/pyca/cryptography/issues/5129
    def _deepcopy_method_for_x509_certificate(inner_self: _Certificate, memo: str) -> x509.Certificate:
        return x509.load_pem_x509_certificate(inner_self.public_bytes(Encoding.PEM), backend=default_backend())

    _Certificate.__deepcopy__ = _deepcopy_method_for_x509_certificate


# Call it on import... hacky but we don't have a choice 
Example #29
Source File: managers.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def parse_csr(self, csr, csr_format):
        if isinstance(csr, x509.CertificateSigningRequest):
            return csr
        elif csr_format == Encoding.PEM:
            return x509.load_pem_x509_csr(force_bytes(csr), default_backend())
        elif csr_format == Encoding.DER:
            return x509.load_der_x509_csr(force_bytes(csr), default_backend())

        raise ValueError('Unknown CSR format passed: %s' % csr_format) 
Example #30
Source File: certificate.py    From pylxd with Apache License 2.0 5 votes vote down vote up
def create(cls, client, password, cert_data):
        """Create a new certificate."""
        cert = x509.load_pem_x509_certificate(cert_data, default_backend())
        base64_cert = cert.public_bytes(Encoding.PEM).decode('utf-8')
        # STRIP OUT CERT META "-----BEGIN CERTIFICATE-----"
        base64_cert = '\n'.join(base64_cert.split('\n')[1:-2])
        data = {
            'type': 'client',
            'certificate': base64_cert,
            'password': password,
        }
        client.api.certificates.post(json=data)

        # XXX: rockstar (08 Jun 2016) - Please see the open lxd bug here:
        # https://github.com/lxc/lxd/issues/2092
        fingerprint = binascii.hexlify(
            cert.fingerprint(hashes.SHA256())).decode('utf-8')
        return cls.get(client, fingerprint)