本文整理匯總了Python中cryptography.x509.load_pem_x509_certificate方法的典型用法代碼示例。如果您正苦於以下問題:Python x509.load_pem_x509_certificate方法的具體用法?Python x509.load_pem_x509_certificate怎麽用?Python x509.load_pem_x509_certificate使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類cryptography.x509
的用法示例。
在下文中一共展示了x509.load_pem_x509_certificate方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: setup_method
# 需要導入模塊: from cryptography import x509 [as 別名]
# 或者: from cryptography.x509 import load_pem_x509_certificate [as 別名]
def setup_method(self, method):
super(TestCustodiaIPACertRequests, self).setup_method(method)
cert = x509.load_pem_x509_certificate(CERT_PEM, default_backend())
cert_der = cert.public_bytes(serialization.Encoding.DER)
cert_stripped = base64.b64encode(cert_der)
ca = x509.load_pem_x509_certificate(CA_PEM, default_backend())
ca_der = ca.public_bytes(serialization.Encoding.DER)
self.m_api.Command.cert_request.return_value = {
u'result': {
u'subject': 'dummy subject',
u'request_id': 1,
u'serial_number': 1,
u'certificate': cert_stripped,
u'certificate_chain': (
cert_der,
ca_der,
)
}
}
示例2: create
# 需要導入模塊: from cryptography import x509 [as 別名]
# 或者: from cryptography.x509 import load_pem_x509_certificate [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)
示例3: create
# 需要導入模塊: from cryptography import x509 [as 別名]
# 或者: from cryptography.x509 import load_pem_x509_certificate [as 別名]
def create(vek, keySizeBytes, certificatePath):
#print("VEK: " + str(binascii.hexlify(vek)))
publicKeyPem = open(certificatePath).read()
publicKey = RSA.importKey(publicKeyPem)
# Convert from PEM to DER
lines = publicKeyPem.replace(" ", '').split()
publicKeyDer = binascii.a2b_base64(''.join(lines[1:-1]))
cert = x509.load_pem_x509_certificate(SmartStr(publicKeyPem), default_backend())
subjectName = cert.subject.rfc4514_string()
serial = cert.serial_number
cipher = PKCS1_OAEP.new(key=publicKey, hashAlgo=SHA256, mgfunc=lambda x, y: pss.MGF1(x, y, SHA1))
wrapped_key = cipher.encrypt(vek)
#print("WrappedKey: " + str(binascii.hexlify(wrapped_key)))
return CertEncryptedKeyBag(subjectName, serial, keySizeBytes, wrapped_key)
示例4: validate_ca_cert
# 需要導入模塊: from cryptography import x509 [as 別名]
# 或者: from cryptography.x509 import load_pem_x509_certificate [as 別名]
def validate_ca_cert(self, ignored):
expected = self._get_expected_ca_cert_fingerprint()
algo, expectedfp = expected.split(':')
expectedfp = expectedfp.replace(' ', '')
backend = default_backend()
with open(self._get_ca_cert_path(), 'r') as f:
certstr = f.read()
cert = load_pem_x509_certificate(certstr, backend)
hasher = getattr(hashes, algo)()
fpbytes = cert.fingerprint(hasher)
fp = binascii.hexlify(fpbytes)
if fp != expectedfp:
os.unlink(self._get_ca_cert_path())
self.log.error("Fingerprint of CA cert doesn't match: %s <-> %s"
% (fp, expectedfp))
raise NetworkError("The provider's CA fingerprint doesn't match")
示例5: test_generate_cert_key_pair
# 需要導入模塊: from cryptography import x509 [as 別名]
# 或者: from cryptography.x509 import load_pem_x509_certificate [as 別名]
def test_generate_cert_key_pair(self):
cn = 'testCN'
bit_length = 512
# Attempt to generate a cert/key pair
cert_object = self.cert_generator.generate_cert_key_pair(
cn=cn,
validity=2 * 365 * 24 * 60 * 60,
bit_length=bit_length,
passphrase=self.ca_private_key_passphrase,
ca_cert=self.ca_certificate,
ca_key=self.ca_private_key,
ca_key_pass=self.ca_private_key_passphrase
)
# Validate that the cert and key are loadable
cert = x509.load_pem_x509_certificate(
data=cert_object.certificate, backend=backends.default_backend())
self.assertIsNotNone(cert)
key = serialization.load_pem_private_key(
data=cert_object.private_key,
password=cert_object.private_key_passphrase,
backend=backends.default_backend())
self.assertIsNotNone(key)
示例6: pem_certificate_upload
# 需要導入模塊: from cryptography import x509 [as 別名]
# 或者: from cryptography.x509 import load_pem_x509_certificate [as 別名]
def pem_certificate_upload(f):
"""Parse PEM formatted certificate in request data
TODO: form field name option
"""
@wraps(f)
def decorator(*args, **kwargs):
try:
certificate_data = request.files['file'].read()
g.certificate = x509.load_pem_x509_certificate(certificate_data, backend=default_backend())
except UnsupportedAlgorithm as e:
current_app.logger.info('could not parse PEM certificate data')
abort(400, 'invalid input data')
return f(*args, **kwargs)
return decorator
示例7: anchor_certs
# 需要導入模塊: from cryptography import x509 [as 別名]
# 或者: from cryptography.x509 import load_pem_x509_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)
示例8: add_valid_from
# 需要導入模塊: from cryptography import x509 [as 別名]
# 或者: from cryptography.x509 import load_pem_x509_certificate [as 別名]
def add_valid_from(apps, schema_editor):
Certificate = apps.get_model('django_ca', 'Certificate')
for cert in Certificate.objects.all():
backend = default_backend()
pem = x509.load_pem_x509_certificate(force_bytes(cert.pub), backend)
valid_from = pem.not_valid_before
if settings.USE_TZ:
valid_from = timezone.make_aware(valid_from)
cert.valid_from = valid_from
cert.save()
CertificateAuthority = apps.get_model('django_ca', 'CertificateAuthority')
for cert in CertificateAuthority.objects.all():
backend = default_backend()
pem = x509.load_pem_x509_certificate(force_bytes(cert.pub), backend)
valid_from = pem.not_valid_before
if settings.USE_TZ:
valid_from = timezone.make_aware(valid_from)
cert.valid_from = valid_from
cert.save()
示例9: handle
# 需要導入模塊: from cryptography import x509 [as 別名]
# 或者: from cryptography.x509 import load_pem_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()
示例10: _load_pub
# 需要導入模塊: from cryptography import x509 [as 別名]
# 或者: from cryptography.x509 import load_pem_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
示例11: _get_public_tls_parameters
# 需要導入模塊: from cryptography import x509 [as 別名]
# 或者: from cryptography.x509 import load_pem_x509_certificate [as 別名]
def _get_public_tls_parameters(service_certificate_path):
with open(service_certificate_path, "rb") as pem_file:
pem_data = pem_file.read()
cert = x509.load_pem_x509_certificate(pem_data, default_backend())
private_key = serialization.load_pem_private_key(
pem_data,
password=None,
backend=default_backend())
key_pem = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption())
cert_pem = cert.public_bytes(serialization.Encoding.PEM)
return {
'SSLCertificate': cert_pem,
'SSLKey': key_pem
}
示例12: _scan_a_cert
# 需要導入模塊: from cryptography import x509 [as 別名]
# 或者: from cryptography.x509 import load_pem_x509_certificate [as 別名]
def _scan_a_cert(id, cert_path, key_path, assigns, is_acme=False):
with open(cert_path, "rb") as f:
crt = x509.load_pem_x509_certificate(f.read(), default_backend())
with open(key_path, "rb") as f:
key = serialization.load_pem_private_key(
f.read(),
password=None,
backend=default_backend()
)
sha1 = binascii.hexlify(crt.fingerprint(hashes.SHA1())).decode()
md5 = binascii.hexlify(crt.fingerprint(hashes.MD5())).decode()
sha1 = ":".join([sha1[i:i+2].upper() for i in range(0, len(sha1), 2)])
md5 = ":".join([md5[i:i+2].upper() for i in range(0, len(md5), 2)])
kt = "RSA" if isinstance(key.public_key(), rsa.RSAPublicKey) else "DSA"
common_name = crt.subject.get_attributes_for_oid(NameOID.COMMON_NAME)
return Certificate(
id=id, cert_path=cert_path, key_path=key_path, keytype=kt,
keylength=key.key_size, domain=common_name[0].value,
assigns=assigns.get(id, []), expiry=crt.not_valid_after, sha1=sha1,
md5=md5, is_acme=is_acme)
示例13: get_certificate
# 需要導入模塊: from cryptography import x509 [as 別名]
# 或者: from cryptography.x509 import load_pem_x509_certificate [as 別名]
def get_certificate(self, kid):
# retrieve keys from jwks_url
resp = self.request(self.jwks_url(), method='GET')
resp.raise_for_status()
# find the proper key for the kid
for key in resp.json()['keys']:
if key['kid'] == kid:
x5c = key['x5c'][0]
break
else:
raise DecodeError('Cannot find kid={}'.format(kid))
certificate = '-----BEGIN CERTIFICATE-----\n' \
'{}\n' \
'-----END CERTIFICATE-----'.format(x5c)
return load_pem_x509_certificate(certificate.encode(),
default_backend())
示例14: __init__
# 需要導入模塊: from cryptography import x509 [as 別名]
# 或者: from cryptography.x509 import load_pem_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"
示例15: fqdns_from_certificate
# 需要導入模塊: from cryptography import x509 [as 別名]
# 或者: from cryptography.x509 import load_pem_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))