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


Python x509.load_der_x509_certificate方法代碼示例

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


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

示例1: validate

# 需要導入模塊: from cryptography import x509 [as 別名]
# 或者: from cryptography.x509 import load_der_x509_certificate [as 別名]
def validate(self, authenticator_data, rp_id_hash, client_data_hash):
        # See https://www.w3.org/TR/webauthn/#fido-u2f-attestation, "Verification procedure"
        credential = authenticator_data.credential
        public_key_u2f = b'\x04' + credential.public_key.x + credential.public_key.y
        verification_data = b'\x00' + rp_id_hash + client_data_hash + credential.id + public_key_u2f
        assert len(credential.public_key.x) == 32
        assert len(credential.public_key.y) == 32
        self.cert_public_key.verify(self.signature, verification_data, ec.ECDSA(hashes.SHA256()))
        key_id = x509.SubjectKeyIdentifier.from_public_key(self.cert_public_key).digest.hex()
        att_root_cert_chain = self.metadata_for_key_id(key_id)["attestationRootCertificates"]

        # TODO: implement full cert chain validation
        # See https://cryptography.io/en/latest/x509/reference/#cryptography.x509.Certificate.tbs_certificate_bytes
        # See https://github.com/pyca/cryptography/issues/2381
        # See https://github.com/wbond/certvalidator
        assert len(att_root_cert_chain) == 1
        att_root_cert = x509.load_der_x509_certificate(att_root_cert_chain[0].encode(),
                                                       cryptography.hazmat.backends.default_backend())
        att_root_cert.public_key().verify(self.att_cert.signature,
                                          self.att_cert.tbs_certificate_bytes,
                                          padding.PKCS1v15(),
                                          self.att_cert.signature_hash_algorithm)
        return self.validated_attestation(type="Basic", trust_path="x5c", credential=credential) 
開發者ID:pyauth,項目名稱:pywarp,代碼行數:25,代碼來源:attestation.py

示例2: request_cert

# 需要導入模塊: from cryptography import x509 [as 別名]
# 或者: from cryptography.x509 import load_der_x509_certificate [as 別名]
def request_cert(self, builder, **kwargs):
        """Send CSR and request certificate
        """
        signed = self._sign_csr(builder)
        csr_pem = signed.public_bytes(serialization.Encoding.PEM)
        if not isinstance(csr_pem, six.text_type):
            csr_pem = csr_pem.decode('ascii')

        response = self._cert_request(csr_pem, **kwargs)

        if self.plugin.chain:
            certs = tuple(
                x509.load_der_x509_certificate(cert, self.backend)
                for cert in response[u'result'][u'certificate_chain']
            )
        else:
            # certificate is just base64 without BEGIN/END certificate
            cert = base64.b64decode(response[u'result'][u'certificate'])
            certs = (x509.load_der_x509_certificate(cert, self.backend), )

        pem = [self._dump_privkey(self._privkey)]
        pem.extend(self._dump_cert(cert) for cert in certs)
        return response, '\n'.join(pem) 
開發者ID:latchset,項目名稱:custodia,代碼行數:25,代碼來源:certrequest.py

示例3: _process_pkcs7_substrate

# 需要導入模塊: from cryptography import x509 [as 別名]
# 或者: from cryptography.x509 import load_der_x509_certificate [as 別名]
def _process_pkcs7_substrate(substrate):
    contentInfo, _ = der_decoder.decode(substrate,
                                        asn1Spec=rfc2315.ContentInfo())

    contentType = contentInfo.getComponentByName('contentType')

    if contentType != rfc2315.signedData:
        raise Exception

    content, _ = der_decoder.decode(
        contentInfo.getComponentByName('content'),
        asn1Spec=rfc2315.SignedData())

    for blob in content.getComponentByName('certificates'):
        cert = x509.load_der_x509_certificate(der_encoder.encode(blob),
                                              backends.default_backend())
        print(cert.public_bytes(
            encoding=serialization.Encoding.PEM).decode(
            'unicode_escape'), end='')


# Main program code 
開發者ID:openstack,項目名稱:octavia,代碼行數:24,代碼來源:pkcs7_to_pem.py

示例4: test_xmldsig_interop_TR2012

# 需要導入模塊: from cryptography import x509 [as 別名]
# 或者: from cryptography.x509 import load_der_x509_certificate [as 別名]
def test_xmldsig_interop_TR2012(self):
        def get_x509_cert(**kwargs):
            from cryptography.x509 import load_der_x509_certificate
            from OpenSSL.crypto import X509
            with open(os.path.join(interop_dir, "TR2012", "rsa-cert.der"), "rb") as fh:
                return [X509.from_cryptography(load_der_x509_certificate(fh.read(), backend=default_backend()))]

        signature_files = glob(os.path.join(interop_dir, "TR2012", "signature*.xml"))
        for signature_file in signature_files:
            print("Verifying", signature_file)
            with open(signature_file, "rb") as fh:
                try:
                    sig = fh.read()
                    XMLVerifier().verify(sig, require_x509=False, hmac_key="testkey", validate_schema=True,
                                         cert_resolver=get_x509_cert if "x509digest" in signature_file else None)
                    decoded_sig = sig.decode("utf-8")
                except Exception as e:
                    if "keyinforeference" in signature_file:
                        print("Unsupported test case:", type(e), e)
                    elif "x509digest" in signature_file:
                        assert isinstance(e, InvalidCertificate)
                    else:
                        raise 
開發者ID:XML-Security,項目名稱:signxml,代碼行數:25,代碼來源:test.py

示例5: handle

# 需要導入模塊: from cryptography import x509 [as 別名]
# 或者: from cryptography.x509 import load_der_x509_certificate [as 別名]
def handle(self, pub, **options):
        pub_data = pub.read()

        try:  # close reader objects (otherwise we get a ResourceWarning)
            pub.close()
        except Exception:  # pragma: no cover
            pass

        # load public key
        try:
            pub_loaded = x509.load_pem_x509_certificate(pub_data, default_backend())
        except Exception:
            try:
                pub_loaded = x509.load_der_x509_certificate(pub_data, default_backend())
            except Exception:
                raise CommandError('Unable to load public key.')

        cert = Certificate(ca=options['ca'])
        cert.x509 = pub_loaded
        cert.save() 
開發者ID:mathiasertl,項目名稱:django-ca,代碼行數:22,代碼來源:import_cert.py

示例6: _load_pub

# 需要導入模塊: from cryptography import x509 [as 別名]
# 或者: from cryptography.x509 import load_der_x509_certificate [as 別名]
def _load_pub(data):
    basedir = data.get('basedir', settings.FIXTURES_DIR)
    path = os.path.join(basedir, data['pub_filename'])

    with open(path, 'rb') as stream:
        pem = stream.read().replace(b'\r\n', b'\n')

    pub_data = {
        'pem': pem.decode('utf-8'),
        'parsed': x509.load_pem_x509_certificate(pem, default_backend()),
    }

    if data.get('pub_der_filename'):
        der_path = os.path.join(basedir, data['pub_der_filename'])
        with open(der_path, 'rb') as stream:
            der = stream.read().replace(b'\r\n', b'\n')
        pub_data['der'] = der
        # Failes for alt-extensions since alternative AKI was added
        #pub_data['der_parsed'] = x509.load_der_x509_certificate(der, default_backend()),

    return pub_data 
開發者ID:mathiasertl,項目名稱:django-ca,代碼行數:23,代碼來源:base.py

示例7: test_BackuprKey_BACKUPKEY_RETRIEVE_BACKUP_KEY_GUID

# 需要導入模塊: from cryptography import x509 [as 別名]
# 或者: from cryptography.x509 import load_der_x509_certificate [as 別名]
def test_BackuprKey_BACKUPKEY_RETRIEVE_BACKUP_KEY_GUID(self):
        dce, rpctransport = self.connect()
        request = bkrp.BackuprKey()
        request['pguidActionAgent'] = bkrp.BACKUPKEY_RETRIEVE_BACKUP_KEY_GUID
        request['pDataIn'] = NULL
        request['cbDataIn'] = 0
        request['dwParam'] = 0

        resp = dce.request(request)

        resp.dump()

        #print "LEN: %d" % len(''.join(resp['ppDataOut']))
        #hexdump(''.join(resp['ppDataOut']))

        cert = x509.load_der_x509_certificate(b''.join(resp['ppDataOut']), default_backend())

        print(cert.subject)
        print(cert.issuer)
        print(cert.signature) 
開發者ID:Coalfire-Research,項目名稱:Slackor,代碼行數:22,代碼來源:test_bkrp.py

示例8: test_hBackuprKey_BACKUPKEY_RETRIEVE_BACKUP_KEY_GUID

# 需要導入模塊: from cryptography import x509 [as 別名]
# 或者: from cryptography.x509 import load_der_x509_certificate [as 別名]
def test_hBackuprKey_BACKUPKEY_RETRIEVE_BACKUP_KEY_GUID(self):
        dce, rpctransport = self.connect()
        request = bkrp.BackuprKey()
        request['pguidActionAgent'] = bkrp.BACKUPKEY_RETRIEVE_BACKUP_KEY_GUID
        request['pDataIn'] = NULL
        request['cbDataIn'] = 0
        request['dwParam'] = 0

        resp = bkrp.hBackuprKey(dce, bkrp.BACKUPKEY_RETRIEVE_BACKUP_KEY_GUID, NULL)

        resp.dump()

        #print "LEN: %d" % len(''.join(resp['ppDataOut']))
        #hexdump(''.join(resp['ppDataOut']))

        cert = x509.load_der_x509_certificate(b''.join(resp['ppDataOut']), default_backend())

        print(cert.subject)
        print(cert.issuer)
        print(cert.signature) 
開發者ID:Coalfire-Research,項目名稱:Slackor,代碼行數:22,代碼來源:test_bkrp.py

示例9: __init__

# 需要導入模塊: from cryptography import x509 [as 別名]
# 或者: from cryptography.x509 import load_der_x509_certificate [as 別名]
def __init__(self, data):
        """
        Cert constructor

        It can handle PEM and DER encoded strings and lists of int bytes.

        :param data: bytes or list of int
        """
        if type(data) == list:
            data = bytes(data)
        if type(data) != bytes:
            raise Exception("data must be bytes or list of int bytes")
        self.__raw_data = data
        if b"-----BEGIN CERTIFICATE-----" in data:
            self.x509 = x509.load_pem_x509_certificate(data, backends.default_backend())
            self.__raw_type = "PEM"
        else:
            self.x509 = x509.load_der_x509_certificate(data, backends.default_backend())
            self.__raw_type = "DER" 
開發者ID:mozilla,項目名稱:tls-canary,代碼行數:21,代碼來源:cert.py

示例10: fqdns_from_certificate

# 需要導入模塊: from cryptography import x509 [as 別名]
# 或者: from cryptography.x509 import load_der_x509_certificate [as 別名]
def fqdns_from_certificate(cert_data):

    try:
        cert = x509.load_pem_x509_certificate(cert_data, default_backend())
    except ValueError:
        pass

    try:
        cert = x509.load_der_x509_certificate(cert_data, default_backend())
    except ValueError:
        raise ValueError("No recognized cert format. Allowed: PEM or DER")

    names = set()
    names.add(cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME)[0].value.lower().rstrip('.'))

    try:
        alt_names = cert.extensions.get_extension_for_class(x509.SubjectAlternativeName)
    except x509.extensions.ExtensionNotFound:
        alt_names = None

    if alt_names:
        for alt_name in alt_names.value.get_values_for_type(x509.DNSName):
            names.add(alt_name.lower().rstrip('.'))

    return list(sorted(names)) 
開發者ID:fportantier,項目名稱:habu,代碼行數:27,代碼來源:fqdn_finder.py

示例11: cert_get_names

# 需要導入模塊: from cryptography import x509 [as 別名]
# 或者: from cryptography.x509 import load_der_x509_certificate [as 別名]
def cert_get_names(cert_data):

    try:
        cert = x509.load_pem_x509_certificate(cert_data, default_backend())
    except ValueError:
        pass

    try:
        cert = x509.load_der_x509_certificate(cert_data, default_backend())
    except ValueError:
        raise ValueError("No recognized cert format. Allowed: PEM or DER")

    names = set()
    names.add(cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME)[0].value.lower())

    try:
        alt_names = cert.extensions.get_extension_for_class(x509.SubjectAlternativeName)
    except x509.extensions.ExtensionNotFound:
        alt_names = None

    if alt_names:
        for alt_name in alt_names.value.get_values_for_type(x509.DNSName):
            names.add(alt_name.lower())

    return list(sorted(names)) 
開發者ID:fportantier,項目名稱:habu,代碼行數:27,代碼來源:cmd_cert_names.py

示例12: metadata_toc

# 需要導入模塊: from cryptography import x509 [as 別名]
# 或者: from cryptography.x509 import load_der_x509_certificate [as 別名]
def metadata_toc(self):
        if self._metadata_toc is None:
            res = requests.get(self.mds_url)
            res.raise_for_status()
            jwt_header = jwt.get_unverified_header(res.content)
            assert jwt_header["alg"] == "ES256"
            cert = x509.load_der_x509_certificate(jwt_header["x5c"][0].encode(),
                                                  cryptography.hazmat.backends.default_backend())
            self._metadata_toc = jwt.decode(res.content, key=cert.public_key(), algorithms=["ES256"])
        return self._metadata_toc 
開發者ID:pyauth,項目名稱:pywarp,代碼行數:12,代碼來源:metadata.py

示例13: __init__

# 需要導入模塊: from cryptography import x509 [as 別名]
# 或者: from cryptography.x509 import load_der_x509_certificate [as 別名]
def __init__(self, att_stmt):
        self.att_stmt = att_stmt
        assert len(self.att_stmt["x5c"]) == 1
        der_cert = att_stmt["x5c"][0]
        self.att_cert = x509.load_der_x509_certificate(der_cert, cryptography.hazmat.backends.default_backend())
        self.cert_public_key = self.att_cert.public_key()
        self.signature = att_stmt["sig"] 
開發者ID:pyauth,項目名稱:pywarp,代碼行數:9,代碼來源:attestation.py

示例14: _get_normalized_payload

# 需要導入模塊: from cryptography import x509 [as 別名]
# 或者: from cryptography.x509 import load_der_x509_certificate [as 別名]
def _get_normalized_payload(self, encoded_bytes, secret_type):
        """Normalizes the bytes of the object.

        Barbican expects certificates, public keys, and private keys in PEM
        format, but Castellan expects these objects to be DER encoded bytes
        instead.
        """
        if secret_type == 'public':
            key = serialization.load_der_public_key(
                encoded_bytes,
                backend=backends.default_backend())
            return key.public_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PublicFormat.SubjectPublicKeyInfo)
        elif secret_type == 'private':
            key = serialization.load_der_private_key(
                encoded_bytes,
                backend=backends.default_backend(),
                password=None)
            return key.private_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PrivateFormat.PKCS8,
                encryption_algorithm=serialization.NoEncryption())
        elif secret_type == 'certificate':
            cert = cryptography_x509.load_der_x509_certificate(
                encoded_bytes,
                backend=backends.default_backend())
            return cert.public_bytes(encoding=serialization.Encoding.PEM)
        else:
            return encoded_bytes 
開發者ID:openstack,項目名稱:castellan,代碼行數:32,代碼來源:barbican_key_manager.py

示例15: scan

# 需要導入模塊: from cryptography import x509 [as 別名]
# 或者: from cryptography.x509 import load_der_x509_certificate [as 別名]
def scan(self, offset=0, maxlen=None):
        for hit in super(CertScanner, self).scan(offset=offset, maxlen=maxlen):
            signature = self.address_space.read(hit + 4, 3)
            size = self.profile.Object(
                "unsigned be short", offset=hit+2, vm=self.address_space)
            description = None

            if signature.startswith(b"\x30\x82"):
                data = self.address_space.read(hit, size + 4)
                if x509:
                    try:
                        cert = x509.load_der_x509_certificate(data, default_backend())
                        description = dict((
                            attr.oid._name, attr.value) for attr in cert.subject)
                    except Exception:
                        pass

                yield hit, "X509", data, description

            elif signature.startswith(b"\x02\x01\x00"):
                data = self.address_space.read(hit, size + 4)
                if x509:
                    try:
                        pem = (b"-----BEGIN RSA PRIVATE KEY-----\n" +
                               base64.b64encode(data) +
                               b"-----END RSA PRIVATE KEY-----")
                        key = serialization.load_pem_private_key(
                            pem, password=None, backend=default_backend())
                        description = ""
                    except Exception:
                        pass

                yield hit, "RSA", data, description 
開發者ID:google,項目名稱:rekall,代碼行數:35,代碼來源:dumpcerts.py


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