pgp_utils.py 664 B

123456789101112131415161718192021222324252627
  1. import gnupg
  2. from app.config import GNUPGHOME
  3. gpg = gnupg.GPG(gnupghome=GNUPGHOME)
  4. gpg.encoding = "utf-8"
  5. class PGPException(Exception):
  6. pass
  7. def load_public_key(public_key: str) -> str:
  8. """Load a public key into keyring and return the fingerprint. If error, raise Exception"""
  9. import_result = gpg.import_keys(public_key)
  10. try:
  11. return import_result.fingerprints[0]
  12. except Exception as e:
  13. raise PGPException("Cannot load key") from e
  14. def encrypt(data: str, fingerprint: str) -> str:
  15. r = gpg.encrypt(data, fingerprint, always_trust=True)
  16. if not r.ok:
  17. raise PGPException("Cannot encrypt")
  18. return str(r)