Skip to content

GPG (GNU Privacy Guard)

Listing your keys

# List saved public keys (Yours and others')
gpg --list-public-keys

# List your private keys (You shouldn't have others' private keys)
gpg --list-secret-keys

Generate a GPG key and subkey with specified attributes

gpg --batch --generate-key <<-EOF
    Key-Type: [RSA|DSA|ELG|ECDSA] # Choose key type
    Key-Length: [2048|3072|4096] # Choose key length
    Subkey-Type: [RSA|DSA|ELG|ECDSA] # Choose subkey type
    Subkey-Length: [2048|3072|4096] # Choose subkey length
    Name-Real: {name}
    Name-Email: {email or identifier} # Used to identify keys
    Expire-Date: [YYYY-MM-DD|Nd|Nw|Nm|Ny|0] # Optional; set expiration date or period (d=days, w=weeks, m=months, y=years); 0 means the key does not expire
    Key-Usage: [sign|encrypt|auth] # Optional; specify key usage
    Passphrase: {secret passphrase} # Optional; See note below
EOF

Note

If you don't want to specify a passphrase in the terminal, so it's not in history, you may remove the "Passphrase" option. However, generating a GPG key in a non-prompt method like this will prevent you from being prompted for a passphrase. So in order to get around this, you will need to install and configure a pinentry (Pin Entry) utility.

# MacOS
brew install pinentry-mac

# Linux (Debian/Ubuntu)
sudo apt install [pinentry-gtk2 | pinentry-curses]

Next, get the path to your pinentry program.

which [pinentry-mac | pinentry-gtk2 | pinentry-curses]

Next, tell the gpg-agent that you're using this by editing ~/.gnupg/gpg-agent.conf and adding in the line

pinentry-program /path/to/pinentry-program

Finally, reload the gpg-agent

gpgconf --kill gpg-agent

Now when you generate the key, it'll prompt for the passphrase using the install pinentry program

Encrypt a file for a specific recipient

  1. Download their public key
  2. Import their key
    gpg --import /path/to/recipient_public_key.asc
    
  3. Encrypt the file
    gpg \
    --encrypt \
    --recipient {email or identifier} \
    [--output file.txt.gpg] \
    file.txt
    

Decrypt a file that was encrypted for you

gpg \
--decrypt \
[--local-user {email or identifier}] \
[--output file.txt] \
file.txt.gpg

Sign a file

gpg \
[--local-user {email or identifier}] \
--sign \
file.txt

Verify a signed file

gpg \
[--local-user {email or identifier}] \
--verify \
file.txt.gpg