Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GPG - Change passphrase non interactively

Most other GPG commands allow you to use --batch mode, but it doesn't appear to be the case when trying to edit a passphrase.

You have to run gpg --edit-key user

Which opens up an interactive GPG prompt.

This isn't going to work in my case as I need the ability to change the passphrase without the command line interaction.

The closest thing I've found is

gpg --batch --passphrase-fd 0 --status-fd 2 --command-fd 0 --edit-key

But this just gives me an invalid command after I enter the existing passphrase.

Any suggestions greatly appreciated.

like image 702
Nick Shears Avatar asked Jun 13 '19 13:06

Nick Shears


1 Answers

I just encountered this problem while writing a key-gen script and came up with a solution!

A few things to note:

  1. Lots of folks point towards --batch because --passphrase* requires it. In this case we'll be working with STDIN (as specified by --command-fd 0) and thus want to pass raw input rather than messing with the GnuPG functions.
  2. While --status-fd 2 is useful for debugging, it isn't necessary. That said, including it lead me to the insight that --change-passphrase is requesting two, and only two, entries.
  3. Set --pinentry-mode loopback to avoid having a prompt asking for your passphrase.

The solution is to pipe (or redirect) both the original and new passphrases to STDIN where GnuPG can processes them. While my initial code used (echo ..;echo ..)|gpg .. it is better to use a here-document.

# Using GnuPG to change PGP key passphrase non-interactively
gpg --command-fd 0 --pinentry-mode loopback \
    --change-passphrase ${KEYID} <<END
${OLD_PASS}
${NEW_PASS}
END

Just set up the variables and that should work. Enjoy!

like image 73
Salt Avatar answered Oct 04 '22 10:10

Salt