Skip to content
Snippets Groups Projects
crypto.py 1.91 KiB
Newer Older
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
GnuPG abstraction layer

Copyright (C) 2010-2020 Cr@ns <roots@crans.org>
Authors : Daniel Stan <daniel.stan@crans.org>
          Vincent Le Gallic <legallic@crans.org>
          Alexandre Iooss <erdnaxe@crans.org>
SPDX-License-Identifier: GPL-3.0-or-later
"""

import subprocess
import logging
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed

import gpg

# Local logger
log = logging.getLogger(__name__)

me5na7qbjqbrp's avatar
me5na7qbjqbrp committed

def decrypt(ciphertext: str):
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    Return decrypted content
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    log.info("Decrypting using GnuPG")
    with gpg.Context() as c:
        plaintext, _, _ = c.decrypt(ciphertext.encode("utf-8"))
    return plaintext.decode("utf-8")


def encrypt(content: str, keys: []) -> str:
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    Return encrypted content for keys
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    log.info("Encrypting using GnuPG")
    with gpg.Context() as c:
        c.armor = True
        cipher, _, _ = c.encrypt(content.encode("utf-8"), keys)
    return cipher.decode("utf-8")
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
def receive_key(fpr: str):
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    Download key from fingerprint
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    full_command = ['gpg', '--recv-keys', fpr]
    log.info("Running `%s`" % " ".join(full_command))
    return subprocess.run(full_command)
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
def check_key_validity(key, email: str) -> bool:
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    Check key identities email and trust level
    Return true if can be trusted and we can encrypt
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    log.info("Checking %s key with email %s" % (key.fpr, email))

    if not key.can_encrypt:
        log.debug("Cannot encrypt for key %s" % key.fpr)
        return False

me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    for uid in key.uids:
        if email == uid.email and not uid.revoked and not uid.invalid \
                and uid.validity >= gpg.constants.validity.FULL:
            return True
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    # no trusted valid uid were found
    log.debug("No trusted valid uid were found for this key")
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    return False
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
def get_key_from_fingerprint(fpr):
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    """
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    Get GnuPG key by fingerprint
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    """
    log.info("Getting key corresponding to %s" % fpr)
    with gpg.Context() as c:
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
        return c.get_key(fpr)