google / openhtf

The open-source hardware testing framework.
Apache License 2.0
530 stars 217 forks source link

Replacing `M2Crypto` dependency with `cryptography` #1135

Open facutuesca opened 8 months ago

facutuesca commented 8 months ago

Hi! Would you be open to a PR to replace the M2Crypto dependency with cryptography?

Since M2Crypto is only used to implement a adb_protocol.AuthSigner subclass (M2CryptoSigner), only needing to load RSA keys and sign with them, it could be easily replaced with something like:

from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives import hashes

def get_passphrase() -> Optional[str]:
  from getpass import getpass
  try:
    return getpass('Enter passphrase:')
  except KeyboardInterrupt:
    return None

class CryptographySigner(adb_protocol.AuthSigner):
  """AuthSigner using cryptography."""
  def __init__(self, rsa_key_path):
    with open(rsa_key_path + '.pub') as rsa_pub_file:
      self.public_key = rsa_pub_file.read()

    with open(rsa_key_path, "rb") as rsa_file:
      self.rsa_key = serialization.load_pem_private_key(rsa_file.read(),
                                                        password=get_passphrase())

  def sign(self, data):
    return self.rsa_key.sign(data, hashes.SHA1)

  def get_public_key(self):
    """Return the public key."""
    return self.public_key