Skip to content

Instantly share code, notes, and snippets.

@arambadk
Created March 21, 2018 00:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arambadk/032b7c4f92c01bcc7cf4361727f31fa5 to your computer and use it in GitHub Desktop.
Save arambadk/032b7c4f92c01bcc7cf4361727f31fa5 to your computer and use it in GitHub Desktop.
Migrating from pycrypto to cryptography

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())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment