Skip to content

Instantly share code, notes, and snippets.

@dade80vr
Created November 1, 2018 21:12
Show Gist options
  • Save dade80vr/ddefa7ea4481d88deac2561914e4f52a to your computer and use it in GitHub Desktop.
Save dade80vr/ddefa7ea4481d88deac2561914e4f52a to your computer and use it in GitHub Desktop.
Bash script to check if a certificate and a private key match
#!/bin/bash
cert=$1
key=$2
if [[ $# -eq 0 ]]
then
echo "Arguments not given. Usage: ./checkcert.sh CERTIFICATE.crt PRIVKEY.key"
else
crthash=$(openssl x509 -noout -modulus -in "$cert" | openssl md5)
echo $cert $crthash
keyhash=$(openssl rsa -noout -modulus -in "$key" | openssl md5)
if [ "$keyhash" = "$crthash" ]
then
keytest=$(openssl rsa -in "$key" -check -noout)
echo $key $keyhash
echo "---- "$keytest" ----"
else
echo "!!!! Invalid key for given cert !!!!"
fi
fi
@franklapolito
Copy link

made a few edits to expand on the above:

#!/bin/bash

cert="demo_poc_atscale-se-demo_com.crt"
key="DEMO.POC.ATSCALE-SE-DEMO.COM-clear.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

@dade80vr
Copy link
Author

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment