Working with openssl to extract information from a pkcs12 certificate

Sonic84 picture Sonic84 · Dec 14, 2011 · Viewed 97k times · Source

I would like some help with the openssl command. I need to automate the retrieval of the subject= line in a pkcs12 certificate for a script I'm working on.

I've used openssl to view the contents of the Identity/Certificate:

openssl pkcs12 -info -in /Users/[user]/Desktop/ID.pfx

But I am prompted three times for the password. I used -passin to eliminate one of the password prompts, but I am still being prompted for the PEM pass phrase and verification entry.
I need to figure out a way to pass ${password} to the other two password challenges or have the scrip issue a ctl-c. The piece of info I need is outputted to the stdout before the second password prompt.

Any help would be appreciated!

Obviously I gutted the certificate output for this post.... but you should get the idea of what I'm seeing:

bash-3.2#  openssl pkcs12 -info -in /Users/[user]/Desktop/ID.pfx -passin pass:${password}
MAC Iteration 2048
MAC verified OK
PKCS7 Encrypted data: pbeWithSHA1And40BitRC2-CBC, Iteration 2048
Certificate bag
Bag Attributes
    localKeyID: ****
    friendlyName: ****
subject=****
issuer=****
-----BEGIN CERTIFICATE-----
::HASH REMOVED::
-----END CERTIFICATE-----
PKCS7 Data
Shrouded Keybag: ****
Bag Attributes
    localKeyID: **** 
    friendlyName: ****
Key Attributes: <No Attributes>

Enter PEM pass phrase:
Verifying - Enter PEM pass phrase:

-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: 

::HASH REMOVED::
-----END RSA PRIVATE KEY-----
bash-3.2# 

Answer

Alfie Hanssen picture Alfie Hanssen · Apr 23, 2013

Try this:

$ openssl pkcs12 -in ~/cert.p12 -nodes \
    -passin pass:"my password" | openssl x509 -noout -subject

Or this for the common name (ruby to strip trailing whitespace):

$ openssl pkcs12 -in ~/cert.p12 -nodes \
    -passin pass:"my password" | openssl x509 -noout -subject \
    | awk -F'[=/]' '{print $6}'`.strip`