Last active
October 19, 2025 17:49
-
-
Save Criomby/a71a9b8dc024b7882ab37948542fd229 to your computer and use it in GitHub Desktop.
Easily create a backup archive of your pgp key.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/env/bin bash | |
| set -e | |
| function print_help() { | |
| echo " | |
| Backup gpg keys and create a compressed archive for backup. | |
| Creates the archive in the current directory. | |
| Usage: gpg_backup.sh <email> | |
| " | |
| } | |
| POS_ARGS=() | |
| while [[ $# -gt 0 ]]; do | |
| case $1 in | |
| -h|--help) | |
| print_help | |
| exit 0 | |
| ;; | |
| -*|--*) | |
| echo "Unknown option $1" | |
| exit 1 | |
| ;; | |
| *) | |
| POS_ARGS+=("$1") | |
| shift | |
| ;; | |
| esac | |
| done | |
| set -- "${POS_ARGS[@]}" | |
| if [[ "${#POS_ARGS[@]}" -lt 1 ]]; then | |
| echo "Error: missing required argument email" | |
| exit 1 | |
| fi | |
| EMAIL="${POS_ARGS[0]}" | |
| KEY_INFO="$(gpg --list-keys --with-colons "$EMAIL" 2>/dev/null)" | |
| gpg2 --export --armor "$EMAIL" > ${EMAIL}.pub.asc | |
| gpg2 --export-secret-keys --armor "$EMAIL" > ${EMAIL}.priv.asc | |
| gpg2 --export-secret-subkeys --armor "$EMAIL" > ${EMAIL}.sub_priv.asc | |
| gpg2 --export-ownertrust > ownertrust.txt | |
| # backup revocation certificate | |
| # LONG_KEY_ID=$(echo "$KEY_INFO" | awk -F: '/^pub/ {print $5}') | |
| FINGERPRINT=$(echo "$KEY_INFO" | awk -F: '/^fpr/ {print $10; exit}') | |
| REVOC="$FINGERPRINT.rev" | |
| if [[ ! -f "$HOME/.gnupg/openpgp-revocs.d/$REVOC" ]]; then | |
| echo "Warning: no revocation certificate found for $EMAIL" | |
| REVOC="" | |
| else | |
| cp "$HOME/.gnupg/openpgp-revocs.d/$REVOC" . | |
| fi | |
| # create a bzip2 compressed archive | |
| tar -cjvf \ | |
| gpg_backup_${EMAIL}.tar.bz2 \ | |
| ${EMAIL}.pub.asc \ | |
| ${EMAIL}.priv.asc \ | |
| ${EMAIL}.sub_priv.asc \ | |
| ownertrust.txt \ | |
| $REVOC | |
| rm \ | |
| ${EMAIL}.pub.asc \ | |
| ${EMAIL}.priv.asc \ | |
| ${EMAIL}.sub_priv.asc \ | |
| ownertrust.txt \ | |
| $REVOC |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment