Last active
February 3, 2026 13:22
-
-
Save gabrielfeo/92befe0501cfbfad6722cd787c0a0ca2 to your computer and use it in GitHub Desktop.
Have gpg fetch key password using 1Password CLI
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/bin/env bash | |
| # Have gpg fetch key password using 1Password CLI. | |
| # | |
| # 1. Add to ~/.gnupg/gpg-agent.conf: | |
| # | |
| # pinentry-program <path to this file> | |
| # | |
| # 2. Export OP_GPG_PASSWORD_ENTRY_<key-id>=<key-password-reference> variables: | |
| # | |
| # export OP_GPG_PASSWORD_ENTRY_22129EAMD723DCC8=op://Employee/asklnfnf234njndsf9asd09asd/password | |
| # export OP_GPG_PASSWORD_ENTRY_ACCOUNT_22129EAMD723DCC8=AcmeInc | |
| # export OP_GPG_PASSWORD_ENTRY_34532D9A9ASKMNC3=op://Employee/q9wardafja8s9f8sdfshdfhsfd/password | |
| # export OP_GPG_PASSWORD_ENTRY_ACCOUNT_34532D9A9ASKMNC3=my.1password.eu | |
| # | |
| # The variables may also be placed in a file that this script can source. The file's path should be in | |
| # the PIN_ENTRY_OP_ENV_FILE variable. If empty, defaults to ~/.pinentry-op.env. | |
| # | |
| # You may have to kill the agent for it take effect: | |
| # | |
| # gpg-connect-agent killagent | |
| # | |
| # If you ever want to change this file, export LOG=<some-path> to see how gpg runs it. | |
| # | |
| # Derived from https://gist.github.com/wmudge/422660bcb3dbd767ad4219a5d471ea38 | |
| : ${PINENTRY_OP_ENV_FILE:=~/.pinentry-op.env} | |
| : ${PINENTRY_OP_LOG_FILE:=~/.gnupg/pinentry-op.log} | |
| function log { | |
| echo "$(date "+%Y-%m-%dT%H:%M:%S") [pinentry-op] $@" >> "$PINENTRY_OP_LOG_FILE" | |
| } | |
| echo "OK" | |
| while read cmd val; do | |
| log "$cmd $val" | |
| case "$cmd" in | |
| \#*) | |
| ;; | |
| SETDESC) | |
| ls "$PINENTRY_OP_ENV_FILE" &> /dev/null && source "$PINENTRY_OP_ENV_FILE" | |
| key_id="$(echo "$val" | sed -E 's/.*ID ([A-Z0-9]+).*/\1/')" | |
| key_var="OP_GPG_PASSWORD_ENTRY_$key_id" | |
| key_account_var="OP_GPG_PASSWORD_ENTRY_ACCOUNT_$key_id" | |
| log "key ID $key_id: $key_var=${!key_var}, $key_account_var=${!key_account_var:-<unset>}" | |
| OP_GPG_PASSWORD_ENTRY_CURRENT="${!key_var}" | |
| OP_GPG_PASSWORD_ACCOUNT_CURRENT="${!key_account_var}" | |
| ;; | |
| GETPIN) | |
| COMMAND="op read --account=$OP_GPG_PASSWORD_ACCOUNT_CURRENT $OP_GPG_PASSWORD_ENTRY_CURRENT" | |
| log "Executing '$COMMAND'" | |
| echo "D $($COMMAND 2>> "$PINENTRY_OP_LOG_FILE")" | |
| ;; | |
| SETERROR) | |
| echo "ERR 31 Invalid passphrase" | |
| ;; | |
| BYE) | |
| exit 0 | |
| ;; | |
| *) | |
| echo | |
| ;; | |
| esac | |
| echo "OK" | |
| done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment