Find a matching certificate and key from a list of keys

Some weeks ago I generated two certificate signing requests and yesterday went to install the new certs. There was only one little big problem. I only had the private key for one of the certificates. Obviously, the certificate (the public key) is useless without the corresponding private key, but the box which had the key and the csr for the second cert, only had the csr for the first cert and no private key. Perplexed, I thought that perhaps I had created the other key on a different machine, but didn't know which. The quickest solution was to locate all the private keys in the backups and see which one matches the cert.

But how to match them? Easy. Extract the modulus, calculate and compare the checksums. Openssl can do both.

First, on one of the backup servers, ran the following:

for key in $(sudo locate *.key); do
  echo $key >> key.list
  openssl rsa -noout -modulus -in  $key | openssl sha1 >> key.list

This gave me a list of key file names and their checksums.

Then calculated the certificate checksum:

openssl x509 -noout -modulus -in my.crt | openssl sha1

Then searched the list for a matching private key:

grep -B1 ab7d44d75744450bef85b0c44021e72350056203 key.list

Hmm, none of the keys matched. I then pulled my shell history file from backups, which showed I had overridden the first key with the second. Duh! No way to recover, so had to issue a new key and csr and request re-issuance of the certificate.

Leave a comment

NOTE: Enclose quotes in <blockquote></blockquote>. Enclose code in <pre lang="LANG"></pre> (where LANG is one of these).