As part of a recent project I needed to encrypt a file with GPG using a public key provided by a client before transferring it over to them. This seemed to be surprisingly badly documented (though this blog did come in handy) so I figured I’d document it as well as possible for future re-use.
First off you need to import the public key file using the following command where “RECIPIENT” is the name of the user that created the key and “PATH” is the path to the key.
gpg --import -r "RECIPIENT" "PATH"
Once the key’s imported you need to trust the recipient otherwise you will receive something like the following when trying to encrypt a file.
gpg: checking the trustdb
gpg: no ultimately trusted keys found
gpg: There is no assurance this key belongs to the named user
It is NOT certain that the key belongs to the person named
in the user ID. If you *really* know what you are doing,
you may answer the next question with yes.
Use this key anyway? (y/N)
This can be sorted by editing the key using the following where “ID” is an ID automatically generated by the import command above which is returned by the command line.
gpg --edit-key 30AB960592F188GT
Once the recipient has been trusted use CTRL+C to exit gpg within the command prompt, you can then encrypt a file using the imported key using the below code. This will create a new encrypted file in the same location as the target with the same name as the target with “.gpg” appended.
gpg --encrypt -r "RECIPIENT" "TARGET_FILEPATH"
If you want to create a file in a different location or with a different name then you need to specify the output path as well.
gpg --encrypt -r "RECIPIENT" -o "OUTPUT_FILEPATH" "TARGET_FILEPATH"