In GPG, there is no proper documentation how to check a valid passphrase via bash code so, this is a hack. Based on the following example code is use to check whether GPG password that is cached in gpg-agent is valid or not:
#!/bin/bash
KEY_ID=YOUR_KEY_ID
echo "1234" | gpg -q --batch --status-fd 1 --sign --local-user $KEY_ID --passphrase-fd 0 --output /dev/null
return_code=$?
if [ "$return_code" = 0 ]; then
echo "Valid passphrase has been set in gpg-agent"
else
echo "Invalid passphrase or no passphrase is set in gpg-agent"
fi
If a valid passphrase is set, and when I run this bash script, the return value is 0. This is correct
But
If no passphrase or invalid passphrase is set, I can see that the command is waiting for some unknown input or processes and it does not exit (blinking cursor until I terminate with CTRL+C). But this is a good signal to show that invalid passphrase is supplied.
My question is, if invalid passphrase is supplied, how do I force the command to exit and get return value of 1 so I can use the if else conditional correctly ?
NOTE AND INFO TO REPRODUCE THE PROBLEM FROM THE CODE (THIS IS NOT A QUESTION):
to set gpg password there are 2 ways:
gpg --export-secret-keys -a <KEY_ID>
(this can validate the passphrase) or- without prompt in bash:
/usr/libexec/gpg-preset-passphrase -c $KEY_GRIP <<< $PASSPHRASE
(this does not validate the passphrase). I need to use command for cron. Why? Read below.
to clear the password I do this:
echo RELOADAGENT | gpg-connect-agent
KEY_ID
- you got when you first create the cert
KEY_GRIP
- can be obtain with this command: gpg --with-keygrip --list-secret-keys $KEY_ID
.
PASSPHRASE
- is your passphrase / password for your cert to cache in gpg-agent.
Note that, If you are using this method to cache password in gpg-agent: /usr/libexec/gpg-preset-passphrase -c $KEY_GRIP <<< $PASSPHRASE
, it won't validate the passphrase because wrong passphrase can also be cached in gpg-agent. This method is the only way to skip interactive input when run as cron to prevent script error because no input from user. This is the reason I use the hacked code.