Skip to content

Instantly share code, notes, and snippets.

@slavafomin
Last active May 14, 2024 10:01
Show Gist options
  • Save slavafomin/7114c76a55a2d89e4119a56aa52cd484 to your computer and use it in GitHub Desktop.
Save slavafomin/7114c76a55a2d89e4119a56aa52cd484 to your computer and use it in GitHub Desktop.
Using GPG encryption on Linux

GPG Encryption

List Keys

gpg --list-keys

Import Key

gpg --import private.key

Config file

# ~/.gnupg/gpg.conf:

default-key {KEY-ID}
default-recipient-self

Encrypt/Decrypt File

This encrypts the file using default key (default recipient):

gpg -e filename

This decrypts it back:

gpg -d filename.gpg > filename

Acrhive & Encrypt

tar czf - . | gpg -e > archive.gpg
#!/usr/bin/env bash
# This is an example of a backup script that
# creates encrypted archive of a JavaScript project.
# The "vars" file should be created alongside
# this script with the following vars:
#
# BACKUP_PATH="/home/username/backup.tgz.gpg" # path to the destination archive
# GPG_KEY="12345" # recipient's GPG key
# Decrypt it with:
# gpg -d filename.gpg > filename.tgz
set -e
set -o pipefail
SCRIPT_PATH="$(dirname "$0")"
VARS_PATH=$(realpath "${SCRIPT_PATH}/vars")
if [ ! -f "$VARS_PATH" ]; then
echo -e "Missing vars file at:\n${VARS_PATH}"
echo -e "\nCreate it with \"cp ./bin/vars.dist ./bin/vars\""
exit 1
fi
# shellcheck source=../vars
source "${VARS_PATH}"
if [ -z "${BACKUP_PATH-}" ]; then
echo -e "Missing the BACKUP_PATH variable from:\n${VARS_PATH}"
exit 1
fi
if [ -z "${GPG_KEY-}" ]; then
echo -e "Missing the GPG_KEY variable from:\n${VARS_PATH}"
exit 1
fi
echo -e "Creating archive at:\n${BACKUP_PATH}"
echo -e "\nUsing GPG key:\n${GPG_KEY}"
tar czf - \
--exclude='.git' \
--exclude='.idea' \
--exclude='dist' \
--exclude='node_modules' \
--exclude='tmp' \
. \
| gpg -e -R "${GPG_KEY}" > "${BACKUP_PATH}"
echo -e "\nBackup complete"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment