python gnupg 没有加密文件

python gnupg not encrypting file

我正在尝试使用 GPG 密钥加密文件,但输出一直为空:

>>> import gnupg
>>> home_dir = '~/.gnupg'
>>> pgp = gnupg.GPG(gnupghome=home_dir)
>>> key = open('ff.asc', 'rb')
>>> fp = open('test.txt', 'rb')
>>> res = pgp.import_keys(key.read())
>>> res.results
[{'fingerprint': 'C3...', 'text': 'Not actually changed\n', 'ok': '0'}]
>>> enc = pgp.encrypt_file(fp, 'C3...')
>>> enc.data
b''

我在这里错过了什么?

此外,是否可以将 public GPG 密钥直接从字符串传递给加密函数而无需导入它?

问题可能是导入的密钥不受信任。来自 documentation of gnupg:

Note:

Any public key provided for encryption should be trusted, otherwise encryption fails but without any warning. This is because gpg just prints a message to the console, but does not provide a specific error indication that the Python wrapper can use.

最简单的解决方案是使用加密函数的 always_trust 关键字参数:

always_trust (defaults to False) - Skip key validation and assume that used keys are always fully trusted.

因此您的加密声明应为

enc = pgp.encrypt_file(fp, 'C3...', always_trust=True)