本文整理匯總了Python中cryptography.x509.Certificate方法的典型用法代碼示例。如果您正苦於以下問題:Python x509.Certificate方法的具體用法?Python x509.Certificate怎麽用?Python x509.Certificate使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類cryptography.x509
的用法示例。
在下文中一共展示了x509.Certificate方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: get_distrust_timeline
# 需要導入模塊: from cryptography import x509 [as 別名]
# 或者: from cryptography.x509 import Certificate [as 別名]
def get_distrust_timeline(
cls, verified_certificate_chain: List[Certificate]
) -> Optional[SymantecDistrustTimelineEnum]:
has_whitelisted_cert = False
has_blacklisted_cert = False
# Is there a Symantec root certificate in the chain?
for certificate in verified_certificate_chain:
key_hash = binascii.hexlify(get_public_key_sha256(certificate)).decode("ascii")
if key_hash in cls._CA_KEYS_BLACKLIST:
has_blacklisted_cert = True
if key_hash in cls._CA_KEYS_WHITELIST:
has_whitelisted_cert = True
distrust_enum = None
if has_blacklisted_cert and not has_whitelisted_cert:
leaf_cert = verified_certificate_chain[0]
if leaf_cert.not_valid_before < datetime(year=2016, month=6, day=1):
distrust_enum = SymantecDistrustTimelineEnum.MARCH_2018
else:
distrust_enum = SymantecDistrustTimelineEnum.SEPTEMBER_2018
return distrust_enum
示例2: extract_dns_subject_alternative_names
# 需要導入模塊: from cryptography import x509 [as 別名]
# 或者: from cryptography.x509 import Certificate [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
示例3: _verify_certificate_chain
# 需要導入模塊: from cryptography import x509 [as 別名]
# 或者: from cryptography.x509 import Certificate [as 別名]
def _verify_certificate_chain(server_certificate_chain: List[str], trust_store: TrustStore) -> PathValidationResult:
server_chain_as_x509s = [X509(pem_cert) for pem_cert in server_certificate_chain]
chain_verifier = CertificateChainVerifier.from_file(trust_store.path)
verified_chain: Optional[List[Certificate]]
try:
openssl_verify_str = None
verified_chain_as_509s = chain_verifier.verify(server_chain_as_x509s)
verified_chain = [
load_pem_x509_certificate(x509_cert.as_pem().encode("ascii"), backend=default_backend())
for x509_cert in verified_chain_as_509s
]
except CertificateChainVerificationFailed as e:
verified_chain = None
openssl_verify_str = e.openssl_error_string
return PathValidationResult(
trust_store=trust_store, verified_certificate_chain=verified_chain, openssl_error_string=openssl_verify_str
)
示例4: from_cryptography
# 需要導入模塊: from cryptography import x509 [as 別名]
# 或者: from cryptography.x509 import Certificate [as 別名]
def from_cryptography(cls, crypto_cert):
"""
Construct based on a ``cryptography`` *crypto_cert*.
:param crypto_key: A ``cryptography`` X.509 certificate.
:type crypto_key: ``cryptography.x509.Certificate``
:rtype: X509
.. versionadded:: 17.1.0
"""
if not isinstance(crypto_cert, x509.Certificate):
raise TypeError("Must be a certificate")
cert = cls()
cert._x509 = crypto_cert._x509
return cert
示例5: ca_trust_payload_from_configuration
# 需要導入模塊: from cryptography import x509 [as 別名]
# 或者: from cryptography.x509 import Certificate [as 別名]
def ca_trust_payload_from_configuration() -> PEMCertificatePayload:
"""Create a CA payload with the PEM representation of the Certificate Authority used by this instance.
You need to check whether the app config contains 'CA_CERTIFICATE' before invoking this.
"""
try:
org = db.session.query(Organization).one()
except NoResultFound:
abort(500, 'No organization is configured, cannot generate enrollment profile.')
except MultipleResultsFound:
abort(500, 'Multiple organizations, backup your database and start again')
with open(current_app.config['CA_CERTIFICATE'], 'rb') as fd:
pem_data = fd.read()
pem_payload = PEMCertificatePayload(
uuid=uuid4(),
identifier=org.payload_prefix + '.ca',
payload_content=pem_data,
display_name='Certificate Authority',
description='Required for your device to trust the server',
type='com.apple.security.root',
version=1
)
return pem_payload
示例6: ssl_trust_payload_from_configuration
# 需要導入模塊: from cryptography import x509 [as 別名]
# 或者: from cryptography.x509 import Certificate [as 別名]
def ssl_trust_payload_from_configuration() -> PEMCertificatePayload:
"""Generate a PEM certificate payload in order to trust this host.
"""
try:
org = db.session.query(Organization).one()
except NoResultFound:
abort(500, 'No organization is configured, cannot generate enrollment profile.')
except MultipleResultsFound:
abort(500, 'Multiple organizations, backup your database and start again')
basepath = os.path.dirname(__file__)
certpath = os.path.join(basepath, current_app.config['SSL_CERTIFICATE'])
with open(certpath, 'rb') as fd:
pem_payload = PEMCertificatePayload(
uuid=uuid4(),
identifier=org.payload_prefix + '.ssl',
payload_content=fd.read(),
display_name='Web Server Certificate',
description='Required for your device to trust the server',
type='com.apple.security.pkcs1',
version=1
)
return pem_payload
示例7: from_crypto_type
# 需要導入模塊: from cryptography import x509 [as 別名]
# 或者: from cryptography.x509 import Certificate [as 別名]
def from_crypto_type(cls, certificate: x509.Certificate, certtype: CertificateType):
# type: (certtype, x509.Certificate, CertificateType) -> Certificate
m = cls()
m.serial = certificate.serial_number
m.pem_data = certificate.public_bytes(serialization.Encoding.PEM)
m.not_after = certificate.not_valid_after
m.not_before = certificate.not_valid_before
m.fingerprint = certificate.fingerprint(hashes.SHA256())
m.discriminator = certtype.value
m.serial = str(certificate.serial_number)
subject: x509.Name = certificate.subject
cns = subject.get_attributes_for_oid(NameOID.COMMON_NAME)
if cns is not None:
m.x509_cn = cns[0].value
return m
示例8: from_crypto
# 需要導入模塊: from cryptography import x509 [as 別名]
# 或者: from cryptography.x509 import Certificate [as 別名]
def from_crypto(cls, csr: x509.CertificateSigningRequest):
# type: (type, x509.CertificateSigningRequest, CertificateType) -> Certificate
m = cls()
m.pem_data = csr.public_bytes(serialization.Encoding.PEM)
m.not_before = datetime.datetime.utcnow()
m.not_after = datetime.datetime.utcnow() + datetime.timedelta(days=700)
h = hashes.Hash(hashes.SHA256(), default_backend())
h.update(m.pem_data)
m.fingerprint = h.finalize()
m.discriminator = CertificateType.CSR.value
subject: x509.Name = csr.subject
cns = subject.get_attributes_for_oid(NameOID.COMMON_NAME)
if cns is not None:
m.x509_cn = cns[0].value
return m
示例9: anchor_certs
# 需要導入模塊: from cryptography import x509 [as 別名]
# 或者: from cryptography.x509 import Certificate [as 別名]
def anchor_certs():
"""Download a list of certificates to trust the MDM
The response is a JSON array of base64 encoded DER certs as described in the DEP profile creation documentation."""
anchors = []
if 'CA_CERTIFICATE' in current_app.config:
with open(current_app.config['CA_CERTIFICATE'], 'rb') as fd:
pem_data = fd.read()
c: x509.Certificate = x509.load_pem_x509_certificate(pem_data, backend=default_backend())
der = c.public_bytes(Encoding.DER)
anchors.append(urlsafe_b64encode(der))
if 'SSL_CERTIFICATE' in current_app.config:
with open(current_app.config['SSL_CERTIFICATE'], 'rb') as fd:
pem_data = fd.read()
c: x509.Certificate = x509.load_pem_x509_certificate(pem_data, backend=default_backend())
der = c.public_bytes(Encoding.DER)
anchors.append(urlsafe_b64encode(der))
return jsonify(anchors)
示例10: certificate
# 需要導入模塊: from cryptography import x509 [as 別名]
# 或者: from cryptography.x509 import Certificate [as 別名]
def certificate(private_key: rsa.RSAPrivateKey) -> x509.Certificate:
b = x509.CertificateBuilder()
name = x509.Name([
x509.NameAttribute(NameOID.COUNTRY_NAME, u"US"),
x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u"CA"),
x509.NameAttribute(NameOID.LOCALITY_NAME, u"San Francisco"),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"Commandment"),
x509.NameAttribute(NameOID.COMMON_NAME, u"CA-CERTIFICATE"),
])
cer = b.subject_name(name).issuer_name(name).public_key(
private_key.public_key()
).serial_number(1).not_valid_before(
datetime.datetime.utcnow()
).not_valid_after(
datetime.datetime.utcnow() + datetime.timedelta(days=10)
).add_extension(
x509.BasicConstraints(ca=False, path_length=None), True
).sign(private_key, hashes.SHA256(), default_backend())
return cer
示例11: assertKey
# 需要導入模塊: from cryptography import x509 [as 別名]
# 或者: from cryptography.x509 import Certificate [as 別名]
def assertKey(self, ca, key_type=RSAPrivateKey, password=None):
priv_path = 'ocsp/%s.key' % ca.serial
cert_path = 'ocsp/%s.pem' % ca.serial
self.assertTrue(ca_storage.exists(priv_path))
self.assertTrue(ca_storage.exists(cert_path))
with ca_storage.open(priv_path, 'rb') as stream:
priv = stream.read()
priv = load_pem_private_key(priv, password, default_backend())
self.assertIsInstance(priv, key_type)
with ca_storage.open(cert_path, 'rb') as stream:
cert = stream.read()
cert = x509.load_pem_x509_certificate(cert, default_backend())
self.assertIsInstance(cert, x509.Certificate)
db_cert = Certificate.objects.exclude(pk__in=self.existing_certs).first()
self.assertEqual(db_cert.authority_information_access.ocsp, [])
return priv, cert
示例12: _get_basic_certificate_text
# 需要導入模塊: from cryptography import x509 [as 別名]
# 或者: from cryptography.x509 import Certificate [as 別名]
def _get_basic_certificate_text(cls, certificate: Certificate) -> List[str]:
text_output = [
cls._format_field(
"SHA1 Fingerprint:", binascii.hexlify(certificate.fingerprint(hashes.SHA1())).decode("ascii")
),
cls._format_field("Common Name:", _get_name_as_short_text(certificate.subject)),
cls._format_field("Issuer:", _get_name_as_short_text(certificate.issuer)),
cls._format_field("Serial Number:", str(certificate.serial_number)),
cls._format_field("Not Before:", certificate.not_valid_before.date().isoformat()),
cls._format_field("Not After:", certificate.not_valid_after.date().isoformat()),
cls._format_field("Public Key Algorithm:", certificate.public_key().__class__.__name__),
]
if certificate.signature_hash_algorithm:
# The signature_hash_algorithm can be None if signature did not use separate hash (ED25519, ED448)
# https://cryptography.io/en/latest/x509/reference/#cryptography.x509.Certificate.signature_hash_algorithm
text_output.append(cls._format_field("Signature Algorithm:", certificate.signature_hash_algorithm.name))
public_key = certificate.public_key()
if isinstance(public_key, EllipticCurvePublicKey):
text_output.append(cls._format_field("Key Size:", str(public_key.curve.key_size)))
text_output.append(cls._format_field("Curve:", str(public_key.curve.name)))
elif isinstance(public_key, RSAPublicKey):
text_output.append(cls._format_field("Key Size:", str(public_key.key_size)))
text_output.append(cls._format_field("Exponent:", str(public_key.public_numbers().e))) # type: ignore
else:
# DSA Key? https://github.com/nabla-c0d3/sslyze/issues/314
pass
try:
# Print the SAN extension if there's one
text_output.append(
cls._format_field(
"DNS Subject Alternative Names:", str(extract_dns_subject_alternative_names(certificate))
)
)
except KeyError:
pass
return text_output
示例13: _monkeypatch_to_fix_certificate_asdict
# 需要導入模塊: from cryptography import x509 [as 別名]
# 或者: from cryptography.x509 import Certificate [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
示例14: verified_certificate_chain
# 需要導入模塊: from cryptography import x509 [as 別名]
# 或者: from cryptography.x509 import Certificate [as 別名]
def verified_certificate_chain(self) -> Optional[List[Certificate]]:
"""Get one of the verified certificate chains if one was successfully built using any of the trust stores.
"""
for path_result in self.path_validation_results:
if path_result.was_validation_successful:
return path_result.verified_certificate_chain
return None
示例15: _certificate_matches_hostname
# 需要導入模塊: from cryptography import x509 [as 別名]
# 或者: from cryptography.x509 import Certificate [as 別名]
def _certificate_matches_hostname(certificate: Certificate, server_hostname: str) -> bool:
"""Verify that the certificate was issued for the given hostname.
"""
# Extract the names from the certificate to create the properly-formatted dictionary
certificate_names = {
"subject": (tuple([("commonName", name) for name in get_common_names(certificate.subject)]),),
"subjectAltName": tuple([("DNS", name) for name in extract_dns_subject_alternative_names(certificate)]),
}
# CertificateError is raised on failure
try:
match_hostname(certificate_names, server_hostname) # type: ignore
return True
except CertificateError:
return False