Skip to content

Instantly share code, notes, and snippets.

@josefglatz
Last active April 1, 2023 22:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save josefglatz/c9802f7bed054fb23c7054265e7fda42 to your computer and use it in GitHub Desktop.
Save josefglatz/c9802f7bed054fb23c7054265e7fda42 to your computer and use it in GitHub Desktop.
Cheatsheet: How to extract certificate and private key from a PFX file

How to extract certificate and private key from a PFX file

Given PFX file

stern-domain-at.pfx (optionally secured with passphrase)

Openssl needs to be installed

Commands

Export certificate

openssl pkcs12 -in stern-domain-at.pfx -nokeys -out cert.pem

Export private key (passphrase will not be removed)

openssl pkcs12 -in stern-domain-at.pfx -nocerts -out key.pem -nodes

Remove passphrase from the exported private key

openssl rsa -in key.pem -nocerts -out server.key

Final results

  • cert.pem contains a number of certificates (Public, Intermidiate, Root)
  • key.pem contains private key (secured by passphrase)
  • server.key contains the private key without passphrase

Check if your certificate matches the key file

You won't find a modulus if your private key or your certificate is signed with ECC (Elliptic Curve Cryptography)!

Run following commands and compare the output. The modulus is the same if they match.

openssl rsa -noout -modulus -in server.key
openssl x509 -noout -modulus -in cert.pem

Alternative use diff

diff <(openssl rsa -noout -modulus -in server.key) <(openssl x509 -noout -modulus -in cert.pem)

Check if your Certificate Sign Request matches

openssl req -noout -modulus -in yourCertificateSignRequestFile.csr
@Digital-Platform-Services

-Running "openssl rsa -in key.pem -nocerts -out server.key" triggered the message: unknown option -nocerts
-Remove -nocerts option from the command and re-ran.. with success: writing RSA key
-Thanks for posting this cheet sheet : )

@ErezBinyamin
Copy link

Offering a helpfull all in one script!

main() {
	local CERT=${1}
	[ -f ${CERT} ] || return 1

	# Export certificate
	openssl pkcs12 -in ${CERT} -nokeys -out cert.pem

	# Export private key (passphrase will not be removed)
	openssl pkcs12 -in ${CERT} -nocerts -out key.pem -nodes

	# Remove passphrase from the exported private key
	openssl rsa -in key.pem -out server.key

	# Check if your certificate matches the key file
	diff <(openssl rsa -noout -modulus -in server.key) <(openssl x509 -noout -modulus -in cert.pem)
	return $?
}
main $@

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment