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


Python Encoding.PEM屬性代碼示例

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


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

示例1: create

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

示例2: run_certificate_command

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

示例3: pathContainingDumpOf

# 需要導入模塊: from cryptography.hazmat.primitives.serialization import Encoding [as 別名]
# 或者: from cryptography.hazmat.primitives.serialization.Encoding import PEM [as 別名]
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 
開發者ID:proxysh,項目名稱:Safejumper-for-Desktop,代碼行數:25,代碼來源:test_sslverify.py

示例4: common_name

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

示例5: get_cainfo

# 需要導入模塊: from cryptography.hazmat.primitives.serialization import Encoding [as 別名]
# 或者: from cryptography.hazmat.primitives.serialization.Encoding import PEM [as 別名]
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'])) 
開發者ID:hyperledger,項目名稱:fabric-sdk-py,代碼行數:21,代碼來源:caservice.py

示例6: test_user_state

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

示例7: get

# 需要導入模塊: from cryptography.hazmat.primitives.serialization import Encoding [as 別名]
# 或者: from cryptography.hazmat.primitives.serialization.Encoding import PEM [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

示例8: add_arguments

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

示例9: _monkeypatch_to_fix_certificate_asdict

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

示例10: verified_certificate_chain_as_pem

# 需要導入模塊: from cryptography.hazmat.primitives.serialization import Encoding [as 別名]
# 或者: from cryptography.hazmat.primitives.serialization.Encoding import PEM [as 別名]
def verified_certificate_chain_as_pem(self) -> Optional[List[str]]:
        if self.verified_certificate_chain is None:
            return None

        pem_certs = []
        for certificate in self.verified_certificate_chain:
            pem_certs.append(certificate.public_bytes(Encoding.PEM).decode("ascii"))
        return pem_certs 
開發者ID:nabla-c0d3,項目名稱:sslyze,代碼行數:10,代碼來源:_cert_chain_analyzer.py

示例11: received_certificate_chain_as_pem

# 需要導入模塊: from cryptography.hazmat.primitives.serialization import Encoding [as 別名]
# 或者: from cryptography.hazmat.primitives.serialization.Encoding import PEM [as 別名]
def received_certificate_chain_as_pem(self) -> List[str]:
        pem_certs = []
        for certificate in self.received_certificate_chain:
            pem_certs.append(certificate.public_bytes(Encoding.PEM).decode("ascii"))
        return pem_certs 
開發者ID:nabla-c0d3,項目名稱:sslyze,代碼行數:7,代碼來源:_cert_chain_analyzer.py

示例12: _get_keys_from_dex

# 需要導入模塊: from cryptography.hazmat.primitives.serialization import Encoding [as 別名]
# 或者: from cryptography.hazmat.primitives.serialization.Encoding import PEM [as 別名]
def _get_keys_from_dex():
    resp = requests.get(urljoin(DEX_URL, AuthParameters.KEYS_PATH), params=None)
    data = json.loads(resp.text)
    keys = []
    for k in data['keys']:
        jwk = jwk_from_dict(k)
        keys.append(jwk)
        logger.info("PEM {}".format(jwk.keyobj.
                                    public_bytes(Encoding.PEM,
                                                 PublicFormat.SubjectPublicKeyInfo)
                                    .decode('utf-8')))
    logger.info("Number of imported keys :" + str(len(keys)))
    return keys 
開發者ID:IntelAI,項目名稱:inference-model-manager,代碼行數:15,代碼來源:auth_controller.py

示例13: get_keys

# 需要導入模塊: from cryptography.hazmat.primitives.serialization import Encoding [as 別名]
# 或者: from cryptography.hazmat.primitives.serialization.Encoding import PEM [as 別名]
def get_keys():
    data = json.loads(keys_json)
    keys = []
    for k in data['keys']:
        jwk = jwk_from_dict(k)
        print(jwk.keyobj.public_bytes(Encoding.PEM, PublicFormat.SubjectPublicKeyInfo))
        keys.append(jwk)

    print("Number of imported keys :" + str(len(keys)))
    print("Keys: {}".format(keys))
    return keys 
開發者ID:IntelAI,項目名稱:inference-model-manager,代碼行數:13,代碼來源:test_endpoints_auth.py

示例14: __init__

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

示例15: create_ssl_context

# 需要導入模塊: from cryptography.hazmat.primitives.serialization import Encoding [as 別名]
# 或者: from cryptography.hazmat.primitives.serialization.Encoding import PEM [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


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