I used pycrypto in my projects before but since the project is no longer under active development it is highly recommended to move to cryptography.
I faced some difficulty during this migration so I am documenting my solution to help others.
This is how my pycrypto code to get pem encoded key looked like
from Crypto.IO import PKCS8
from Crypto.IO import PEM
def key_stuff(key_file=None):
if key_file is not None:
with open(key_file) as kf:
algo, binary_pk, params = PKCS8.unwrap(kf.read())
else:
# This is from a non local key source. This is specific to my environment feel free to ignore if not applicable to your environment
algo, binary_pk, params = PKCS8.unwrap(get_my_key())
return PEM.encode(binary_pk, 'RSA PRIVATE KEY')
Now the code looks as follows
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.backends import default_backend
def key_stuff(key_file=None):
if key_file is not None:
with open(key_file) as kf:
binary_pk = serialization.load_der_private_key(kf.read())
else:
# This is from a non local key source. This is specific to my environment feel free to ignore if not applicable to your environment
binary_pk = serialization.load_der_private_key(get_my_key(), None, default_backend())
return binary_pk.private_bytes(encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption())