Create and Use OpenPGP Keys

Published on 2020-06-30 by Dash Eclipse

In this article I'm gonna explain how do I generate and use OpenPGP keys.

1 Install GnuPG

On macOS you can use brew to install GnuPG brew install gnupg, you will also need pinentry-mac package if you are going to use it with GUI programs such like Thunderbird with Eng

2 OpenPGP key generation

Beside gpg --full-generate-key, you can also create a key with gpg in batch mode1.

cat >first-last.txt <<EOF
%echo Generating a basic OpenPGP key
Key-Type: RSA
Key-Length: 4096
Key-Usage: cert
#Subkey-Type: RSA
#Subkey-Length: 4096
Name-Real: First Last
#Name-Comment:
Name-Email: user@domain.tld
Expire-Date: 30y
Passphrase: password
%commit
%echo done
EOF

Create a key in an ephemeral home directory

mkdir -m700 .gnupg
## Set the environment variable
## or pass --homedir .gnupg as an argument
export GNUPGHOME=".gnupg"
gpg --batch --generate-key first-last.txt

3 Use subkeys

I use encryption and signing subkeys instead of just use one key for everything, because it's safer when you keep your master key elsewhere and use different keys for different purposes. Debian also recommend to use subkeys.2

## adduid, (trust, 5,) save
gpg --edit-key user@domain.tld
## Get keygrip
gpg --with-keygrip --list-key <key-id>
## Export and Import the key to the GPG homedir
## where you are gonna use the key,
## remove the master key from there
## and change the password
rm .gnupg/private-keys-v1.d/<keygrip>.key
gpg --edit-key <key-id> passwd

3.1 Thunderbird and Enigmail

I use Thunderbird with Enigmail to send and receive PGP encrypted emails, you can follow the guide by EFF SSD to set it up. Note you need to install pinentry-mac the package to use GPG with such GUI programs.

brew install pinentry-mac
echo 'pinentry-program /usr/local/bin/pinentry-mac' > ~/.gnupg/gpg-agent.conf

3.2 Git

git config --global gpg.program $(which gpg)
git config --global user.name 'First Last'
git config --global user.email 'user@domain.tld'
git config --global user.signingkey <signing_subkey_id>
git config --global commit.gpgsign true

In case you don't want to sign commits for specific repo, just run git config commit.gpgsign false in the repo directory.

3.3 pass (the standard unix password manager)

I use pass to manage my passwords, with a different key. pass store passwords in a git repo, you can also store the $GNUPGHOME in a git repo or just in the same repo. I have some config like this in my zsh config ~/.zshrc.local

PASSWORD_STORE_DIR="$HOME/passwordstore"
alias pass="GNUPGHOME=\"$HOME/passwordstore/.gnupg\" PASSWORD_STORE_DIR=\"$HOME/passwordstore\" pass"

Footnotes: