Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save meysam81/7c9fe8f16df4bfe70483cbe398f7ce8d to your computer and use it in GitHub Desktop.
Save meysam81/7c9fe8f16df4bfe70483cbe398f7ce8d to your computer and use it in GitHub Desktop.
#!/bin/bash
# Function to display help message
usage() {
echo "Usage: $0 --email <email> [--name <name>] [--passphrase <passphrase>]"
echo "Generate an Ed25519 GPG private key non-interactively."
echo ""
echo "Options:"
echo " --email Email address for the GPG key (required)"
echo " --name Name for the GPG key (optional, defaults to email)"
echo " --passphrase Passphrase for the key (optional, empty for no passphrase)"
echo " --help Display this help message"
exit 1
}
# Parse command-line arguments
EMAIL=""
NAME=""
PASSPHRASE=""
while [[ $# -gt 0 ]]; do
case "$1" in
--email)
EMAIL="$2"
shift 2
;;
--name)
NAME="$2"
shift 2
;;
--passphrase)
PASSPHRASE="$2"
shift 2
;;
--help)
usage
;;
*)
echo "Unknown option: $1"
usage
;;
esac
done
# Validate email
if [ -z "$EMAIL" ]; then
echo "Error: --email is required."
usage
fi
# Set default name to email if not provided
if [ -z "$NAME" ]; then
NAME="$EMAIL"
fi
# Create temporary configuration file for GPG key generation
TEMP_CONFIG=$(mktemp)
cat >"$TEMP_CONFIG" <<EOF
Key-Type: eddsa
Key-Curve: Ed25519
Key-Usage: sign
Subkey-Type: ecdh
Subkey-Curve: Curve25519
Subkey-Usage: encrypt
Name-Real: $NAME
Name-Email: $EMAIL
Expire-Date: 0
EOF
# Add passphrase or no-protection based on input
if [ -n "$PASSPHRASE" ]; then
echo "Passphrase: $PASSPHRASE" >>"$TEMP_CONFIG"
else
echo "%no-protection" >>"$TEMP_CONFIG"
fi
echo "%commit" >>"$TEMP_CONFIG"
# Generate the GPG key non-interactively
if ! gpg --batch --generate-key "$TEMP_CONFIG" 2>gpg_error.log; then
echo "Error generating GPG key."
cat gpg_error.log
rm -f gpg_error.log "$TEMP_CONFIG"
exit 1
fi
# Clean up
rm -f gpg_error.log "$TEMP_CONFIG"
echo "GPG Ed25519 key generated for $EMAIL"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment