當前位置: 首頁>>代碼示例>>Python>>正文


Python Encoding.DER屬性代碼示例

本文整理匯總了Python中cryptography.hazmat.primitives.serialization.Encoding.DER屬性的典型用法代碼示例。如果您正苦於以下問題:Python Encoding.DER屬性的具體用法?Python Encoding.DER怎麽用?Python Encoding.DER使用的例子?那麽, 這裏精選的屬性代碼示例或許可以為您提供幫助。您也可以進一步了解該屬性所在cryptography.hazmat.primitives.serialization.Encoding的用法示例。


在下文中一共展示了Encoding.DER屬性的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: anchor_certs

# 需要導入模塊: from cryptography.hazmat.primitives.serialization import Encoding [as 別名]
# 或者: from cryptography.hazmat.primitives.serialization.Encoding import DER [as 別名]
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) 
開發者ID:cmdmnt,項目名稱:commandment,代碼行數:23,代碼來源:app.py

示例2: get

# 需要導入模塊: from cryptography.hazmat.primitives.serialization import Encoding [as 別名]
# 或者: from cryptography.hazmat.primitives.serialization.Encoding import DER [as 別名]
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) 
開發者ID:mathiasertl,項目名稱:django-ca,代碼行數:26,代碼來源:views.py

示例3: handle

# 需要導入模塊: from cryptography.hazmat.primitives.serialization import Encoding [as 別名]
# 或者: from cryptography.hazmat.primitives.serialization.Encoding import DER [as 別名]
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) 
開發者ID:mathiasertl,項目名稱:django-ca,代碼行數:20,代碼來源:dump_cert.py

示例4: handle

# 需要導入模塊: from cryptography.hazmat.primitives.serialization import Encoding [as 別名]
# 或者: from cryptography.hazmat.primitives.serialization.Encoding import DER [as 別名]
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) 
開發者ID:mathiasertl,項目名稱:django-ca,代碼行數:20,代碼來源:dump_ca.py

示例5: test_basic

# 需要導入模塊: from cryptography.hazmat.primitives.serialization import Encoding [as 別名]
# 或者: from cryptography.hazmat.primitives.serialization.Encoding import DER [as 別名]
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) 
開發者ID:mathiasertl,項目名稱:django-ca,代碼行數:18,代碼來源:tests_command_cache_crls.py

示例6: test_der

# 需要導入模塊: from cryptography.hazmat.primitives.serialization import Encoding [as 別名]
# 或者: from cryptography.hazmat.primitives.serialization.Encoding import DER [as 別名]
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'') 
開發者ID:mathiasertl,項目名稱:django-ca,代碼行數:25,代碼來源:tests_command_view_cert.py

示例7: test_basic

# 需要導入模塊: from cryptography.hazmat.primitives.serialization import Encoding [as 別名]
# 或者: from cryptography.hazmat.primitives.serialization.Encoding import DER [as 別名]
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) 
開發者ID:mathiasertl,項目名稱:django-ca,代碼行數:27,代碼來源:tests_views.py

示例8: calculate_public_key_fingerprint

# 需要導入模塊: from cryptography.hazmat.primitives.serialization import Encoding [as 別名]
# 或者: from cryptography.hazmat.primitives.serialization.Encoding import DER [as 別名]
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 
開發者ID:snowflakedb,項目名稱:snowflake-ingest-python,代碼行數:26,代碼來源:tokentools.py

示例9: get_public_key_sha256

# 需要導入模塊: from cryptography.hazmat.primitives.serialization import Encoding [as 別名]
# 或者: from cryptography.hazmat.primitives.serialization.Encoding import DER [as 別名]
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 
開發者ID:nabla-c0d3,項目名稱:sslyze,代碼行數:6,代碼來源:_certificate_utils.py

示例10: authenticate

# 需要導入模塊: from cryptography.hazmat.primitives.serialization import Encoding [as 別名]
# 或者: from cryptography.hazmat.primitives.serialization.Encoding import DER [as 別名]
def authenticate(
            self, authenticator, service_name, account, user, password):
        account = account.upper()
        user = user.upper()

        now = datetime.utcnow()

        try:
            private_key = load_der_private_key(data=self._private_key, password=None, backend=default_backend())
        except Exception as e:
            raise ProgrammingError(
                msg='Failed to load private key: {}\nPlease provide a valid unencrypted rsa private '
                    'key in DER format as bytes object'.format(str(e)),
                errno=ER_INVALID_PRIVATE_KEY
            )

        if not isinstance(private_key, RSAPrivateKey):
            raise ProgrammingError(
                msg='Private key type ({}) not supported.\nPlease provide a valid rsa private '
                    'key in DER format as bytes object'.format(private_key.__class__.__name__),
                errno=ER_INVALID_PRIVATE_KEY
            )

        public_key_fp = self.calculate_public_key_fingerprint(private_key)

        self._jwt_token_exp = now + self.LIFETIME
        payload = {
            self.ISSUER: "{}.{}.{}".format(account, user, public_key_fp),
            self.SUBJECT: "{}.{}".format(account, user),
            self.ISSUE_TIME: now,
            self.EXPIRE_TIME: self._jwt_token_exp
        }

        self._jwt_token = jwt.encode(payload, private_key,
                                     algorithm=self.ALGORITHM).decode('utf-8')

        return self._jwt_token 
開發者ID:snowflakedb,項目名稱:snowflake-connector-python,代碼行數:39,代碼來源:auth_keypair.py

示例11: calculate_public_key_fingerprint

# 需要導入模塊: from cryptography.hazmat.primitives.serialization import Encoding [as 別名]
# 或者: from cryptography.hazmat.primitives.serialization.Encoding import DER [as 別名]
def calculate_public_key_fingerprint(private_key):
        # get public key bytes
        public_key_der = 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_der)

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

        return public_key_fp 
開發者ID:snowflakedb,項目名稱:snowflake-connector-python,代碼行數:14,代碼來源:auth_keypair.py

示例12: profile

# 需要導入模塊: from cryptography.hazmat.primitives.serialization import Encoding [as 別名]
# 或者: from cryptography.hazmat.primitives.serialization.Encoding import DER [as 別名]
def profile():
    """Accept a CMS Signed DER encoded XML data containing device information.

    This starts the DEP enrollment process. The absolute url to this endpoint should be present in the DEP profile's
    enrollment URL.

    The signed data contains a plist with the following keys:

    :UDID: The device’s UDID.
    :SERIAL: The device's Serial Number.
    :PRODUCT: The device’s product type: e.g., iPhone5,1.
    :VERSION: The OS version installed on the device: e.g., 7A182.
    :IMEI: The device’s IMEI (if available).
    :MEID: The device’s MEID (if available).
    :LANGUAGE: The user’s currently-selected language: e.g., en.

    See Also:
        - `Mobile Device Management Protocol: Request to a Profile URL
            <https://developer.apple.com/library/content/documentation/Miscellaneous/Reference/MobileDeviceManagementProtocolRef/4-Profile_Management/ProfileManagement.html#//apple_ref/doc/uid/TP40017387-CH7-SW242>`_.
    """
    g.plist_data = plistlib.loads(g.signed_data)
    profile = generate_enroll_profile()

    schema = ProfileSchema()
    result = schema.dump(profile)
    plist_data = dumps_none(result.data, skipkeys=True)

    return plist_data, 200, {'Content-Type': PROFILE_CONTENT_TYPE} 
開發者ID:cmdmnt,項目名稱:commandment,代碼行數:30,代碼來源:app.py

示例13: create_ssl_context

# 需要導入模塊: from cryptography.hazmat.primitives.serialization import Encoding [as 別名]
# 或者: from cryptography.hazmat.primitives.serialization.Encoding import DER [as 別名]
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 
開發者ID:alfa-addon,項目名稱:addon,代碼行數:39,代碼來源:x509.py

示例14: parse_csr

# 需要導入模塊: from cryptography.hazmat.primitives.serialization import Encoding [as 別名]
# 或者: from cryptography.hazmat.primitives.serialization.Encoding import DER [as 別名]
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) 
開發者ID:mathiasertl,項目名稱:django-ca,代碼行數:11,代碼來源:managers.py

示例15: fail

# 需要導入模塊: from cryptography.hazmat.primitives.serialization import Encoding [as 別名]
# 或者: from cryptography.hazmat.primitives.serialization.Encoding import DER [as 別名]
def fail(self, status=ocsp.OCSPResponseStatus.INTERNAL_ERROR):
        return self.http_response(
            ocsp.OCSPResponseBuilder.build_unsuccessful(status).public_bytes(Encoding.DER)
        ) 
開發者ID:mathiasertl,項目名稱:django-ca,代碼行數:6,代碼來源:views.py


注:本文中的cryptography.hazmat.primitives.serialization.Encoding.DER屬性示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。