gnupg 指纹未被识别为有效的加密接收者

gnupg fingerprint not identified as valid recipient for encryption

密钥的 gnupg 指纹未被识别为加密的有效接收者。根据这个文档 https://pythonhosted.org/python-gnupg/#encryption 我们可以使用指纹。但是它不起作用。

>>> import gnupg
>>> gpg = gnupg.GPG(gnupghome="/home/user/.gnupg")
>>> key_data = open('/home/user/path/to/public_key.pgp').read()
>>> import_result = gpg.import_keys(key_data)
>>> test_status = gpg.encrypt('test', import_result.fingerprints[0])
>>> test_status.status
'invalid recipient'
>>> 

如果您尝试从命令行执行相同的过程,您将在尝试加密发送给收件人 (gpg -ea -r <fingerprint>) 的邮件时看到以下错误:

It is NOT certain that the key belongs to the person named
in the user ID.  If you *really* know what you are doing,
you may answer the next question with yes.

Use this key anyway? (y/N)

有必要先“信任”密钥,然后才能将其用作收件人。您可以使用 trust_keys 方法执行此操作:

>>> import_result = gpg.import_keys(key_data)
>>> gpg.trust_keys(import_result.fingerprints[0], 'TRUST_ULTIMATE')
<gnupg.TrustResult object at 0x7f2ab0b22e30>
>>> test_status = gpg.encrypt('test', import_result.fingerprints[0])
>>> test_status.status
'encryption ok'

或者,您可以设置 always_trust 参数:

>>> import_result = gpg.import_keys(key_data)
>>> test_status = gpg.encrypt('test', import_result.fingerprints[0], always_trust=True)
>>> test_status.status
'encryption ok'

always_trust 选项描述为 in the documentation