本文整理汇总了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)
示例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}
示例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
示例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
)
示例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']))
示例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'))
示例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)
示例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'))
示例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
示例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
示例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
示例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
示例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
示例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)
示例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