I need to retrieve the attributes of a certificate that is stored in the keychain on my Mac from the command line. I can collect them manually from the Keychain Access app, but I want to do that with a script.
I used the security
command to get a certificate and "grep" to inspect the "subject" section:
security find-certificate -c "Apple Development" login.keychain | grep "subj"
and then got the following output (some omitted by "...").
"subj"<blob>=0x3081943...553 "0\201\2241\0320\03...02US"
In the output above, what format is the data following "subj"<blob>=
and how can I parse it? I found that decoding the first half of the hexadecimal sequence(0x30...) with UTF-8 yields the second half of the string (0\201...), but I don't know what 0\201\2241\...
means. I have tried other character codes, but they just give me garbled characters.
As for the format, the certificates are stored in DER/PEM format, which is a representation of ASN.1 encoded data. What you see in the output is the hexadecimal representation of the ASN.1 binary data. The blob indicates that the value or attribute is stored as binary data.
As for exporting (for certificates), I would highly recommend combining security
with openssl
as follows:
security find-certificate -p -c "Apple Development" login.keychain | openssl x509 -noout -subject
The -p
option in the security command exports the found certificate in PEM format, which is a format openssl can use. You can then pipe the PEM data into the openssl
command, where one can easily extract the subject using the -subject
option.
You can check out both the man page of security and the man page of openssl x509.