i'm trying to gpg-sign a file using python-gnupgp
.
This should be rather simple:
my code is simple:
import gnupg
import sys
gpg = gnupg.GPG()
stream = open(sys.argv[1], "rb")
signed_data = gpg.sign_file(stream)
print("signed data: %s" % (signed_data.data))
print("stderr: %s" % (signed_data.stderr))
now the above code does not work, as I don't provide a passphrase to gpg.sign_file()
, and gnupg cannot ask for it, as the error indicates:
signed data: b''
stderr: [GNUPG:] USERID_HINT 1234567890ABCDEF me myself <[email protected]>
[GNUPG:] NEED_PASSPHRASE 1234567890ABCDEF 1234567890ABCDEF 1 0
gpg: Sorry, no terminal at all requested - can't get input
according to this question/answer the problem is likely a default of having no-tty
in the default GPG-options.
now i think that the no-tty
option makes sense, and i would like to provide a way to ask for the passphrase and then supply it to the sign_file
call.
in the simplest case, something like:
import getpass
pw=getpass.getpass()
signed_data=gpg.sign_file(stream, passphrase=pw)
no my problem is, that i would like to tell the user, which key's passphrase they are being asked for. something like
print("Please enter the passphrase for key %s" % defaultkey_id)
pw=getpass.getpass()
which turns out suprisingly hard to do, as i haven't found a way to query the ID of the default key. a simple gpg.list_keys(True)[0]
gives a random private key (well not random; most likely the first one added to the keyring; but that need not be the default key).
So i guess my real question is: how can i find out what is the default key used for signing, so i can ask the user for a passphrase for this very key?
(i'd rather not parse the content of $GNUPGHOME/gpg.conf
)
If you have gpgconf available, you could parse the output of
gpgconf gpg
, which should list (among the other configured options) the configured default-key.