add script to validate keys

This commit is contained in:
Lucy 2025-04-05 12:56:58 +02:00
parent cb49027fb9
commit b5fdbdacdc

33
check_key.sh Executable file
View file

@ -0,0 +1,33 @@
#!/bin/bash
# Input file containing the SSH public keys
key_file=$1
# Read the file line by line
while IFS= read -r line; do
# Skip empty lines
if [ -z "$line" ]; then
continue
fi
# Trim leading/trailing whitespace (preserving the key and comment structure)
trimmed_line=$(echo "$line" | xargs)
# Validate the SSH key format:
# Starts with ssh-<type>, followed by base64-encoded data, and an optional comment
echo $key_file
if ! echo "$trimmed_line" | grep -Eq '^ssh-(rsa|ed25519|dss|ecdsa) [A-Za-z0-9+/=]+ ?.*$'; then
echo "Invalid key format: $line"
exit 1
fi
# Ensure there is only one key on the line: a valid key should only have one space separating key data from the comment
space_count=$(echo "$trimmed_line" | grep -o ' ' | wc -l)
if [ "$space_count" -gt 2 ]; then
echo "Invalid: Multiple keys found on the same line"
exit 1
fi
done < "$key_file"
echo "All keys are valid and correctly formatted."