From 96d1fb171ad06e8d1efd3b98ebd56d840c9a4661 Mon Sep 17 00:00:00 2001 From: Hendrik Hogertz Date: Sat, 21 Feb 2026 11:34:08 +0100 Subject: [PATCH] Add GPG YubiKey switch helper script --- gpg-switch-yubikey/README.md | 26 ++++++++++++++++++++++++++ gpg-switch-yubikey/gpg-switch-yubikey | 12 ++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 gpg-switch-yubikey/README.md create mode 100755 gpg-switch-yubikey/gpg-switch-yubikey diff --git a/gpg-switch-yubikey/README.md b/gpg-switch-yubikey/README.md new file mode 100644 index 0000000..fa9561d --- /dev/null +++ b/gpg-switch-yubikey/README.md @@ -0,0 +1,26 @@ +# gpg-switch-yubikey + +Switch GPG between two YubiKeys that hold identical key material. + +GPG binds secret key stubs to a specific card serial number. When you swap YubiKeys, GPG prompts you to insert the other one. This script deletes the stubs and re-learns whichever card is currently inserted. + +## Install + +```bash +cp gpg-switch-yubikey ~/.local/bin/ +chmod +x ~/.local/bin/gpg-switch-yubikey +``` + +Make sure `~/.local/bin` is in your `PATH`. + +## Usage + +After physically swapping to a different YubiKey: + +```bash +gpg-switch-yubikey +``` + +## Configuration + +The script contains a hardcoded GPG key fingerprint. Edit the `FINGERPRINT` variable in the script to match your own key. diff --git a/gpg-switch-yubikey/gpg-switch-yubikey b/gpg-switch-yubikey/gpg-switch-yubikey new file mode 100755 index 0000000..44f02dd --- /dev/null +++ b/gpg-switch-yubikey/gpg-switch-yubikey @@ -0,0 +1,12 @@ +#!/bin/bash +# Re-learn the currently inserted YubiKey for GPG +FINGERPRINT="4A227DDEFA7A37048609549863C6571F1095CC5C" + +KEYGRIPS=$(gpg --with-keygrip --list-secret-keys "$FINGERPRINT" 2>/dev/null | grep Keygrip | awk '{print $3}') +for kg in $KEYGRIPS; do + rm -f ~/.gnupg/private-keys-v1.d/${kg}.key +done +gpgconf --kill gpg-agent +gpgconf --kill scdaemon +sleep 1 +gpg --card-status > /dev/null 2>&1 && echo "Switched to $(gpg --card-status 2>/dev/null | grep 'Serial number' | awk '{print $NF}')" || echo "No card found"