本文整理汇总了Python中cryptography.x509.ExtensionNotFound方法的典型用法代码示例。如果您正苦于以下问题:Python x509.ExtensionNotFound方法的具体用法?Python x509.ExtensionNotFound怎么用?Python x509.ExtensionNotFound使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cryptography.x509
的用法示例。
在下文中一共展示了x509.ExtensionNotFound方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: extract_dns_subject_alternative_names
# 需要导入模块: from cryptography import x509 [as 别名]
# 或者: from cryptography.x509 import ExtensionNotFound [as 别名]
def extract_dns_subject_alternative_names(certificate: x509.Certificate) -> List[str]:
"""Retrieve all the DNS entries of the Subject Alternative Name extension.
"""
subj_alt_names: List[str] = []
try:
san_ext = certificate.extensions.get_extension_for_oid(ExtensionOID.SUBJECT_ALTERNATIVE_NAME)
san_ext_value = cast(x509.SubjectAlternativeName, san_ext.value)
subj_alt_names = san_ext_value.get_values_for_type(DNSName)
except ExtensionNotFound:
pass
except DuplicateExtension:
# Fix for https://github.com/nabla-c0d3/sslyze/issues/420
# Not sure how browsers behave in this case but having a duplicate extension makes the certificate invalid
# so we just return no SANs (likely to make hostname validation fail, which is fine)
pass
return subj_alt_names
示例2: get_sans_from_csr
# 需要导入模块: from cryptography import x509 [as 别名]
# 或者: from cryptography.x509 import ExtensionNotFound [as 别名]
def get_sans_from_csr(data):
"""
Fetches SubjectAlternativeNames from CSR.
Works with any kind of SubjectAlternativeName
:param data: PEM-encoded string with CSR
:return: List of LemurAPI-compatible subAltNames
"""
sub_alt_names = []
try:
request = x509.load_pem_x509_csr(data.encode("utf-8"), default_backend())
except Exception:
raise ValidationError("CSR presented is not valid.")
try:
alt_names = request.extensions.get_extension_for_class(
x509.SubjectAlternativeName
)
for alt_name in alt_names.value:
sub_alt_names.append(
{"nameType": type(alt_name).__name__, "value": alt_name.value}
)
except x509.ExtensionNotFound:
pass
return sub_alt_names
示例3: test_csr_empty_san
# 需要导入模块: from cryptography import x509 [as 别名]
# 或者: from cryptography.x509 import ExtensionNotFound [as 别名]
def test_csr_empty_san(client):
"""Test that an empty "names" list does not produce a CSR with empty SubjectAltNames extension.
The Lemur UI always submits this extension even when no alt names are defined.
"""
csr_text, pkey = create_csr(
common_name="daniel-san.example.com",
owner="daniel-san@example.com",
key_type="RSA2048",
extensions={"sub_alt_names": {"names": x509.SubjectAlternativeName([])}},
)
csr = x509.load_pem_x509_csr(csr_text.encode("utf-8"), default_backend())
with pytest.raises(x509.ExtensionNotFound):
csr.extensions.get_extension_for_class(x509.SubjectAlternativeName)
示例4: domains
# 需要导入模块: from cryptography import x509 [as 别名]
# 或者: from cryptography.x509 import ExtensionNotFound [as 别名]
def domains(cert):
"""
Attempts to get an domains listed in a certificate.
If 'subjectAltName' extension is not available we simply
return the common name.
:param cert:
:return: List of domains
"""
domains = []
try:
ext = cert.extensions.get_extension_for_oid(x509.OID_SUBJECT_ALTERNATIVE_NAME)
entries = ext.value.get_values_for_type(x509.DNSName)
for entry in entries:
domains.append(entry)
except x509.ExtensionNotFound:
if current_app.config.get("LOG_SSL_SUBJ_ALT_NAME_ERRORS", True):
sentry.captureException()
except Exception as e:
sentry.captureException()
return domains
示例5: precertificate_signed_certificate_timestamps
# 需要导入模块: from cryptography import x509 [as 别名]
# 或者: from cryptography.x509 import ExtensionNotFound [as 别名]
def precertificate_signed_certificate_timestamps(self):
try:
ext = self.x509.extensions.get_extension_for_oid(
ExtensionOID.PRECERT_SIGNED_CERTIFICATE_TIMESTAMPS)
except x509.ExtensionNotFound:
return None
if isinstance(ext.value, x509.UnrecognizedExtension):
# Older versions of OpenSSL (and LibreSSL) cannot parse this extension
# see https://github.com/pyca/cryptography/blob/master/tests/x509/test_x509_ext.py#L4455-L4459
return UnrecognizedExtension(
ext,
name=get_extension_name(ext),
error='Requires OpenSSL 1.1.0f or later')
else: # pragma: only SCT
return PrecertificateSignedCertificateTimestamps(ext)
示例6: test_certs
# 需要导入模块: from cryptography import x509 [as 别名]
# 或者: from cryptography.x509 import ExtensionNotFound [as 别名]
def test_certs(self):
self.load_all_cas()
self.load_all_certs()
for name, cert in list(self.cas.items()) + list(self.certs.items()):
try:
val = cert.x509.extensions.get_extension_for_oid(ExtensionOID.CERTIFICATE_POLICIES).value
except x509.ExtensionNotFound:
continue
for policy in val:
pi = PolicyInformation(policy)
self.assertEqual(pi.for_extension_type, policy)
# pass the serialized value to the constructor and see if it's still the same
pi2 = PolicyInformation(pi.serialize())
self.assertEqual(pi, pi2)
self.assertEqual(pi.serialize(), pi2.serialize())
self.assertEqual(pi2.for_extension_type, policy)
示例7: get_host_names
# 需要导入模块: from cryptography import x509 [as 别名]
# 或者: from cryptography.x509 import ExtensionNotFound [as 别名]
def get_host_names(certificate):
"""Extract the host names from the Pem encoded X509 certificate
:param certificate: A PEM encoded certificate
:returns: A dictionary containing the following keys:
['cn', 'dns_names']
where 'cn' is the CN from the SubjectName of the
certificate, and 'dns_names' is a list of dNSNames
(possibly empty) from the SubjectAltNames of the certificate.
"""
if isinstance(certificate, str):
certificate = certificate.encode('utf-8')
try:
cert = x509.load_pem_x509_certificate(certificate,
backends.default_backend())
cn = cert.subject.get_attributes_for_oid(x509.OID_COMMON_NAME)[0]
host_names = {
'cn': cn.value.lower(),
'dns_names': []
}
try:
ext = cert.extensions.get_extension_for_oid(
x509.OID_SUBJECT_ALTERNATIVE_NAME
)
host_names['dns_names'] = ext.value.get_values_for_type(
x509.DNSName)
except x509.ExtensionNotFound:
LOG.debug("%s extension not found",
x509.OID_SUBJECT_ALTERNATIVE_NAME)
return host_names
except Exception:
LOG.exception('Unreadable Certificate.')
raise exceptions.UnreadableCert
示例8: csr
# 需要导入模块: from cryptography import x509 [as 别名]
# 或者: from cryptography.x509 import ExtensionNotFound [as 别名]
def csr(data):
"""
Determines if the CSR is valid and allowed.
:param data:
:return:
"""
try:
request = x509.load_pem_x509_csr(data.encode("utf-8"), default_backend())
except Exception:
raise ValidationError("CSR presented is not valid.")
# Validate common name and SubjectAltNames
try:
for name in request.subject.get_attributes_for_oid(NameOID.COMMON_NAME):
common_name(name.value)
except ValueError as err:
current_app.logger.info("Error parsing Subject from CSR: %s", err)
raise ValidationError("Invalid Subject value in supplied CSR")
try:
alt_names = request.extensions.get_extension_for_class(
x509.SubjectAlternativeName
)
for name in alt_names.value.get_values_for_type(x509.DNSName):
sensitive_domain(name)
except x509.ExtensionNotFound:
pass
示例9: get_extended_key_usage_from_certificate
# 需要导入模块: from cryptography import x509 [as 别名]
# 或者: from cryptography.x509 import ExtensionNotFound [as 别名]
def get_extended_key_usage_from_certificate(certificate):
"""
Given an X.509 certificate, extract and return the extendedKeyUsage
extension.
"""
try:
return certificate.extensions.get_extension_for_oid(
x509.oid.ExtensionOID.EXTENDED_KEY_USAGE
).value
except x509.ExtensionNotFound:
return None
示例10: is_ca
# 需要导入模块: from cryptography import x509 [as 别名]
# 或者: from cryptography.x509 import ExtensionNotFound [as 别名]
def is_ca(certificate):
# TODO: test self signed if no extensions found
extensions = certificate.extensions
try:
return extensions.get_extension_for_oid(ExtensionOID.BASIC_CONSTRAINTS).value.ca
except x509.ExtensionNotFound:
try:
return extensions.get_extension_for_oid(ExtensionOID.KEY_USAGE).value.key_cert_sign
except x509.ExtensionNotFound:
pass
return False
示例11: get_authority_key_identifier
# 需要导入模块: from cryptography import x509 [as 别名]
# 或者: from cryptography.x509 import ExtensionNotFound [as 别名]
def get_authority_key_identifier(self):
"""Return the AuthorityKeyIdentifier extension used in certificates signed by this CA."""
try:
ski = self.x509.extensions.get_extension_for_class(x509.SubjectKeyIdentifier)
except x509.ExtensionNotFound:
return x509.AuthorityKeyIdentifier.from_issuer_public_key(self.x509.public_key())
else:
return x509.AuthorityKeyIdentifier.from_issuer_subject_key_identifier(ski.value)
示例12: pathlen
# 需要导入模块: from cryptography import x509 [as 别名]
# 或者: from cryptography.x509 import ExtensionNotFound [as 别名]
def pathlen(self):
"""The ``pathlen`` attribute of the ``BasicConstraints`` extension (either an ``int`` or ``None``)."""
try:
ext = self.x509.extensions.get_extension_for_oid(ExtensionOID.BASIC_CONSTRAINTS)
except x509.ExtensionNotFound: # pragma: no cover - extension should always be present
return None
return ext.value.path_length
示例13: test_as_text
# 需要导入模块: from cryptography import x509 [as 别名]
# 或者: from cryptography.x509 import ExtensionNotFound [as 别名]
def test_as_text(self):
self.assertEqual(self.pi1.as_text(), 'Policy Identifier: 2.5.29.32.0\n'
'Policy Qualifiers:\n* text1')
self.assertEqual(self.pi2.as_text(), 'Policy Identifier: 2.5.29.32.0\n'
'Policy Qualifiers:\n'
'* UserNotice:\n'
' * Explicit text: text2')
self.assertEqual(self.pi3.as_text(),
'Policy Identifier: 2.5.29.32.0\n'
'Policy Qualifiers:\n'
'* UserNotice:\n'
' * Reference:\n'
' * Organiziation: text3\n'
' * Notice Numbers: [1]')
self.assertEqual(self.pi4.as_text(),
'Policy Identifier: 2.5.29.32.0\n'
'Policy Qualifiers:\n'
'* text4\n'
'* UserNotice:\n'
' * Explicit text: text5\n'
' * Reference:\n'
' * Organiziation: text6\n'
' * Notice Numbers: [1, 2, 3]')
self.assertEqual(self.pi_empty.as_text(), 'Policy Identifier: None\nNo Policy Qualifiers')
self.load_all_cas()
self.load_all_certs()
for name, cert in list(self.cas.items()) + list(self.certs.items()):
try:
ext = cert.x509.extensions.get_extension_for_oid(ExtensionOID.CERTIFICATE_POLICIES).value
except x509.ExtensionNotFound:
continue
for index, policy in enumerate(ext):
pi = PolicyInformation(policy)
self.assertEqual(pi.as_text(), certs[name]['policy_texts'][index])
示例14: test_get_authority_key_identifier
# 需要导入模块: from cryptography import x509 [as 别名]
# 或者: from cryptography.x509 import ExtensionNotFound [as 别名]
def test_get_authority_key_identifier(self):
for name, ca in self.cas.items():
self.assertEqual(ca.get_authority_key_identifier().key_identifier,
certs[name]['subject_key_identifier'].value)
# All CAs have a subject key identifier, so we mock that this exception is not present
def side_effect(cls):
raise x509.ExtensionNotFound('mocked', x509.SubjectKeyIdentifier.oid)
ca = self.cas['child']
with mock.patch('cryptography.x509.extensions.Extensions.get_extension_for_class',
side_effect=side_effect):
self.assertEqual(ca.get_authority_key_identifier().key_identifier,
certs['child']['subject_key_identifier'].value)
示例15: update_contrib
# 需要导入模块: from cryptography import x509 [as 别名]
# 或者: from cryptography.x509 import ExtensionNotFound [as 别名]
def update_contrib(data, cert, name, filename):
cert_data = {
'name': name,
'cn': cert.cn,
'cat': 'sphinx-contrib',
'pub_filename': filename,
'key_filename': False,
'csr_filename': False,
'valid_from': parsed.not_valid_before.strftime(_timeformat),
'valid_until': parsed.not_valid_after.strftime(_timeformat),
'serial': cert.serial,
'subject': cert.distinguishedName(),
'hpkp': cert.hpkp_pin,
'md5': cert.get_digest('md5'),
'sha1': cert.get_digest('sha1'),
'sha256': cert.get_digest('sha256'),
'sha512': cert.get_digest('sha512'),
}
for ext in cert.extensions:
if isinstance(ext, Extension):
key = OID_TO_EXTENSION[ext.oid].key
cert_data[key] = ext.serialize()
elif isinstance(ext, tuple):
print('### get extension tuple!!!')
key, value = ext
if isinstance(value[1], x509.ObjectIdentifier):
# Currently just some old StartSSL extensions for Netscape (!)
continue
else:
cert_data[key] = value
try:
ext = cert.x509.extensions.get_extension_for_oid(ExtensionOID.CERTIFICATE_POLICIES).value
cert_data['policy_texts'] = [PolicyInformation(p).as_text() for p in ext]
except x509.ExtensionNotFound:
pass
data[name] = cert_data