Based on commands given in Verifying that a Private Key Matches a Certificate (originally from The Apache SSL FAQ) it's possible to build a small bash script that iterates through all *.key files in the folder and compares the modulus portion of the certificate with every key at once.
My findkey.sh takes the certificate's filename as a command line argument & prints the matches.
#!/bin/bash
cert=$1
crthash=$(openssl x509 -noout -modulus -in "$cert" | openssl md5)
echo $cert $crthash
for file in *.key; do
[ -e "$file" ] || continue
keyhash=$(openssl rsa -noout -modulus -in "$file" | openssl md5)
if [ "$keyhash" = "$crthash" ]
then
keytest==$(openssl rsa -in "$file" -check -noout)
echo $file $keyhash $keytest
fi
done
I created some key pairs testN.key / testN.crt and tested my script, which seems to do the job:
./findkey.sh test4.crt
test4.crt (stdin)= 8e30eac60ff8d3c5b1c9bee7e79774bb
test4.key (stdin)= 8e30eac60ff8d3c5b1c9bee7e79774bb =RSA key ok
It doesn't matter if there's some certificates (or certificate requests) among the keys, because even if named incorrectly as *.key the openssl rsa -modulus would give unable to load Private Key error instead of the modulus for the certificate. In addition, the end of the line tells whether the key is consistent, to prevent fake private keys. You only need this script & OpenSSL installed.
You may use a certificate key matcher tool to check whether your private key matches the certificate like the following one:
https://www.sslshopper.com/certificate-key-matcher.html
Moreover if you want to use the openssl commandline tool, the followings would be a suggested for reading:
- https://kb.wisc.edu/middleware/page.php?id=4064
- http://httpd.apache.org/docs/2.0/ssl/ssl_faq.html#verify