I want to import a PGP public key into my keychain in a script, but I don't want it to write the contents to a file. Right now my script does this:
curl http://example.com/pgp-public-key -o /tmp/pgp && gpg --import /tmp/gpg
How could I write this script so I can just call gpg --import
and import the public key as a string? Thank you for your help.
gpg --import
knows two ways of operation: it can either read from a file (for example gpg --import key.gpg
) or -- if no file name is passed -- read from STDIN. curl
on the other hand will print the fetched document to STDOUT if no -o
parameter is given. Putting both together with a pipe will directly stream the results from curl
into gpg --import
:
curl http://example.com/pgp-public-key | gpg --import
You can also use curl
to search for a key from a public keyserver if you know the key's ID:
curl -fsSL "https://keyserver.ubuntu.com/pks/lookup?op=get&options=mr&search=<key-id-here>" | gpg --import -
Note: you must prepend the key ID with 0x
.
Most public key servers allow you to truncate the key ID so you don't need to type the whole thing. For example, the following three examples will produce the exact same key:
curl -fsSL "https://keyserver.ubuntu.com/pks/lookup?op=get&options=mr&search=0x9454C19A66B920C83DDF696E07C8CCAFCE49F8C5" | gpg --import -
curl -fsSL "https://keyserver.ubuntu.com/pks/lookup?op=get&options=mr&search=0x07C8CCAFCE49F8C5" | gpg --import -
curl -fsSL "https://keyserver.ubuntu.com/pks/lookup?op=get&options=mr&search=0xCE49F8C5" | gpg --import -
Most of the key servers are synchronized too , so you don't necessarily need to stick with a single key server. You can see a list of other key servers and the information at the SKS Keyserver status page.
Explanations for the -fsSL
in the curl
command:
-f
, --fail
:
(HTTP) Fail silently (no output at all) on server errors.
-s
, --silent
:
Silent or quiet mode.
-S
, --show-error
:
When used with -s, --silent, it makes curl show an error message if it fails.
-L
, --location
:
(HTTP) If the server reports that the requested page has moved to a different location (indicated with a Location: header and a 3XX response code), this option will make curl redo the request on the new place.
In bash, you can use:
gpg --import <(curl http://example.com/pgp-public-key)
This is called process substitution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With