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

The following are 30 code examples of cryptography.hazmat.primitives.serialization.Encoding.DER(). 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: tokentools.py    From snowflake-ingest-python with Apache License 2.0 6 votes vote down vote up
def calculate_public_key_fingerprint(self, private_key: Text) -> Text:
        """
        Given a private key in pem format, return the public key fingerprint
        :param private_key: private key string
        :return: public key fingerprint
        """
        try:
            private_key = load_pem_private_key(private_key.encode(), None, default_backend())
        except (ValueError,  UnsupportedAlgorithm) as e:
            raise IngestClientError(
                    code=ERR_INVALID_PRIVATE_KEY,
                    message='Invalid private key. {}'.format(e))

        # get the raw bytes of public key
        public_key_raw = private_key.public_key().public_bytes(Encoding.DER, PublicFormat.SubjectPublicKeyInfo)

        # take sha256 on raw bytes and then do base64 encode
        sha256hash = hashlib.sha256()
        sha256hash.update(public_key_raw)

        public_key_fp = 'SHA256:' + base64.b64encode(sha256hash.digest()).decode('utf-8')
        logger.info("Public key fingerprint is %s", public_key_fp)

        return public_key_fp 
Example #2
Source File: tests_views.py    From django-ca with GNU General Public License v3.0 6 votes vote down vote up
def test_basic(self):
        # test the default view
        idp = self.get_idp(full_name=self.get_idp_full_name(self.ca), only_contains_user_certs=True)
        response = self.client.get(reverse('default', kwargs={'serial': self.ca.serial}))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response['Content-Type'], 'application/pkix-crl')
        self.assertCRL(response.content, encoding=Encoding.DER, expires=600, idp=idp)

        # revoke a certificate
        cert = self.certs['child-cert']
        cert.revoke()

        # fetch again - we should see a cached response
        response = self.client.get(reverse('default', kwargs={'serial': self.ca.serial}))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response['Content-Type'], 'application/pkix-crl')
        self.assertCRL(response.content, encoding=Encoding.DER, expires=600, idp=idp)

        # clear the cache and fetch again
        cache.clear()
        response = self.client.get(reverse('default', kwargs={'serial': self.ca.serial}))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response['Content-Type'], 'application/pkix-crl')
        self.assertCRL(response.content, encoding=Encoding.DER, expires=600, idp=idp, certs=[cert],
                       crl_number=1) 
Example #3
Source File: app.py    From commandment with MIT License 6 votes vote down vote up
def anchor_certs():
    """Download a list of certificates to trust the MDM

    The response is a JSON array of base64 encoded DER certs as described in the DEP profile creation documentation."""
    anchors = []

    if 'CA_CERTIFICATE' in current_app.config:
        with open(current_app.config['CA_CERTIFICATE'], 'rb') as fd:
            pem_data = fd.read()
            c: x509.Certificate = x509.load_pem_x509_certificate(pem_data, backend=default_backend())
            der = c.public_bytes(Encoding.DER)
            anchors.append(urlsafe_b64encode(der))

    if 'SSL_CERTIFICATE' in current_app.config:
        with open(current_app.config['SSL_CERTIFICATE'], 'rb') as fd:
            pem_data = fd.read()
            c: x509.Certificate = x509.load_pem_x509_certificate(pem_data, backend=default_backend())
            der = c.public_bytes(Encoding.DER)
            anchors.append(urlsafe_b64encode(der))

    return jsonify(anchors) 
Example #4
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 #5
Source File: tests_command_view_cert.py    From django-ca with GNU General Public License v3.0 6 votes vote down vote up
def test_der(self):
        cert = self.certs['child-cert']
        stdout, stderr = self.cmd('view_cert', cert.serial, format=Encoding.DER,
                                  stdout=BytesIO(), stderr=BytesIO())
        expected = '''Common Name: {cn}
Valid from: {valid_from_short}
Valid until: {valid_until_short}
Status: Valid
SubjectAlternativeName{subject_alternative_name_critical}:
    * {subject_alternative_name[0]}
Watchers:
Digest:
    md5: {md5}
    sha1: {sha1}
    sha256: {sha256}
    sha512: {sha512}
HPKP pin: {hpkp}

'''.format(**self.get_cert_context('child-cert'))
        expected = force_bytes(expected) + certs['child-cert']['pub']['der'] + b'\n'

        self.assertEqual(stdout, expected)
        self.assertEqual(stderr, b'') 
Example #6
Source File: tests_command_cache_crls.py    From django-ca with GNU General Public License v3.0 6 votes vote down vote up
def test_basic(self):
        hash_cls = hashes.SHA512
        enc_cls = Encoding.DER
        stdout, stderr = self.cmd('cache_crls')
        self.assertEqual(stdout, '')
        self.assertEqual(stderr, '')

        for name, ca in self.cas.items():
            key = get_crl_cache_key(ca.serial, hash_cls, enc_cls, 'ca')
            crl = x509.load_der_x509_crl(cache.get(key), default_backend())
            self.assertIsNotNone(crl)
            self.assertIsInstance(crl.signature_hash_algorithm, hash_cls)

            key = get_crl_cache_key(ca.serial, hash_cls, enc_cls, 'user')
            crl = x509.load_der_x509_crl(cache.get(key), default_backend())
            self.assertIsNotNone(crl) 
Example #7
Source File: dump_ca.py    From django-ca with GNU General Public License v3.0 6 votes vote down vote up
def handle(self, ca, path, **options):
        if options['bundle'] and options['format'] == Encoding.DER:
            raise CommandError('Cannot dump bundle when using DER format.')

        if options['bundle']:
            certs = ca.bundle
        else:
            certs = [ca]

        data = b''.join([c.dump_certificate(options['format']) for c in certs])
        if path == '-':
            self.stdout.write(data, ending=b'')
        else:
            try:
                with open(path, 'wb') as stream:
                    stream.write(data)
            except IOError as e:
                raise CommandError(e) 
Example #8
Source File: dump_cert.py    From django-ca with GNU General Public License v3.0 6 votes vote down vote up
def handle(self, cert, path, **options):
        if options['bundle'] and options['format'] == Encoding.DER:
            raise CommandError('Cannot dump bundle when using DER format.')

        if options['bundle']:
            certs = cert.bundle
        else:
            certs = [cert]

        data = b''.join([c.dump_certificate(options['format']) for c in certs])
        if path == '-':
            self.stdout.write(data, ending=b'')
        else:
            try:
                with open(path, 'wb') as stream:
                    stream.write(data)
            except IOError as e:
                raise CommandError(e) 
Example #9
Source File: base.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def _load_csr(data):
    basedir = data.get('basedir', settings.FIXTURES_DIR)
    path = os.path.join(basedir, data['csr_filename'])

    with open(path, 'rb') as stream:
        raw = stream.read().strip()

    csr_data = {
        'pem': raw.decode('utf-8'),
        'parsed': x509.load_pem_x509_csr(raw, default_backend()),
    }

    csr_data['der'] = csr_data['parsed'].public_bytes(Encoding.DER)

    return csr_data 
Example #10
Source File: tests_tasks.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def test_cache_all_crls(self):
        hash_cls = hashes.SHA512
        enc_cls = Encoding.DER
        tasks.cache_crls()

        for ca, data in self.cas.items():
            key = get_crl_cache_key(data.serial, hash_cls, enc_cls, 'ca')
            crl = x509.load_der_x509_crl(cache.get(key), default_backend())
            self.assertIsInstance(crl.signature_hash_algorithm, hash_cls)

            key = get_crl_cache_key(data.serial, hash_cls, enc_cls, 'user')
            crl = x509.load_der_x509_crl(cache.get(key), default_backend()) 
Example #11
Source File: tests_views.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def test_full_scope(self):
        full_name = 'http://localhost/crl'
        idp = self.get_idp(full_name=[x509.UniformResourceIdentifier(value=full_name)])

        self.ca.crl_url = full_name
        self.ca.save()

        response = self.client.get(reverse('full', kwargs={'serial': self.ca.serial}))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response['Content-Type'], 'application/pkix-crl')
        self.assertCRL(response.content, encoding=Encoding.DER, expires=600, idp=idp) 
Example #12
Source File: tests_views.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def test_view(self):
        client = Client()

        for name, ca in self.cas.items():
            url = reverse('django_ca:issuer', kwargs={'serial': ca.root.serial})
            resp = client.get(url)
            self.assertEqual(resp['Content-Type'], 'application/pkix-cert')
            self.assertEqual(resp.content, ca.root.x509.public_bytes(encoding=Encoding.DER)) 
Example #13
Source File: tests_views_ocsp.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def test_no_nonce(self):
        from cryptography.x509 import ocsp
        cert = self.certs['child-cert']
        builder = ocsp.OCSPRequestBuilder()
        builder = builder.add_certificate(cert.x509, cert.ca.x509, hashes.SHA1())
        data = base64.b64encode(builder.build().public_bytes(serialization.Encoding.DER))

        response = self.client.get(reverse('get', kwargs={'data': data.decode('utf-8')}))
        self.assertOCSP(response, requested=[cert], nonce=None) 
Example #14
Source File: tests_views_ocsp.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def test_no_nonce_asn1crypto(self):
        cert = self.certs['child-cert']
        builder = ocspbuilder.OCSPRequestBuilder(
            certificate=asn1crypto.x509.Certificate.load(cert.x509.public_bytes(Encoding.DER)),
            issuer=asn1crypto.x509.Certificate.load(cert.ca.x509.public_bytes(Encoding.DER))
        )
        builder.nonce = False
        data = base64.b64encode(builder.build().dump()).decode('utf-8')

        response = self.client.get(reverse('get', kwargs={'data': data}))
        self.assertEqual(response.status_code, 200)
        self.assertOCSP(response, requested=[cert], nonce=None) 
Example #15
Source File: tests_command_dump_ca.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def test_format(self):
        for option in ['PEM', 'DER']:
            encoding = getattr(Encoding, option)
            stdout, stderr = self.cmd('dump_ca', self.ca.serial, format=encoding,
                                      stdout=BytesIO(), stderr=BytesIO())
            self.assertEqual(stderr, b'')
            self.assertEqual(stdout, self.ca.dump_certificate(encoding)) 
Example #16
Source File: tests_command_dump_ca.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def test_errors(self):
        path = os.path.join(ca_settings.CA_DIR, 'does-not-exist', 'test_ca.pem')
        msg = r"^\[Errno 2\] No such file or directory: '%s/does-not-exist/test_ca\.pem'$" % (
            ca_settings.CA_DIR)

        with self.assertCommandError(msg):
            self.cmd('dump_ca', self.ca.serial, path, stdout=BytesIO(), stderr=BytesIO())

        with self.assertCommandError(r'^Cannot dump bundle when using DER format\.$'):
            self.cmd('dump_ca', self.ca.serial, format=Encoding.DER, bundle=True,
                     stdout=BytesIO(), stderr=BytesIO()) 
Example #17
Source File: tests_command_dump_cert.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def test_format(self):
        for option in ['PEM', 'DER']:
            encoding = getattr(Encoding, option)
            stdout, stderr = self.cmd('dump_cert', self.cert.serial, format=encoding,
                                      stdout=BytesIO(), stderr=BytesIO())
            self.assertEqual(stderr, b'')
            self.assertEqual(stdout, self.cert.dump_certificate(encoding)) 
Example #18
Source File: tests_command_dump_cert.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def test_errors(self):
        path = os.path.join(ca_settings.CA_DIR, 'does-not-exist', 'test_cert.pem')
        msg = r"^\[Errno 2\] No such file or directory: '%s/does-not-exist/test_cert\.pem'$" % (
            ca_settings.CA_DIR)
        with self.assertCommandError(msg):
            self.cmd('dump_cert', self.cert.serial, path, stdout=BytesIO(), stderr=BytesIO())

        with self.assertCommandError(r"^Cannot dump bundle when using DER format\.$"):
            self.cmd('dump_cert', self.cert.serial, format=Encoding.DER, bundle=True,
                     stdout=BytesIO(), stderr=BytesIO()) 
Example #19
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 #20
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 #21
Source File: admin.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def download_view(self, request, pk):
        """A view that allows the user to download a certificate in PEM or DER/ASN1 format."""

        return self._download_response(request, pk) 
Example #22
Source File: recreate-fixtures.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def copy_cert(cert, data, key_path, csr_path):
    key_dest = os.path.join(args.dest, data['key_filename'])
    csr_dest = os.path.join(args.dest, data['csr_filename'])
    pub_dest = os.path.join(args.dest, data['pub_filename'])
    key_der_dest = os.path.join(args.dest, data['key_der_filename'])
    pub_der_dest = os.path.join(args.dest, data['pub_der_filename'])

    shutil.copy(key_path, key_dest)
    shutil.copy(csr_path, csr_dest)
    with open(pub_dest, 'w') as stream:
        stream.write(cert.pub)

    with open(key_dest, 'rb') as stream:
        priv_key = stream.read()
    priv_key = load_pem_private_key(priv_key, None, default_backend())
    key_der = priv_key.private_bytes(
        encoding=Encoding.DER, format=PrivateFormat.PKCS8, encryption_algorithm=NoEncryption())
    with open(key_der_dest, 'wb') as stream:
        stream.write(key_der)
    with open(pub_der_dest, 'wb') as stream:
        stream.write(cert.dump_certificate(Encoding.DER))

    data['crl'] = cert.ca.crl_url
    data['subject'] = cert.distinguishedName()
    data['parsed_cert'] = cert

    update_cert_data(cert, data) 
Example #23
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 #24
Source File: tests_admin.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def test_invalid_format(self):
        response = self.client.get('%s?format=INVALID' % self.url)
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.content, b'')

        # DER is not supported for bundles
        response = self.client.get('%s?format=DER' % self.url)
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.content, b'DER/ASN.1 certificates cannot be downloaded as a bundle.') 
Example #25
Source File: tests_admin.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def test_not_found(self):
        url = reverse('admin:django_ca_certificate_download', kwargs={'pk': '123'})
        response = self.client.get('%s?format=DER' % url)
        self.assertEqual(response.status_code, 404) 
Example #26
Source File: tests_utils.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def test_basic(self):
        self.assertEqual(parse_encoding(), Encoding.PEM)
        self.assertEqual(parse_encoding('PEM'), Encoding.PEM)
        self.assertEqual(parse_encoding(Encoding.PEM), Encoding.PEM)

        self.assertEqual(parse_encoding('DER'), Encoding.DER)
        self.assertEqual(parse_encoding('ASN1'), Encoding.DER)
        self.assertEqual(parse_encoding(Encoding.DER), Encoding.DER)

        self.assertEqual(parse_encoding('OpenSSH'), Encoding.OpenSSH)
        self.assertEqual(parse_encoding(Encoding.OpenSSH), Encoding.OpenSSH) 
Example #27
Source File: _certificate_utils.py    From sslyze with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_public_key_sha256(certificate: x509.Certificate) -> bytes:
    pub_bytes = certificate.public_key().public_bytes(encoding=Encoding.DER, format=PublicFormat.SubjectPublicKeyInfo)
    digest = sha256(pub_bytes).digest()
    return digest 
Example #28
Source File: tests_tasks.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def test_basic(self):
        hash_cls = hashes.SHA512
        enc_cls = Encoding.DER

        for ca, data in self.cas.items():
            tasks.cache_crl(data.serial)

            key = get_crl_cache_key(data.serial, hash_cls, enc_cls, 'ca')
            crl = x509.load_der_x509_crl(cache.get(key), default_backend())
            self.assertIsInstance(crl.signature_hash_algorithm, hash_cls)

            key = get_crl_cache_key(data.serial, hash_cls, enc_cls, 'user')
            crl = x509.load_der_x509_crl(cache.get(key), default_backend()) 
Example #29
Source File: models.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def cache_crls(self, password=None, algorithm=None):
        password = password or self.get_password()
        ca_key = self.key(password)
        if isinstance(ca_key, dsa.DSAPrivateKey) and algorithm is None:
            algorithm = hashes.SHA1()

        for name, config in ca_settings.CA_CRL_PROFILES.items():
            overrides = config.get('OVERRIDES', {}).get(self.serial, {})

            if overrides.get('skip'):
                continue

            algorithm = algorithm or parse_hash_algorithm(overrides.get('algorithm', config.get('algorithm')))
            expires = overrides.get('expires', config.get('expires', 86400))
            scope = overrides.get('scope', config.get('scope'))
            full_name = overrides.get('full_name', config.get('full_name'))
            relative_name = overrides.get('relative_name', config.get('relative_name'))
            encodings = overrides.get('encodings', config.get('encodings', ['DER', ]))
            crl = None  # only compute crl when it is actually needed

            for encoding in encodings:
                encoding = parse_encoding(encoding)
                cache_key = get_crl_cache_key(self.serial, algorithm, encoding, scope=scope)

                if expires >= 600:  # pragma: no branch
                    # for longer expiries we substract a random value so that regular CRL regeneration is
                    # distributed a bit
                    cache_expires = expires - random.randint(1, 5) * 60

                if cache.get(cache_key) is None:
                    if crl is None:
                        crl = self.get_crl(expires=expires, algorithm=algorithm, password=password,
                                           scope=scope, full_name=full_name, relative_name=relative_name)

                    encoded_crl = crl.public_bytes(encoding)
                    cache.set(cache_key, encoded_crl, cache_expires) 
Example #30
Source File: models.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def hpkp_pin(self):
        # taken from https://github.com/luisgf/hpkp-python/blob/master/hpkp.py

        public_key_raw = self.x509.public_key().public_bytes(
            encoding=Encoding.DER, format=PublicFormat.SubjectPublicKeyInfo)
        public_key_hash = hashlib.sha256(public_key_raw).digest()
        return base64.b64encode(public_key_hash).decode('utf-8')