Scripting Help: Removing a specific certificate from the keychain

mbezzo
Contributor III

Hi All,
I've been poking around but haven't found a solution for my unique situation. Basically, I need to remove an old certificate that will have the same exact name as a newer certificate from the system keychain. The only difference is one is SHA-1, the other is SHA-256. I can't seem to find a way to programmatically read the "Signature Algorithm" field. It looks like openSSL can do this with a line like:

openssl x509 -noout -text -in /path/to/yourcert.crt

But since these certs are in the keychain, I don't think there's a way to pass the path? Maybe I'm missing something?

Anyone able to point me in the right direction?

Thanks!
Matt

3 REPLIES 3

mm2270
Legendary Contributor III

Assuming you can actually get the security command to operate on both certificates, given they have the same name (I'm not sure on that), you can export the certificate into PEM form using this:

/usr/bin/security find-certificate -a -c "Common Name" -p > /tmp/certname.pem

From there, you can use openssl to tell it to expect a PEM certificate to read in and examine the signature algorithm

/usr/bin/openssl x509 -noout -text -inform PEM -in /tmp/certname.pem | awk '/Signature Algorithm:/{print $NF; exit}'

The above should print something like sha256WithRSAEncryption or whatever it is.

The biggest problem I think you might face is, even after determining which cert is the old one, actually getting the security command to delete it successfully. My experience with it is that deleting a cert when there is more than one with the same name fails, at least when specifying it by the common name, which makes sense, since there are multiples with the same name. You might need to first capture the SHA-1 for each cert into a variable using something like

SHA-1=$(/usr/bin/security find-certificate -a -c "Common Name" -Z | awk '/SHA-1/{print $NF}')

Then use

/usr/bin/security delete-certificate -Z "$SHA-1"

Give the above steps a try. Of course, you'll need to somehow keep track of which cert is being exported for examination as it goes over each one in a loop perhaps and then try deleting the one with the older SHA-1.

Hope all the above helps a little. Good luck.

mbezzo
Contributor III

Thanks @mm2270 - I think you're on to something here. I'll play around and see how it goes, it's definitely more complex than I'd like... but should be doable!

Thank you!
Matt

swallace
Contributor

I know this is a little late to the party, but just experienced the same cert issues at my new job. Here's what I used (similar to those commenting above). It looks at sha-1 and has some logic to determine if it has the new one before removing the old one. Worked out really well for me. Good luck!
b3cd0570dc794f3f95f8543b844e0406