Перейти к содержимому

Как из pfx получить cer и key

  • автор:

Вики IT-KB

Как извлечь сертификат и закрытый ключ из PFX-файла с помощью OpenSSL

Бывают ситуации, когда имеется PFX-контейнер, защищённый паролем и нам известен этот пароль. При этом необходимо извлечь из этого PFX-файла данные сертификата и закрытого ключа в формате PEM. Рассмотрим пример того, как выполнить эту задачу с помощью утилиты openssl.

Шаг 1. Извлечение сертификата

Распаковываем сертификат. При выполнении будет запрошен пароль (Import Password), которым защищён PFX контейнер. Вводим пароль.

Шаг 2. Извлечение закрытого ключа

Распаковываем закрытый ключ. При выполнении будет запрошен пароль (Import Password), которым защищён PFX контейнер. Вводим пароль. Далее будет запрошена новая парольная фраза (PEM pass phrase), которой будут зашифрованы данные закрытого ключа при выгрузке. Два раза вводим парольную фразу защиты закрытого ключа.

Шаг 3. Дешифровка закрытого ключа

Выполняем дешифровку закрытого ключа. При запросе вводим парольную фразу (PEM pass phrase), заданную на шаге 2.

В результате имеем два файла my_ru.crt (сертификат) и my_ru.key (дешифрованный закрытый ключ) в формате PEM, которые можно использовать для настройки разных сервисов, например, для включения SSL на веб-сервере на базе Linux. Файл my_ru_encr.key в большинстве случаев не требуется и может быть удалён.

Проверено на следующих конфигурациях:

Версия OpenSSL
OpenSSL 1.0.2d-fips 9 Jul 2015

Автор первичной редакции:
Алексей Максимов
Время публикации: 14.12.2021 18:24

How to extract key, cert and ca cert from a PFX file extension

Sam A

The PKCS#12 or PFX format is a binary format for storing the server certificate, any intermediate certificates, and the private key in one encryptable file. PFX files usually have extensions such as . pfx and . p12. PFX files are typically used on Windows machines to import and export certificates and private keys

Now that you know what is this file how can extract key, cert and ca cert from this file ?

Run the command below to extract the client certificate key

Run the command below to extract the client certificated

Run the command below to extract the ca certificate

Now that you have all these three files whats the next step ?

In cases that you only have to two upload options one for key and one for cert you should add the ca cert file to the end of client cert and upload the new file as client cert.

Convert .pfx to .cer

Is it possible to convert a .pfx (Personal Information Exchange) file to a .cer (Security Certificate) file? Unless I’m mistaken, isn’t a .cer somehow embedded inside a .pfx? I’d like some way to extract it, if possible.

8 Answers 8

PFX files are PKCS#12 Personal Information Exchange Syntax Standard bundles. They can include arbitrary number of private keys with accompanying X.509 certificates and a certificate authority chain (set certificates).

If you want to extract client certificates, you can use OpenSSL’s PKCS12 tool.

The command above will output certificate(s) in PEM format. The «.crt» file extension is handled by both macOS and Window.

You mention «.cer» extension in the question which is conventionally used for the DER encoded files. A binary encoding. Try the «.crt» file first and if it’s not accepted, easy to convert from PEM to DER:

the simple way I believe is to import it then export it, using the certificate manager in Windows Management Console.

If you’re working in PowerShell you can use something like the following, given a pfx file InputBundle.pfx, to produce a DER encoded (binary) certificate file OutputCert.der:

Newline added for clarity, but you can of course have this all on a single line.

If you need the certificate in ASCII/Base64 encoded PEM format, you can take extra steps to do so as documented elsewhere, such as here: https://superuser.com/questions/351548/windows-integrated-utility-to-convert-der-to-pem

If you need to export to a different format than DER encoded, you can change the -Type parameter for Export-Certificate to use the types supported by .NET, as seen in help Export-Certificate -Detailed :

How to export .cer and .key from .pfx file

So you are ready to add a signed certificate and private key to your web application. Here’s one approach to making that happen.

Note, I’m using a Windows 10 workstation.

For the purpose of this post, we assume you already have a .pfx file from your certificate authority. (.pfx is a binary file. There are other file formats such as .pem (which is base64 encoded). If you have a .pem file you can convert it to .pfx and then follow these steps.)

  • Save the .pfx file on your computer. In my examples below, the pfx file is saved at C:/Users/usernameGoesHere/.ssh
  • Next you will need to extract the .key and .cer files from the .pfx:
  • Ensure you have openssl installed.
  • In this example the openssl.exe executable is installed at /bin/openssl
  • From the dir on your workstation where you have the pfx file from your CA (in my example named my-site.com.pfx), run the following command:

echo QUIT | /bin/openssl.exe pkcs12 -in my-site.com.pfx -nocerts -out server.cer.key -nodes

NOTE: If you are using something other than the git bash command line emulator, you might not need the echo QUIT | part, and you can replace /bin/openssl.exe with just openssl .)

NOTE2: We have included the -nodes flag so that the key is not encrypted with an export key.

  • Note that you now have a server.cer.key file in your directory.
  • Next run this command to extract the .key:
  • echo QUIT | /bin/openssl.exe pkcs12 -in my-site.com.pfx -out server.cer -nokeys -clcerts

NOTE: same as above, (if you aren’t using git bash emulator, you might no need the first bit of the command)

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *