本文整理汇总了Python中asn1crypto.pem.unarmor方法的典型用法代码示例。如果您正苦于以下问题:Python pem.unarmor方法的具体用法?Python pem.unarmor怎么用?Python pem.unarmor使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类asn1crypto.pem
的用法示例。
在下文中一共展示了pem.unarmor方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_revoked
# 需要导入模块: from asn1crypto import pem [as 别名]
# 或者: from asn1crypto.pem import unarmor [as 别名]
def get_revoked(serial):
if isinstance(serial, str):
serial = int(serial, 16)
path = os.path.join(config.REVOKED_DIR, "%040x.pem" % serial)
with open(path, "rb") as fh:
buf = fh.read()
header, _, der_bytes = pem.unarmor(buf)
cert = x509.Certificate.load(der_bytes)
try:
reason = getxattr(path, "user.revocation.reason").decode("ascii")
except IOError: # TODO: make sure it's not required
reason = "key_compromise"
return path, buf, cert, \
cert["tbs_certificate"]["validity"]["not_before"].native.replace(tzinfo=None), \
cert["tbs_certificate"]["validity"]["not_after"].native.replace(tzinfo=None), \
datetime.utcfromtimestamp(os.stat(path).st_ctime), \
reason
示例2: authorize_server
# 需要导入模块: from asn1crypto import pem [as 别名]
# 或者: from asn1crypto.pem import unarmor [as 别名]
def authorize_server(func):
"""
Make sure the request originator has a certificate with server flags
"""
from asn1crypto import pem, x509
def wrapped(resource, req, resp, *args, **kwargs):
buf = req.get_header("X-SSL-CERT")
if not buf:
logger.info("No TLS certificate presented to access administrative API call from %s" % req.context.get("remote_addr"))
raise falcon.HTTPForbidden("Forbidden", "Machine not authorized to perform the operation")
header, _, der_bytes = pem.unarmor(buf.replace("\t", "").encode("ascii"))
cert = x509.Certificate.load(der_bytes) # TODO: validate serial
for extension in cert["tbs_certificate"]["extensions"]:
if extension["extn_id"].native == "extended_key_usage":
if "server_auth" in extension["extn_value"].native:
req.context["machine"] = cert.subject.native["common_name"]
return func(resource, req, resp, *args, **kwargs)
logger.info("TLS authenticated machine '%s' not authorized to access administrative API", cert.subject.native["common_name"])
raise falcon.HTTPForbidden("Forbidden", "Machine not authorized to perform the operation")
return wrapped
示例3: on_put
# 需要导入模块: from asn1crypto import pem [as 别名]
# 或者: from asn1crypto.pem import unarmor [as 别名]
def on_put(self, req, resp):
try:
username, mail, created, expires, profile = self.manager.consume(req.get_param("token", required=True))
except RelationalMixin.DoesNotExist:
raise falcon.HTTPForbidden("Forbidden", "No such token or token expired")
body = req.stream.read(req.content_length)
header, _, der_bytes = pem.unarmor(body)
csr = CertificationRequest.load(der_bytes)
common_name = csr["certification_request_info"]["subject"].native["common_name"]
if not common_name.startswith(username + "@"):
raise falcon.HTTPBadRequest("Bad requst", "Invalid common name %s" % common_name)
try:
_, resp.body = self.authority._sign(csr, body, profile=config.PROFILES.get(profile),
overwrite=config.TOKEN_OVERWRITE_PERMITTED)
resp.set_header("Content-Type", "application/x-pem-file")
logger.info("Autosigned %s as proven by token ownership", common_name)
except FileExistsError:
logger.info("Won't autosign duplicate %s", common_name)
raise falcon.HTTPConflict(
"Certificate with such common name (CN) already exists",
"Will not overwrite existing certificate signing request, explicitly delete existing one and try again")
示例4: pem_to_der
# 需要导入模块: from asn1crypto import pem [as 别名]
# 或者: from asn1crypto.pem import unarmor [as 别名]
def pem_to_der(cert: bytes, return_multiple: bool = True):
"""Converts a given certificate or list to PEM format."""
# initialize the certificate array
cert_list = []
# If certificate is in DER then un-armour it
if pem.detect(cert):
for _, _, der_bytes in pem.unarmor(cert, multiple=True):
cert_list.append(der_bytes)
else:
cert_list.append(cert)
# return multiple if return_multiple is set else first element
if return_multiple:
return cert_list
else:
return cert_list.pop()
示例5: _grab_crl
# 需要导入模块: from asn1crypto import pem [as 别名]
# 或者: from asn1crypto.pem import unarmor [as 别名]
def _grab_crl(user_agent, url, timeout):
"""
Fetches a CRL and parses it
:param user_agent:
A unicode string of the user agent to use when fetching the URL
:param url:
A unicode string of the URL to fetch the CRL from
:param timeout:
The number of seconds after which an HTTP request should timeout
:return:
An asn1crypto.crl.CertificateList object
"""
request = Request(url)
request.add_header('Accept', 'application/pkix-crl')
request.add_header('User-Agent', user_agent)
response = urlopen(request, None, timeout)
data = response.read()
if pem.detect(data):
_, _, data = pem.unarmor(data)
return crl.CertificateList.load(data)
示例6: test_build_paths
# 需要导入模块: from asn1crypto import pem [as 别名]
# 或者: from asn1crypto.pem import unarmor [as 别名]
def test_build_paths(self):
with open(os.path.join(fixtures_dir, 'mozilla.org.crt'), 'rb') as f:
cert_bytes = f.read()
if pem.detect(cert_bytes):
_, _, cert_bytes = pem.unarmor(cert_bytes)
cert = x509.Certificate.load(cert_bytes)
with open(os.path.join(fixtures_dir, 'digicert-sha2-secure-server-ca.crt'), 'rb') as f:
other_certs = [f.read()]
repo = CertificateRegistry(other_certs=other_certs)
paths = repo.build_paths(cert)
self.assertEqual(1, len(paths))
path = paths[0]
self.assertEqual(3, len(path))
self.assertEqual(
[
b'\x80Q\x06\x012\xad\x9a\xc2}Q\x87\xa0\xe8\x87\xfb\x01b\x01U\xee',
b"\x10_\xa6z\x80\x08\x9d\xb5'\x9f5\xce\x83\x0bC\x88\x9e\xa3\xc7\r",
b'I\xac\x03\xf8\xf3Km\xca)V)\xf2I\x9a\x98\xbe\x98\xdc.\x81'
],
[item.subject.sha1 for item in path]
)
示例7: test_unarmor_multiple
# 需要导入模块: from asn1crypto import pem [as 别名]
# 或者: from asn1crypto.pem import unarmor [as 别名]
def test_unarmor_multiple(self):
data = self.unarmor_armor_files()
input_data = b''
der_data = []
for pem_file, der_file in ((data[0][0], data[0][1]), (data[1][0], data[1][1])):
with open(os.path.join(fixtures_dir, pem_file), 'rb') as f:
input_data += f.read() + b'\n'
with open(os.path.join(fixtures_dir, der_file), 'rb') as f:
der_data.append(f.read())
i = 0
for name, headers, der_bytes in pem.unarmor(input_data, True):
self.assertEqual('CERTIFICATE', name)
self.assertEqual({}, headers)
self.assertEqual(der_data[i], der_bytes)
i += 1
self.assertEqual(2, i)
示例8: get_request
# 需要导入模块: from asn1crypto import pem [as 别名]
# 或者: from asn1crypto.pem import unarmor [as 别名]
def get_request(common_name):
if not re.match(const.RE_COMMON_NAME, common_name):
raise ValueError("Invalid common name %s" % repr(common_name))
path = os.path.join(config.REQUESTS_DIR, common_name + ".pem")
try:
with open(path, "rb") as fh:
buf = fh.read()
header, _, der_bytes = pem.unarmor(buf)
return path, buf, CertificationRequest.load(der_bytes), \
datetime.utcfromtimestamp(os.stat(path).st_ctime)
except EnvironmentError:
raise errors.RequestDoesNotExist("Certificate signing request file %s does not exist" % path)
示例9: get_signed
# 需要导入模块: from asn1crypto import pem [as 别名]
# 或者: from asn1crypto.pem import unarmor [as 别名]
def get_signed(common_name):
if not re.match(const.RE_COMMON_NAME, common_name):
raise ValueError("Invalid common name %s" % repr(common_name))
path = os.path.join(config.SIGNED_DIR, common_name + ".pem")
with open(path, "rb") as fh:
buf = fh.read()
header, _, der_bytes = pem.unarmor(buf)
cert = x509.Certificate.load(der_bytes)
return path, buf, cert, \
cert["tbs_certificate"]["validity"]["not_before"].native.replace(tzinfo=None), \
cert["tbs_certificate"]["validity"]["not_after"].native.replace(tzinfo=None)
示例10: _list_certificates
# 需要导入模块: from asn1crypto import pem [as 别名]
# 或者: from asn1crypto.pem import unarmor [as 别名]
def _list_certificates(directory):
for filename in os.listdir(directory):
if filename.endswith(".pem"):
path = os.path.join(directory, filename)
with open(path, "rb") as fh:
buf = fh.read()
header, _, der_bytes = pem.unarmor(buf)
cert = x509.Certificate.load(der_bytes)
server = False
for extension in cert["tbs_certificate"]["extensions"]:
if extension["extn_id"].native == "extended_key_usage":
if "server_auth" in extension["extn_value"].native:
server = True
yield cert.subject.native["common_name"], path, buf, cert, server
示例11: whitelist_subject
# 需要导入模块: from asn1crypto import pem [as 别名]
# 或者: from asn1crypto.pem import unarmor [as 别名]
def whitelist_subject(func):
def wrapped(self, req, resp, cn, *args, **kwargs):
from ipaddress import ip_address
from certidude import authority
from xattr import getxattr
try:
path, buf, cert, signed, expires = authority.get_signed(cn)
except IOError:
raise falcon.HTTPNotFound()
else:
# First attempt to authenticate client with certificate
buf = req.get_header("X-SSL-CERT")
if buf:
header, _, der_bytes = pem.unarmor(buf.replace("\t", "").encode("ascii"))
origin_cert = x509.Certificate.load(der_bytes)
if origin_cert.native == cert.native:
logger.debug("Subject authenticated using certificates")
return func(self, req, resp, cn, *args, **kwargs)
# For backwards compatibility check source IP address
# TODO: make it disableable
try:
inner_address = getxattr(path, "user.lease.inner_address").decode("ascii")
except IOError:
raise falcon.HTTPForbidden("Forbidden", "Remote address %s not whitelisted" % req.context.get("remote_addr"))
else:
if req.context.get("remote_addr") != ip_address(inner_address):
raise falcon.HTTPForbidden("Forbidden", "Remote address %s mismatch" % req.context.get("remote_addr"))
else:
return func(self, req, resp, cn, *args, **kwargs)
return wrapped
示例12: test_get_list_mutate
# 需要导入模块: from asn1crypto import pem [as 别名]
# 或者: from asn1crypto.pem import unarmor [as 别名]
def test_get_list_mutate(self):
trust_list.clear_cache()
certs = trust_list.get_list()
certs2 = trust_list.get_list()
with open(digicert_ca_path, 'rb') as f:
_, _, digicert_ca_bytes = pem.unarmor(f.read())
digicert_ca_cert = x509.Certificate.load(digicert_ca_bytes)
certs.append(digicert_ca_cert)
self.assertNotEqual(certs2, certs)
示例13: read_cert_bundle
# 需要导入模块: from asn1crypto import pem [as 别名]
# 或者: from asn1crypto.pem import unarmor [as 别名]
def read_cert_bundle(self, ca_bundle_file, storage=None):
"""Reads a certificate file including certificates in PEM format."""
if storage is None:
storage = SnowflakeOCSP.ROOT_CERTIFICATES_DICT
logger.debug('reading certificate bundle: %s', ca_bundle_file)
with open(ca_bundle_file, 'rb') as all_certs:
# don't lock storage
from asn1crypto import pem
pem_certs = pem.unarmor(all_certs.read(), multiple=True)
for type_name, _, der_bytes in pem_certs:
if type_name == 'CERTIFICATE':
crt = Certificate.load(der_bytes)
storage[crt.subject.sha256] = crt
示例14: _grab_crl
# 需要导入模块: from asn1crypto import pem [as 别名]
# 或者: from asn1crypto.pem import unarmor [as 别名]
def _grab_crl(user_agent, url, timeout):
"""
Fetches a CRL and parses it
:param user_agent:
A unicode string of the user agent to use when fetching the URL
:param url:
A unicode string of the URL to fetch the CRL from
:param timeout:
The number of seconds after which an HTTP request should timeout
:return:
An asn1crypto.crl.CertificateList object
"""
if sys.version_info < (3,):
url = util.iri_to_uri(url)
request = Request(url)
request.add_header(b'Accept', b'application/pkix-crl')
request.add_header(b'User-Agent', user_agent.encode('iso-8859-1'))
response = urlopen(request, None, timeout)
data = response.read()
if pem.detect(data):
_, _, data = pem.unarmor(data)
return crl.CertificateList.load(data)
示例15: _validate_unarmor
# 需要导入模块: from asn1crypto import pem [as 别名]
# 或者: from asn1crypto.pem import unarmor [as 别名]
def _validate_unarmor(self, certs, var_name):
"""
Takes a list of byte strings or asn1crypto.x509.Certificates objects,
validates and loads them while unarmoring any PEM-encoded contents
:param certs:
A list of byte strings or asn1crypto.x509.Certificate objects
:param var_name:
A unicode variable name to use in any TypeError exceptions
:return:
A list of asn1crypto.x509.Certificate objects
"""
output = []
for cert in certs:
if isinstance(cert, x509.Certificate):
output.append(cert)
else:
if not isinstance(cert, byte_cls):
raise TypeError(pretty_message(
'''
%s must contain only byte strings or
asn1crypto.x509.Certificate objects, not %s
''',
var_name,
type_name(cert)
))
if pem.detect(cert):
_, _, cert = pem.unarmor(cert)
output.append(x509.Certificate.load(cert))
return output