in ec2instanceconnectcli/key_utils.py [0:0]
def serialize_key(key, encoding='PEM', return_private=False, password=None):
"""
Given an RSA private key object, return the public or private key in the requested encoding.
encoded in the requested formats. Private keys will always use TraditionalOpenSSL format,
because that's the format supported by Paramiko
public keys will always use SubjectPublicKeyInfo format UNLESS
the encoding is 'OpenSSH' (in which case, it will use OpenSSH format).
:param key: An RSA private key object
:type key: cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey
:param encoding: The encoding to use for serializing the private key. Allowed: 'PEM', 'DER', 'OpenSSH'. Default: 'PEM'. \
Note that if return_private is True then 'OpenSSH' is not allowed.
:type encoding: basestring
:param return_private: Whether to return the public or private key. Default: False.
:type return_private: bool
:param password: In bytes, an optional password to use for encoding a private key. Ignored if return_private is False. \
Default: None
:type password: basestring
:return: Encoded key as a byte array
:rtype: bytearray
"""
if return_private and encoding == 'OpenSSH':
raise AssertionError('Private keys cannot be serialized in OpenSSH encoding')
if encoding == 'OpenSSH':
assert(not return_private)
enc = crypto_serialization.Encoding.OpenSSH
elif encoding == 'PEM':
enc = crypto_serialization.Encoding.PEM
elif encoding == 'DER':
enc = crypto_serialization.Encoding.DER
else:
raise AssertionError('Unrecognized encoding {0}'.format(encoding))
if return_private:
if password:
enc_alg = crypto_serialization.BestAvailableEncryption(password)
else:
enc_alg = crypto_serialization.NoEncryption()
return key.private_bytes(
encoding=enc,
format=crypto_serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=enc_alg
)
else:
if encoding == 'OpenSSH':
format = crypto_serialization.PublicFormat.OpenSSH
else:
format = crypto_serialization.PublicFormat.SubjectPublicKeyInfo
return key.public_key().public_bytes(
encoding=enc,
format=format
)