Skip to content

Instantly share code, notes, and snippets.

@franklapolito
Forked from dade80vr/checkcert.sh
Last active March 14, 2025 19:25
Show Gist options
  • Save franklapolito/a043d4e3a13e3cfad2dfa4a4c64a996a to your computer and use it in GitHub Desktop.
Save franklapolito/a043d4e3a13e3cfad2dfa4a4c64a996a to your computer and use it in GitHub Desktop.
Bash script to check if a certificate and a private key match
#!/bin/bash
#Developed by: Frank Lapolito; Date: 3/14/25
# to run, first execute chmod +x checkcert.sh
# next, to execute the file run ./checkcert.sh
cert="<cert>.crt"
key="<key>.key"
echo "Starting script..." #Added line for debugging.
if [[ $# -eq 2 ]]; then
cert="$1"
key="$2"
echo "Arguments provided: cert=$cert, key=$key" #Added line for debugging.
elif [[ $# -eq 0 ]]; then
echo "Using default cert and key files."
else
echo "Usage: $0 [CERTIFICATE.crt] [PRIVKEY.key] (or use defaults)"
exit 1
fi
if [[ ! -f "$cert" ]]; then
echo "Error: Certificate file '$cert' not found."
exit 1
fi
if [[ ! -f "$key" ]]; then
echo "Error: Private key file '$key' not found."
exit 1
fi
crthash=$(openssl x509 -noout -modulus -in "$cert" | openssl md5)
if [[ $? -ne 0 ]]; then
echo "Error: Failed to process certificate."
exit 1
fi
echo "Certificate: $cert, Hash: $crthash"
keyhash=$(openssl rsa -noout -modulus -in "$key" | openssl md5)
if [[ $? -ne 0 ]]; then
echo "Error: Failed to process private key."
exit 1
fi
if [[ "$keyhash" = "$crthash" ]]; then
keytest=$(openssl rsa -in "$key" -check -noout)
if [[ $? -ne 0 ]]; then
echo "Error: Private key check failed."
exit 1
fi
echo "Private Key: $key, Hash: $keyhash"
echo "---- $keytest ----"
echo "Certificate and private key match and are valid."
else
echo "Error: Invalid private key for given certificate."
exit 1
fi
exit 0
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment