app-MAIL-temp/app/pgp_utils.py

41 lines
1.2 KiB
Python
Raw Normal View History

2020-04-02 21:29:16 +02:00
from io import BytesIO
2020-03-08 12:51:33 +01:00
import gnupg
from app.config import GNUPGHOME
from app.log import LOG
from app.utils import random_string
2020-03-08 12:51:33 +01:00
gpg = gnupg.GPG(gnupghome=GNUPGHOME)
2020-03-13 12:54:52 +01:00
gpg.encoding = "utf-8"
2020-03-08 12:51:33 +01:00
2020-03-08 12:51:33 +01:00
class PGPException(Exception):
pass
2020-03-08 12:51:33 +01:00
def load_public_key(public_key: str) -> str:
"""Load a public key into keyring and return the fingerprint. If error, raise Exception"""
import_result = gpg.import_keys(public_key)
try:
return import_result.fingerprints[0]
except Exception as e:
raise PGPException("Cannot load key") from e
2020-04-02 21:29:16 +02:00
def encrypt_file(data: BytesIO, fingerprint: str) -> str:
r = gpg.encrypt_file(data, fingerprint, always_trust=True)
2020-03-08 12:51:33 +01:00
if not r.ok:
2020-06-06 23:06:34 +02:00
LOG.error("Try encrypt again %s", fingerprint)
r = gpg.encrypt_file(data, fingerprint, always_trust=True)
if not r.ok:
# save the content for debugging
random_file_name = random_string(20) + ".eml"
full_path = f"/tmp/{random_file_name}"
with open(full_path, "wb") as f:
f.write(data.getbuffer())
LOG.error("Log to %s", full_path)
raise PGPException("Cannot encrypt")
2020-03-08 12:51:33 +01:00
return str(r)