Skip to content

Instantly share code, notes, and snippets.

@martin-braun
Created June 4, 2025 21:05
Show Gist options
  • Save martin-braun/ffda926798d6a9334d92ab6e867252ce to your computer and use it in GitHub Desktop.
Save martin-braun/ffda926798d6a9334d92ab6e867252ce to your computer and use it in GitHub Desktop.

SSH Store

Secure your secrets using your SSH agent.

sshstore() {
store="$HOME/.ssh/store"
if [ "$1" = "-l" ] || [ "$1" = "--list" ]; then
find "$store" -mindepth 1 -maxdepth 1 -type f -exec basename {} \; | cut -d. -f -2 | xargs echo
return 0
fi
identity="$HOME/.ssh/id_rsa"
if [ $# -lt 1 ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
echo "Loads or saves a symmetrically encrypted data from/to the SSH store using $identity." >&2
echo "Usage: sshstore [-h, --help] [-l, --list] name [-s data] [-s < data] > data" >&2
echo '' >&2
echo "The private identity key within the SSH agent is used to sign the given name." >&2
echo "The resulting signature is used to symmetrically encrypt or decrypt the data." >&2
echo "Note: This function is backward compatible with older identities and encryption methods." >&2
echo '' >&2
return 129
fi
sign() { echo "$1" | ssh-keygen -Y sign -n store -f "$2" -q; }
v=1
name="$(echo "$1" | tr -cd '[:alnum:]_-')"
mkdir -p "$store"
if [ "$2" = "-s" ]; then
data="$3"
test -n "$data" || {
stdin=$(mktemp) && timeout 1 cat > "$stdin" && data="$(cat "$stdin")"
rm "$stdin"
}
test -n "$data" || { echo Missing data to encryt. >&2 && return 1; }
rm "$store/$name.*" 2> /dev/null
echo "$data" | gzip | openssl enc -e -aes-256-cbc -md sha512 -pbkdf2 -iter 69420 -k "$(sign "$name" "$identity")" > "$store/$name.$v"
data=""
fi
test -s "$store/$name.$v" && openssl enc -d -aes-256-cbc -md sha512 -pbkdf2 -iter 69420 -k "$(sign "$name" "$identity")" < "$store/$name.$v" | gzip -d && return 0
# test -s "$store/$name.1" && openssl enc -d -aes-256-cbc -md sha512 -pbkdf2 -iter 69420 -k "$(sign "$name" "$HOME/.ssh/id_rsa")" < "$store/$name.1" | gzip -d && return 0
echo "Could not find $name to decrypt." >&2 && return 1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment