本文整理汇总了Python中cryptography.hazmat.primitives.serialization.load_pem_private_key方法的典型用法代码示例。如果您正苦于以下问题:Python serialization.load_pem_private_key方法的具体用法?Python serialization.load_pem_private_key怎么用?Python serialization.load_pem_private_key使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cryptography.hazmat.primitives.serialization
的用法示例。
在下文中一共展示了serialization.load_pem_private_key方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: rsa_decrypt
# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import load_pem_private_key [as 别名]
def rsa_decrypt(encrypted_data, pem, password=None):
"""
rsa 解密
:param encrypted_data: 待解密 bytes
:param pem: RSA private key 内容/binary
:param password: RSA private key pass phrase
:return: 解密后的 binary
"""
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
encrypted_data = to_binary(encrypted_data)
pem = to_binary(pem)
private_key = serialization.load_pem_private_key(pem, password, backend=default_backend())
data = private_key.decrypt(
encrypted_data, padding=padding.OAEP(mgf=padding.MGF1(hashes.SHA1()), algorithm=hashes.SHA1(), label=None,),
)
return data
示例2: rsa_signer
# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import load_pem_private_key [as 别名]
def rsa_signer(message):
"""Sign a message with an rsa key pair found on the file system for CloudFront signed urls.
Parameters
----------
message : Type[string]
the message for which we want to compute a signature
Returns
-------
string
The rsa signature
"""
try:
with open(settings.CLOUDFRONT_PRIVATE_KEY_PATH, "rb") as key_file:
private_key = serialization.load_pem_private_key(
key_file.read(), password=None, backend=default_backend()
)
except FileNotFoundError:
raise MissingRSAKey()
# The following line is excluded from bandit security check because cloudfront supports
# only sha1 hash for signed URLs.
return private_key.sign(message, padding.PKCS1v15(), hashes.SHA1()) # nosec
示例3: test_generate_cert_key_pair
# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import load_pem_private_key [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)
示例4: _read_private_key
# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import load_pem_private_key [as 别名]
def _read_private_key(private_key_pem, passphrase=None):
"""Reads a private key PEM block and returns a RSAPrivatekey
:param private_key_pem: The private key PEM block
:param passphrase: Optional passphrase needed to decrypt the private key
:returns: a RSAPrivatekey object
"""
if passphrase and isinstance(passphrase, str):
passphrase = passphrase.encode("utf-8")
if isinstance(private_key_pem, str):
private_key_pem = private_key_pem.encode('utf-8')
try:
return serialization.load_pem_private_key(private_key_pem, passphrase,
backends.default_backend())
except Exception:
LOG.exception("Passphrase required.")
raise exceptions.NeedsPassphrase
示例5: convert_pem_to_der
# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import load_pem_private_key [as 别名]
def convert_pem_to_der(pem_key):
"""
Converts a given key from PEM to DER format.
:param pem_key: PEM-encoded key bytes
:type pem_key: bytearray
:return: DER-encoded key bytes
:rtype: bytearray
"""
first_line = pem_key.decode().split('\n', 1)[0]
is_private = first_line == begin_key.format(private_str)
if is_private:
loaded_key = crypto_serialization.load_pem_private_key(pem_key, backend=crypto_default_backend())
return serialize_key(loaded_key, encoding='DER', return_private=is_private)
else:
loaded_key = crypto_serialization.load_pem_public_key(pem_key, backend=crypto_default_backend())
return loaded_key.public_bytes(encoding=crypto_serialization.Encoding.DER,
format=crypto_serialization.PublicFormat.SubjectPublicKeyInfo)
示例6: __init__
# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import load_pem_private_key [as 别名]
def __init__(self, wrapping_algorithm, wrapping_key, wrapping_key_type, password=None):
"""Prepares initial values."""
self.wrapping_algorithm = wrapping_algorithm
self.wrapping_key_type = wrapping_key_type
if wrapping_key_type is EncryptionKeyType.PRIVATE:
self._wrapping_key = serialization.load_pem_private_key(
data=wrapping_key, password=password, backend=default_backend()
)
elif wrapping_key_type is EncryptionKeyType.PUBLIC:
self._wrapping_key = serialization.load_pem_public_key(data=wrapping_key, backend=default_backend())
elif wrapping_key_type is EncryptionKeyType.SYMMETRIC:
self._wrapping_key = wrapping_key
self._derived_wrapping_key = derive_data_encryption_key(
source_key=self._wrapping_key, algorithm=self.wrapping_algorithm.algorithm, message_id=None
)
else:
raise InvalidDataKeyError("Invalid wrapping_key_type: {}".format(wrapping_key_type))
示例7: _convert_key
# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import load_pem_private_key [as 别名]
def _convert_key(encoding_name, format_name, private_key):
if not encoding_name and not format_name:
return private_key
backend = backends.default_backend()
key_obj = serialization.load_pem_private_key(private_key.encode("utf-8"), None, backend)
if encoding_name.lower() == "pem":
encoding = serialization.Encoding.PEM
elif encoding_name.lower() == "der":
encoding = serialization.Encoding.DER
else:
raise Exception("Unknown key encoding: %s" % encoding_name)
if format_name.lower() == "pkcs1":
format = serialization.PrivateFormat.TraditionalOpenSSL
elif format_name.lower() == "pkcs8":
format = serialization.PrivateFormat.PKCS8
else:
raise Exception("Unknown key format: %s" % format_name)
target_key = key_obj.private_bytes(encoding=encoding, format=format, encryption_algorithm=serialization.NoEncryption())
return target_key.decode("utf-8")
示例8: get_key
# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import load_pem_private_key [as 别名]
def get_key(self):
response = self.ssm.get_parameter(
Name=self.name_from_physical_resource_id(), WithDecryption=True
)
private_key = response["Parameter"]["Value"].encode("ascii")
key = crypto_serialization.load_pem_private_key(
private_key, password=None, backend=crypto_default_backend()
)
private_key = key.private_bytes(
crypto_serialization.Encoding.PEM,
self.key_format,
crypto_serialization.NoEncryption(),
)
public_key = key.public_key().public_bytes(
crypto_serialization.Encoding.OpenSSH,
crypto_serialization.PublicFormat.OpenSSH,
)
return private_key.decode("ascii"), public_key.decode("ascii")
示例9: from_string
# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import load_pem_private_key [as 别名]
def from_string(cls, key, key_id=None):
"""Construct a RSASigner from a private key in PEM format.
Args:
key (Union[bytes, str]): Private key in PEM format.
key_id (str): An optional key id used to identify the private key.
Returns:
google.auth.crypt._cryptography_rsa.RSASigner: The
constructed signer.
Raises:
ValueError: If ``key`` is not ``bytes`` or ``str`` (unicode).
UnicodeDecodeError: If ``key`` is ``bytes`` but cannot be decoded
into a UTF-8 ``str``.
ValueError: If ``cryptography`` "Could not deserialize key data."
"""
key = _helpers.to_bytes(key)
private_key = serialization.load_pem_private_key(
key, password=None, backend=_BACKEND
)
return cls(private_key, key_id=key_id)
示例10: _obtain_private_key
# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import load_pem_private_key [as 别名]
def _obtain_private_key(self, key_identifier, private_key_pem):
""" returns a loaded instance of the given private key either from
cache or from the given private_key_pem.
"""
priv_key = self._private_keys_cache.get(key_identifier.key_id, None)
if priv_key is not None:
return priv_key
if not isinstance(private_key_pem, bytes):
private_key_pem = private_key_pem.encode()
priv_key = serialization.load_pem_private_key(
private_key_pem,
password=None,
backend=default_backend()
)
if len(self._private_keys_cache) > 10:
self._private_keys_cache = dict()
self._private_keys_cache[key_identifier.key_id] = priv_key
return priv_key
示例11: load_or_create_client_key
# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import load_pem_private_key [as 别名]
def load_or_create_client_key(pem_path):
"""
Load the client key from a directory, creating it if it does not exist.
.. note:: The client key that will be created will be a 2048-bit RSA key.
:type pem_path: ``twisted.python.filepath.FilePath``
:param pem_path: The certificate directory
to use, as with the endpoint.
"""
acme_key_file = pem_path.asTextMode().child(u'client.key')
if acme_key_file.exists():
key = serialization.load_pem_private_key(
acme_key_file.getContent(),
password=None,
backend=default_backend())
else:
key = generate_private_key(u'rsa')
acme_key_file.setContent(
key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption()))
return JWKRSA(key=key)
示例12: loadPrivateKey
# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import load_pem_private_key [as 别名]
def loadPrivateKey(private_filename: str, optional_password: Optional[str]) -> Optional[RSAPrivateKey]:
"""Load a private key from a file.
:param private_filename: The filename of the file containing the private key.
:param optional_password: The key can be signed with a password as well (or not).
:return: The private key contained in the file.
"""
try:
password_bytes = None if optional_password is None else optional_password.encode()
with open(private_filename, "rb") as file:
private_key = load_pem_private_key(file.read(), backend=default_backend(), password=password_bytes)
return private_key
except: # Yes, we do really want this on _every_ exception that might occur.
Logger.logException("e", "Couldn't load private-key.")
return None
示例13: __init_crypto
# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import load_pem_private_key [as 别名]
def __init_crypto(self):
# https://stackoverflow.com/questions/29650495/how-to-verify-a-jwt-using-python-pyjwt-with-public-key
with self.app.app_context():
with open('{}/keys/appkernel.pem'.format(self.cfg_dir), "rb") as key_file:
private_key = serialization.load_pem_private_key(
key_file.read(),
password=None,
backend=default_backend()
)
config.private_key = private_key
with open('{}/keys/appkernel.pub'.format(self.cfg_dir), 'rb') as key_file:
public_key = serialization.load_pem_public_key(
key_file.read(),
backend=default_backend()
)
config.public_key = public_key
示例14: from_string
# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import load_pem_private_key [as 别名]
def from_string(cls, key, key_id=None):
"""Construct a RSASigner from a private key in PEM format.
Args:
key (Union[bytes, str]): Private key in PEM format.
key_id (str): An optional key id used to identify the private key.
Returns:
google.auth.crypt._cryptography_rsa.RSASigner: The
constructed signer.
Raises:
ValueError: If ``key`` is not ``bytes`` or ``str`` (unicode).
UnicodeDecodeError: If ``key`` is ``bytes`` but cannot be decoded
into a UTF-8 ``str``.
ValueError: If ``cryptography`` "Could not deserialize key data."
"""
key = _helpers.to_bytes(key)
private_key = serialization.load_pem_private_key(
key, password=None, backend=_BACKEND)
return cls(private_key, key_id=key_id)
示例15: _restore_state
# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import load_pem_private_key [as 别名]
def _restore_state(self):
"""Restore user state."""
try:
state = self._state_store.get_value(self._state_store_key)
state_dict = pickle.loads(
binascii.unhexlify(state.encode("utf-8")))
self._name = state_dict['name']
self.enrollment_secret = state_dict['enrollment_secret']
enrollment = state_dict['enrollment']
if enrollment:
private_key = serialization.load_pem_private_key(
enrollment['private_key'],
password=None,
backend=default_backend()
)
cert = enrollment['cert']
self.enrollment = Enrollment(private_key, cert)
self.affiliation = state_dict['affiliation']
self.account = state_dict['account']
self.roles = state_dict['roles']
self._org = state_dict['org']
self.msp_id = state_dict['msp_id']
except Exception as e:
raise IOError("Cannot deserialize the user", e)