pgp_utils.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. from io import BytesIO
  2. import gnupg
  3. from memory_profiler import memory_usage
  4. from app.config import GNUPGHOME
  5. from app.log import LOG
  6. from app.utils import random_string
  7. gpg = gnupg.GPG(gnupghome=GNUPGHOME)
  8. gpg.encoding = "utf-8"
  9. class PGPException(Exception):
  10. pass
  11. def load_public_key(public_key: str) -> str:
  12. """Load a public key into keyring and return the fingerprint. If error, raise Exception"""
  13. import_result = gpg.import_keys(public_key)
  14. try:
  15. return import_result.fingerprints[0]
  16. except Exception as e:
  17. raise PGPException("Cannot load key") from e
  18. def encrypt_file(data: BytesIO, fingerprint: str) -> str:
  19. LOG.d("encrypt for %s", fingerprint)
  20. mem_usage = memory_usage(-1, interval=1, timeout=1)
  21. LOG.d("mem_usage %s", mem_usage)
  22. r = gpg.encrypt_file(data, fingerprint, always_trust=True)
  23. if not r.ok:
  24. LOG.error("Try encrypt again %s", fingerprint)
  25. r = gpg.encrypt_file(data, fingerprint, always_trust=True)
  26. if not r.ok:
  27. # save the content for debugging
  28. random_file_name = random_string(20) + ".eml"
  29. full_path = f"/tmp/{random_file_name}"
  30. with open(full_path, "wb") as f:
  31. f.write(data.getbuffer())
  32. LOG.error("PGP fail - log to %s", full_path)
  33. raise PGPException("Cannot encrypt")
  34. return str(r)