Skip to content

Instantly share code, notes, and snippets.

@SeanPesce
Last active July 23, 2025 14:11
Show Gist options
  • Save SeanPesce/1c621e716459f0f8651000cf015b2362 to your computer and use it in GitHub Desktop.
Save SeanPesce/1c621e716459f0f8651000cf015b2362 to your computer and use it in GitHub Desktop.
Shell script to check whether a certificate/public key and private key belong to the same key pair
#!/bin/bash
# Author: Sean Pesce
#
# This script checks whether a certificate/public key and private key belong to the same key pair
# Check if correct number of arguments is provided
if [ "$#" -ne 2 ]; then
echo "Usage: $0 <private_key.pem> <certificate_or_public_key.pem>"
exit 1
fi
PRIVATE_KEY=$1
CERT_OR_PUBKEY=$2
# Temporary files to store extracted public keys
PRIVATE_KEY_PUB=/tmp/private_key_pub.pem
CERT_PUB=/tmp/cert_pub.pem
# Determine the private key algorithm
KEY_ALG=''
if openssl rsa -in "$PRIVATE_KEY" -check -noout 2>/dev/null >/dev/null; then
echo "[INFO] RSA private key detected."
KEY_ALG='rsa'
elif openssl ec -in "$PRIVATE_KEY" -check 2>/dev/null >/dev/null; then
echo "[INFO] ECDSA private key detected."
KEY_ALG='ec'
elif openssl pkey -in "$PRIVATE_KEY" -text 2>/dev/null >/dev/null; then
KEY_ALG='pkey'
KEY_ALG_TMP="$(openssl pkey -in "$PRIVATE_KEY" -text -noout 2>/dev/null | grep -i private | head -n1 | cut -d ' ' -f 1)"
echo "[INFO] $KEY_ALG_TMP private key detected."
else
echo "[ERROR] Unknown or unsupported private key type: $PRIVATE_KEY"
exit 1
fi
# Extract the public key from the private key
openssl "$KEY_ALG" -in "$PRIVATE_KEY" -pubout > "$PRIVATE_KEY_PUB" 2>/dev/null
if [ $? -ne 0 ]; then
echo "[ERROR] Failed to read private key from '$PRIVATE_KEY'"
exit 1
fi
# Determine if the second file is a certificate or public key
if openssl x509 -in "$CERT_OR_PUBKEY" -noout 2>/dev/null; then
# If it's a certificate, extract the public key
openssl x509 -in "$CERT_OR_PUBKEY" -pubkey -noout -out "$CERT_PUB" 2>/dev/null
elif openssl "$KEY_ALG" -pubin -in "$CERT_OR_PUBKEY" -noout 2>/dev/null; then
# If it's already a public key, copy it directly
cp "$CERT_OR_PUBKEY" "$CERT_PUB"
else
echo "[ERROR] Not a valid certificate or public key: $CERT_OR_PUBKEY"
rm -f "$PRIVATE_KEY_PUB"
exit 1
fi
# Compare the public keys
if diff -B -q "$PRIVATE_KEY_PUB" "$CERT_PUB" >/dev/null; then
echo "The private key matches the certificate/public key."
else
echo "The private key does NOT match the certificate/public key."
fi
# Clean up temporary files
rm -f "$PRIVATE_KEY_PUB" "$CERT_PUB"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment