gnupg fingerprint of key is not identified as valid recipient for encryption. According to this doc https://pythonhosted.org/python-gnupg/#encryption we can use fingerprint. But its not working.
>>> 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'
>>>
If you were to attempt the same process from the command line, you would see the following error when attempting to encrypt a message to the 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)
It is necessary to "trust" the key before you can use it as a recipient. You can do this using the trust_keys
method:
>>> 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'
Alternately, you can set the always_trust
parameter:
>>> import_result = gpg.import_keys(key_data)
>>> test_status = gpg.encrypt('test', import_result.fingerprints[0], always_trust=True)
>>> test_status.status
'encryption ok'
The always_trust
option is described in the documentation.