Skip to content

Instantly share code, notes, and snippets.

@jonuwz
Last active December 29, 2015 05:29
Show Gist options
  • Save jonuwz/7621749 to your computer and use it in GitHub Desktop.
Save jonuwz/7621749 to your computer and use it in GitHub Desktop.
GPG key creation and retrieval
#!/bin/bash
# This makes sure that a pgp public key for a given email exists.
# If it already exists it prints the info, if not it creates one, then prints the info
# If we create the keypair, the secret is exported and removed from the keyring
# Minimum requirement is a key
if [[ -z "$1" ]];then
echo -e "\nUsage\n\t$(basename $0) key [ name ] [ comment ]\n\n"
exit 1
fi
# Sane defaults
key=$1
name=${2:-${key%%@*}}
comment=${3:-${key%%@*}}
KEY_TYPE=${KEY_TYPE:-RSA}
KEY_LENGTH=${KEY_LENGTH:-2048}
SUBKEY_TYPE=${SUBKEY_TYPE:-RSA}
SUBKEY_LENGTH=${KEY_LENGTH:-2048}
EXPIRE=${EXPIRE:-0}
key_details () {
local key=$1
output="$(gpg --fingerprint --with-colons --list-public-keys -a "$key" 2>/dev/null)"
if (( $? == 0 ));then
echo "$output" | awk -F: '{
key[$1]=$5
if ($1=="pub") {
key["name"]=key["comment"]=key["key"]=$10
sub(/ \(.*/,"",key["name"])
gsub(/.*\(|\).*/,"",key["comment"])
gsub(/.*<|>.*/,"",key["key"])
}
if ($1=="fpr") {
key["fpr"]=$10
}
}
END {
print "key="key["key"]";name="key["name"]";comment="key["comment"]";keyid="key["pub"]";subkeyid="key["sub"]";fingerprint="key["fpr"]
} '
return 0
else
return 1
fi
}
export_key () {
local key=$1
local keytype=${2:-public}
[[ -d ~/exported_pgpkeys ]] || mkdir ~/exported_pgpkeys
output="$(gpg --yes --batch --output ~/exported_pgpkeys/"${key}.${keytype}" --armor --export-${keytype}-key "$key" 2>&1)"
if (( $? == 0 ));then
echo "The $keytype key for $key has been exported to exported_pgpkeys/${key}.${keytype}" >&2
else
echo "$output"
return 1
fi
}
delete_key () {
local fingerprint=$1
local keytype=${2:-public}
case $keytype in
secret|private) keytype=secret;option="--delete-secret-keys";;
public) keytype=public;option="--delete-keys";;
esac
output="$(gpg --yes --batch --delete-${keytype}-keys $fingerprint)"
if (( $? != 0 ));then
echo "$output"
return 1
fi
}
create_key () {
# Create the key
local key=$1
local name=$2
local comment=$3
error="$(cat <<-EOF | gpg --gen-key --batch - 2>&1 1>/dev/null
Key-Type: ${KEY_TYPE}
Key-Length: ${KEY_LENGTH}
Key-Usage: sign
Subkey-Type: ${SUBKEY_TYPE}
Subkey-Length: ${SUBKEY_LENGTH}
Subkey-Usage: encrypt
Name-Real: $name
Name-Comment: $comment
Name-Email: $key
Expire-Date: ${EXPIRE}
%commit
EOF
)"
if (( $? == 0 ));then
details=$(key_details "$key")
if (( $? == 0 ));then
echo $details
fingerprint=${details##*fingerprint=}
export_key "$key" secret || return 1
delete_key "$fingerprint" secret || return 1
return 0
else
return 1
fi
else
echo "$error" >&2
return 1
fi
}
key_details "$key" || create_key "$key" "$name" "$comment"
exit $?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment