Skip to content

Instantly share code, notes, and snippets.

@bearkfear
Last active October 23, 2025 17:44
Show Gist options
  • Select an option

  • Save bearkfear/fa14c6feeb14c89f740e1ff6773b7d61 to your computer and use it in GitHub Desktop.

Select an option

Save bearkfear/fa14c6feeb14c89f740e1ff6773b7d61 to your computer and use it in GitHub Desktop.
autconfig gpg in github - chmod +x ./run.sh && ./run.sh
#!/bin/bash
# Prompt for the GitHub token
read -p "Enter your GitHub token: " GITHUB_TOKEN
# Prompt for GitHub username
read -p "Enter your GitHub username: " GITHUB_USER
# Get user real name
read -p "Enter your real name: " REAL_NAME
# Prompt for the GitHub email to ensure it matches in Git and GPG
read -p "Enter the email associated with your GitHub account: " GITHUB_EMAIL
# Set the Git user email to match the GitHub email
git config --global user.email "$GITHUB_EMAIL"
# Check if a GPG key with this email already exists
if ! gpg --list-secret-keys --keyid-format LONG | grep -q "$GITHUB_EMAIL"; then
# Generate a GPG key with the provided email
gpg --batch --gen-key <<EOF
Key-Type: RSA
Key-Length: 4096
Name-Real: $REAL_NAME
Name-Email: $GITHUB_EMAIL
Expire-Date: 1y
%no-protection
EOF
echo "Generated a new GPG key for email: $GITHUB_EMAIL."
else
echo "A GPG key already exists for email: $GITHUB_EMAIL."
fi
# Extract the GPG key ID associated with the email
GPG_KEY_ID=$(gpg --list-secret-keys --keyid-format LONG "$GITHUB_EMAIL" | grep sec | awk '{print $2}' | cut -d'/' -f2)
# Export GPG key for GitHub
GPG_PUBLIC_KEY=$(gpg --armor --export $GPG_KEY_ID)
# Install jq if not installed: sudo apt-get install jq
# Add GPG key to GitHub using the API with proper JSON formatting
curl -H "Authorization: token $GITHUB_TOKEN" \
-H "Accept: application/vnd.github+json" \
-X POST \
-d "$(jq -n --arg key "$GPG_PUBLIC_KEY" '{armored_public_key: $key}')" \
https://api.github.com/user/gpg_keys
# Configure Git to use the GPG key for signing commits
git config --global user.signingkey "$GPG_KEY_ID"
git config --global commit.gpgSign true
echo "GPG key added to GitHub, and Git is configured to sign commits by default with email: $GITHUB_EMAIL."
@bearkfear
Copy link
Author

Must have installed GPG and JQ

brew install gpg
brew install jq

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment