Is it possible to use a gpg public key to encrypt a message without importing the key?

Solution 1:

You could make a small shell script that copies your pubring.gpg file, imports the key, encrypts your file, then moves your original pubring.gpg file back into place. This turns it into a one-liner next time.

#!/bin/sh
cp -a ~/.gnupg/pubring.gpg ~/.gnupg/pubring.gpg-backup
gpg ... # Command to import 
gpg ... # Command to encrypt message/file
mv ~/.gnupg/pubring.gpg-backup ~/.gnupg/pubring.gpg

Note: parameters to the script are variables "$1", "$2", ...


Edit: I know I answered this a long time ago. I'd like to mention a pitfall in the above: an interruption before restoring the backup would lead to an altered keystore. I suggest instead copying into a temp directory:

#!/bin/sh
gpgtemp="$(mktemp -d gpgtemp.XXXXXXXXXX)"
cp -a ~/.gnupg "$gpgtemp"
gpg --homedir "$gpgtemp/.gnupg" ... # Command to import 
gpg --homedir "$gpgtemp/.gnupg" ... # Command to encrypt message/file
rm "$gpgtemp" -rf

Solution 2:

GnuPG requires all keys you want to use to be imported into a keyring.

If you don't want to import it to your normal keyring, either use another (temporary) keyring, or even a temporary GnuPG home directory (which will also bypass any configuration).

Temporary Keyring

Set --primary-keyring temporary.gpg to use (and create if necessary) a temporary keyring as default. It will be created in your GnuPG home directory (~/.gnupg/temporary.gpg by default). Your normal keyring will still be available, but imports will go to the temporary one. Delete it as you want to.

For example:

gpg --primary-keyring temporary.gpg --import key.asc
gpg --primary-keyring temporary.gpg --recipient 0xDEADBEEF --encrypt
rm ~/.gnupg/temporary.gpg # can be omitted, not loaded by default

Temporary GnuPG Home Directory

This will also reset all configuration, and might be helpful for testing some stuff. Set --homedir [folder] or the environment variable $GNUPGHOME, import the key, perform any operations and then delete the folder as you wish to.

For example:

export GNUPGHOME=/tmp/gnupg # Or apply --homedir on each invocation
gpg --import key.asc
gpg --recipient 0xDEADBEEF --encrypt
rm -r $GNUPGHOME # Can be omitted
unset $GNUPGHOME

GnuPG is very picky regarding permissions, you might need to apply stricter permissions to the $GNUPGHOME folder before being able to perform all operations. Might very well be an option to keep some playground-$GNUPGHOME around.