首页 > 解决方案 > 如何在没有子进程的情况下导入和使用系统 gpg 密钥

问题描述

我决定回顾一下我的脚本如何提取 gpg 密钥并使用该密钥加密密码。目前,我正在使用子进程在主机上运行命令,如下所示:

def check_for_imported_gpg_key():
    gpg_keys = subprocess.check_output(["gpg", "-k"]).decode("utf-8")
    if "pillar" in gpg_keys:
        return True
    else:
        return False


def encrypt_pillar_password(password):
    hashed_pass = crypt.crypt(str(password))
    key_imported = check_for_imported_gpg_key()
    if key_imported is False:
        print("OI! Import the key bud!")
    print("Encrypting Password with Pub Key")
    process = subprocess.Popen(
        (
            "gpg",
            "--armor",
            "--batch",
            "--trust-model",
            "always",
            "--encrypt",
            "-r",
            "pillar",
        ),
        stdout=subprocess.PIPE,
        stdin=subprocess.PIPE,
        stderr=subprocess.PIPE,
    )
    gpg_message = process.communicate(input=hashed_pass.encode())[0]
    if "BEGIN PGP MESSAGE" in str(gpg_message):
        return gpg_message
    else:
        print("Something went wrong when generating the encrypted hash")
        print(str(gpg_message))
        return None

有没有更好、更 Pythonic 的方式来完成这项任务?我目前不知道有任何其他方法可以做到这一点。

标签: pythongnupg

解决方案


到目前为止,除了手动将加密原语应用于消息(不推荐)之外,生成子进程是在 python 中访问 gnupg 的最佳方式。有一个名为 的第三方模块python-gnupg,但它主要是 gpg 二进制文件的包装器。


推荐阅读