pgp_utils.py 1.2 KB

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