简体   繁体   中英

How to get fingerprint or key_id from gpg signature in python?

I'm using the python-gpg library to decrypt / encrypt. Validation while decrypting a mail works fine, but i'm also trying to check which key was used to created a PGP signature, for example when a mail was not encrypted, just signed.

Is there a way to get the fingerprint or key_id from a gpg signature string using the python-gpg lib ? Thanks !

Yes, there is. If you try to validate a signature for a key that is not in your keybox or a specified keybox or keyring, a BadSignatures error will be raised, just as currently occurs with correctly implemented MUAs. That error message will also return the full key ID (ie the fingerprint) of the key or subkey which made the signature. The function is the same for verifying a signature as you normally would, but in a manner which will catch any BadSignatures errors if they are raised.

Both the examples scripts for verifying detatched signatures and normal signatures or clearsigned messages demonstrate how this is done. If the message uses PGP/MIME (which it should) then the detached signature verification method should be used, otherwise the other method ought to be used.

The part of the code in detached signature verification example dealing with this error data is this:

import gpg

c = gpg.Context()

try:
    data, result = c.verify(open(filename), open(sig_file))
except gpg.errors.BadSignatures as e:
    print(e)

If the error is raised the output will be the full key ID followed by ": no public key" and no traceback.

This is also covered in the documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM