diff --git a/bin/get_ssh_key b/bin/get_ssh_key index 65a6ee0..2ba832f 100755 --- a/bin/get_ssh_key +++ b/bin/get_ssh_key @@ -1,23 +1,56 @@ #!/usr/bin/env bash set -euo pipefail +cd "$(dirname "$0")" + # This file contains functions that make it easier to for me to -# access my SSH and GPG keys on a new machine. +# access my SSH a new machine. # Example usage: -# $ get_ssh_key "id_rsa_raspi" +# $ get_ssh_key "Personal" "git commit signing key" + +vault_name="${1:-}" +key_name="${2:-}" -key_name="${1:-}" +if [ -z "$vault_name" ]; then + echo "vault_name not passed as 1st argument. Nothing was done." + exit 1 +fi if [ -z "$key_name" ]; then - echo "key_name not passed as argument. Nothing was done." + echo "key_name not passed as 2nd argument. Nothing was done." exit 1 fi -key_path="$HOME/.ssh/$key_name" +private_key_path="id_ed25519" +public_key_path="id_ed25519.pub" -if [ -f "$key_path" ]; then - echo "$key_path already exists. Nothing was done to it." +if [ -f "$private_key_path" ]; then + echo "$private_key_path already exists. Nothing was done." exit 2 fi -op document get "$key_name" >"$key_path" && chmod 400 "$key_path" +if [ -f "public_key_path" ]; then + echo "public_key_path already exists. Nothing was done." + exit 2 +fi + +op read \ + --out-file "$private_key_path" \ + "op://$vault_name/$key_name/private key?ssh-format=openssh" + +# Apply workaround for: +# https://1password.community/discussion/142733/bad-characters-when-exporting-ssh-private-key-via-cli +private_key_content="$(cat "$private_key_path")" +printf "%s" "$private_key_content" | tr -d '\r' > "$private_key_path" + +op read \ + --out-file "$public_key_path" \ + "op://$vault_name/$key_name/public key" + +# Add a comment (if it exists) +comment="$(op read "op://Personal/git commit signing key/comment" 2>/dev/null || true)" +if [ -n "$comment" ]; then + pubkey_content="$(tr -d '\n' < "$public_key_path")" + true > "$public_key_path" + printf "%s %s\n" "$pubkey_content" "$comment" > "$public_key_path" +fi