Can I specify a public key file instead of recipient when encrypting with GPG

GnuPG does not support encrypting to a recipient specified by a key file. The key must be imported in advance, and the recipient defined with either his mail address or key ID.

I'd recommend to use a cleaner approach as expected by GnuPG and hard-code either the key's fingerprint, or a user ID given by that key and import it as usual.

If you really do not want to import the key, you could do following as workaround (which actually imports the key, but to a temporary GnuPG home directory):

  1. Import the key to a temporary folder, for example using

    gpg --homedir /tmp/gnupg --import my.pub
    
  2. Determine the key ID of the key stored in the file:

    KEYID=`gpg --list-public-keys --batch --with-colons --homedir /tmp/gnupg | head -n1 | cut -d: -f5`
    
  3. Encrypt a message to the recipient

    gpg --homedir /tmp/gnupg --recipient ${KEYID} --encrypt
    
  4. Clean up temporary GnuPG home directory

    rm -f /tmp/gnupg
    

You could of course save this as a script to make using it more convenient.


Since GnuPG 2.1.14 there is a new option allowing to encrypt from a keyfile: --recipient-file FILENAME. It works from an binary or an ascii armored file.

Check the release notes or the dev mailing list.


It appears from reviewing your question that you're interested in encrypting using your own public key which you'd already have (my.pub in the example).

Indeed, not only is it possible, it's desirable as it serves to provide non-interactive automation of encryption. If it's YOUR public key, then you trust it implicitly and can do the following without worry:

gpg --batch --yes --trust-model always -r $GPGPUBKEYRECIPIENTEMAIL -e ./file.txt

No interactive prompts that require an answer so encryption can be scripted. NOTE: I upload my PUBLIC key to the public server I want to protect data on, keeping the PRIVATE key apart from it.

However, if you're NOT encrypting with your own key, the --trust-model always switch could be dodgy. Also note that when decrypting, you'll be prompted for a password unless you automate that of course. HTH bud- Terrence Houlahan