本文整理汇总了Python中cryptography.hazmat.primitives.serialization.Encoding.DER属性的典型用法代码示例。如果您正苦于以下问题:Python Encoding.DER属性的具体用法?Python Encoding.DER怎么用?Python Encoding.DER使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类cryptography.hazmat.primitives.serialization.Encoding
的用法示例。
在下文中一共展示了Encoding.DER属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: anchor_certs
# 需要导入模块: from cryptography.hazmat.primitives.serialization import Encoding [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization.Encoding import DER [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)
示例2: get
# 需要导入模块: from cryptography.hazmat.primitives.serialization import Encoding [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization.Encoding import DER [as 别名]
def get(self, request, serial):
encoding = parse_encoding(request.GET.get('encoding', self.type))
cache_key = get_crl_cache_key(serial, algorithm=self.digest, encoding=encoding, scope=self.scope)
crl = cache.get(cache_key)
if crl is None:
ca = self.get_object()
encoding = parse_encoding(self.type)
crl = ca.get_crl(expires=self.expires, algorithm=self.digest, password=self.password,
scope=self.scope)
crl = crl.public_bytes(encoding)
cache.set(cache_key, crl, self.expires)
content_type = self.content_type
if content_type is None:
if self.type == Encoding.DER:
content_type = 'application/pkix-crl'
elif self.type == Encoding.PEM:
content_type = 'text/plain'
else: # pragma: no cover
# DER/PEM are all known encoding types, so this shouldn't happen
return HttpResponseServerError()
return HttpResponse(crl, content_type=content_type)
示例3: handle
# 需要导入模块: from cryptography.hazmat.primitives.serialization import Encoding [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization.Encoding import DER [as 别名]
def handle(self, cert, path, **options):
if options['bundle'] and options['format'] == Encoding.DER:
raise CommandError('Cannot dump bundle when using DER format.')
if options['bundle']:
certs = cert.bundle
else:
certs = [cert]
data = b''.join([c.dump_certificate(options['format']) for c in certs])
if path == '-':
self.stdout.write(data, ending=b'')
else:
try:
with open(path, 'wb') as stream:
stream.write(data)
except IOError as e:
raise CommandError(e)
示例4: handle
# 需要导入模块: from cryptography.hazmat.primitives.serialization import Encoding [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization.Encoding import DER [as 别名]
def handle(self, ca, path, **options):
if options['bundle'] and options['format'] == Encoding.DER:
raise CommandError('Cannot dump bundle when using DER format.')
if options['bundle']:
certs = ca.bundle
else:
certs = [ca]
data = b''.join([c.dump_certificate(options['format']) for c in certs])
if path == '-':
self.stdout.write(data, ending=b'')
else:
try:
with open(path, 'wb') as stream:
stream.write(data)
except IOError as e:
raise CommandError(e)
示例5: test_basic
# 需要导入模块: from cryptography.hazmat.primitives.serialization import Encoding [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization.Encoding import DER [as 别名]
def test_basic(self):
hash_cls = hashes.SHA512
enc_cls = Encoding.DER
stdout, stderr = self.cmd('cache_crls')
self.assertEqual(stdout, '')
self.assertEqual(stderr, '')
for name, ca in self.cas.items():
key = get_crl_cache_key(ca.serial, hash_cls, enc_cls, 'ca')
crl = x509.load_der_x509_crl(cache.get(key), default_backend())
self.assertIsNotNone(crl)
self.assertIsInstance(crl.signature_hash_algorithm, hash_cls)
key = get_crl_cache_key(ca.serial, hash_cls, enc_cls, 'user')
crl = x509.load_der_x509_crl(cache.get(key), default_backend())
self.assertIsNotNone(crl)
示例6: test_der
# 需要导入模块: from cryptography.hazmat.primitives.serialization import Encoding [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization.Encoding import DER [as 别名]
def test_der(self):
cert = self.certs['child-cert']
stdout, stderr = self.cmd('view_cert', cert.serial, format=Encoding.DER,
stdout=BytesIO(), stderr=BytesIO())
expected = '''Common Name: {cn}
Valid from: {valid_from_short}
Valid until: {valid_until_short}
Status: Valid
SubjectAlternativeName{subject_alternative_name_critical}:
* {subject_alternative_name[0]}
Watchers:
Digest:
md5: {md5}
sha1: {sha1}
sha256: {sha256}
sha512: {sha512}
HPKP pin: {hpkp}
'''.format(**self.get_cert_context('child-cert'))
expected = force_bytes(expected) + certs['child-cert']['pub']['der'] + b'\n'
self.assertEqual(stdout, expected)
self.assertEqual(stderr, b'')
示例7: test_basic
# 需要导入模块: from cryptography.hazmat.primitives.serialization import Encoding [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization.Encoding import DER [as 别名]
def test_basic(self):
# test the default view
idp = self.get_idp(full_name=self.get_idp_full_name(self.ca), only_contains_user_certs=True)
response = self.client.get(reverse('default', kwargs={'serial': self.ca.serial}))
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/pkix-crl')
self.assertCRL(response.content, encoding=Encoding.DER, expires=600, idp=idp)
# revoke a certificate
cert = self.certs['child-cert']
cert.revoke()
# fetch again - we should see a cached response
response = self.client.get(reverse('default', kwargs={'serial': self.ca.serial}))
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/pkix-crl')
self.assertCRL(response.content, encoding=Encoding.DER, expires=600, idp=idp)
# clear the cache and fetch again
cache.clear()
response = self.client.get(reverse('default', kwargs={'serial': self.ca.serial}))
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/pkix-crl')
self.assertCRL(response.content, encoding=Encoding.DER, expires=600, idp=idp, certs=[cert],
crl_number=1)
示例8: calculate_public_key_fingerprint
# 需要导入模块: from cryptography.hazmat.primitives.serialization import Encoding [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization.Encoding import DER [as 别名]
def calculate_public_key_fingerprint(self, private_key: Text) -> Text:
"""
Given a private key in pem format, return the public key fingerprint
:param private_key: private key string
:return: public key fingerprint
"""
try:
private_key = load_pem_private_key(private_key.encode(), None, default_backend())
except (ValueError, UnsupportedAlgorithm) as e:
raise IngestClientError(
code=ERR_INVALID_PRIVATE_KEY,
message='Invalid private key. {}'.format(e))
# get the raw bytes of public key
public_key_raw = private_key.public_key().public_bytes(Encoding.DER, PublicFormat.SubjectPublicKeyInfo)
# take sha256 on raw bytes and then do base64 encode
sha256hash = hashlib.sha256()
sha256hash.update(public_key_raw)
public_key_fp = 'SHA256:' + base64.b64encode(sha256hash.digest()).decode('utf-8')
logger.info("Public key fingerprint is %s", public_key_fp)
return public_key_fp
示例9: get_public_key_sha256
# 需要导入模块: from cryptography.hazmat.primitives.serialization import Encoding [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization.Encoding import DER [as 别名]
def get_public_key_sha256(certificate: x509.Certificate) -> bytes:
pub_bytes = certificate.public_key().public_bytes(encoding=Encoding.DER, format=PublicFormat.SubjectPublicKeyInfo)
digest = sha256(pub_bytes).digest()
return digest
示例10: authenticate
# 需要导入模块: from cryptography.hazmat.primitives.serialization import Encoding [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization.Encoding import DER [as 别名]
def authenticate(
self, authenticator, service_name, account, user, password):
account = account.upper()
user = user.upper()
now = datetime.utcnow()
try:
private_key = load_der_private_key(data=self._private_key, password=None, backend=default_backend())
except Exception as e:
raise ProgrammingError(
msg='Failed to load private key: {}\nPlease provide a valid unencrypted rsa private '
'key in DER format as bytes object'.format(str(e)),
errno=ER_INVALID_PRIVATE_KEY
)
if not isinstance(private_key, RSAPrivateKey):
raise ProgrammingError(
msg='Private key type ({}) not supported.\nPlease provide a valid rsa private '
'key in DER format as bytes object'.format(private_key.__class__.__name__),
errno=ER_INVALID_PRIVATE_KEY
)
public_key_fp = self.calculate_public_key_fingerprint(private_key)
self._jwt_token_exp = now + self.LIFETIME
payload = {
self.ISSUER: "{}.{}.{}".format(account, user, public_key_fp),
self.SUBJECT: "{}.{}".format(account, user),
self.ISSUE_TIME: now,
self.EXPIRE_TIME: self._jwt_token_exp
}
self._jwt_token = jwt.encode(payload, private_key,
algorithm=self.ALGORITHM).decode('utf-8')
return self._jwt_token
示例11: calculate_public_key_fingerprint
# 需要导入模块: from cryptography.hazmat.primitives.serialization import Encoding [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization.Encoding import DER [as 别名]
def calculate_public_key_fingerprint(private_key):
# get public key bytes
public_key_der = private_key.public_key().public_bytes(Encoding.DER, PublicFormat.SubjectPublicKeyInfo)
# take sha256 on raw bytes and then do base64 encode
sha256hash = hashlib.sha256()
sha256hash.update(public_key_der)
public_key_fp = 'SHA256:' + base64.b64encode(sha256hash.digest()).decode('utf-8')
logger.debug("Public key fingerprint is %s", public_key_fp)
return public_key_fp
示例12: profile
# 需要导入模块: from cryptography.hazmat.primitives.serialization import Encoding [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization.Encoding import DER [as 别名]
def profile():
"""Accept a CMS Signed DER encoded XML data containing device information.
This starts the DEP enrollment process. The absolute url to this endpoint should be present in the DEP profile's
enrollment URL.
The signed data contains a plist with the following keys:
:UDID: The device’s UDID.
:SERIAL: The device's Serial Number.
:PRODUCT: The device’s product type: e.g., iPhone5,1.
:VERSION: The OS version installed on the device: e.g., 7A182.
:IMEI: The device’s IMEI (if available).
:MEID: The device’s MEID (if available).
:LANGUAGE: The user’s currently-selected language: e.g., en.
See Also:
- `Mobile Device Management Protocol: Request to a Profile URL
<https://developer.apple.com/library/content/documentation/Miscellaneous/Reference/MobileDeviceManagementProtocolRef/4-Profile_Management/ProfileManagement.html#//apple_ref/doc/uid/TP40017387-CH7-SW242>`_.
"""
g.plist_data = plistlib.loads(g.signed_data)
profile = generate_enroll_profile()
schema = ProfileSchema()
result = schema.dump(profile)
plist_data = dumps_none(result.data, skipkeys=True)
return plist_data, 200, {'Content-Type': PROFILE_CONTENT_TYPE}
示例13: create_ssl_context
# 需要导入模块: from cryptography.hazmat.primitives.serialization import Encoding [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization.Encoding import DER [as 别名]
def create_ssl_context(cert_byes, pk_bytes, password=None,
encoding=Encoding.PEM):
"""Create an SSL Context with the supplied cert/password.
:param cert_bytes array of bytes containing the cert encoded
using the method supplied in the ``encoding`` parameter
:param pk_bytes array of bytes containing the private key encoded
using the method supplied in the ``encoding`` parameter
:param password array of bytes containing the passphrase to be used
with the supplied private key. None if unencrypted.
Defaults to None.
:param encoding ``cryptography.hazmat.primitives.serialization.Encoding``
details the encoding method used on the ``cert_bytes`` and
``pk_bytes`` parameters. Can be either PEM or DER.
Defaults to PEM.
"""
backend = default_backend()
cert = None
key = None
if encoding == Encoding.PEM:
cert = x509.load_pem_x509_certificate(cert_byes, backend)
key = load_pem_private_key(pk_bytes, password, backend)
elif encoding == Encoding.DER:
cert = x509.load_der_x509_certificate(cert_byes, backend)
key = load_der_private_key(pk_bytes, password, backend)
else:
raise ValueError('Invalid encoding provided: Must be PEM or DER')
if not (cert and key):
raise ValueError('Cert and key could not be parsed from '
'provided data')
check_cert_dates(cert)
ssl_context = PyOpenSSLContext(PROTOCOL)
ssl_context._ctx.use_certificate(X509.from_cryptography(cert))
ssl_context._ctx.use_privatekey(PKey.from_cryptography_key(key))
return ssl_context
示例14: parse_csr
# 需要导入模块: from cryptography.hazmat.primitives.serialization import Encoding [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization.Encoding import DER [as 别名]
def parse_csr(self, csr, csr_format):
if isinstance(csr, x509.CertificateSigningRequest):
return csr
elif csr_format == Encoding.PEM:
return x509.load_pem_x509_csr(force_bytes(csr), default_backend())
elif csr_format == Encoding.DER:
return x509.load_der_x509_csr(force_bytes(csr), default_backend())
raise ValueError('Unknown CSR format passed: %s' % csr_format)
示例15: fail
# 需要导入模块: from cryptography.hazmat.primitives.serialization import Encoding [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization.Encoding import DER [as 别名]
def fail(self, status=ocsp.OCSPResponseStatus.INTERNAL_ERROR):
return self.http_response(
ocsp.OCSPResponseBuilder.build_unsuccessful(status).public_bytes(Encoding.DER)
)