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