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

Бывают ситуации, когда имеется PFX-контейнер, защищённый паролем и нам известен этот пароль. При этом необходимо извлечь из этого PFX-файла данные сертификата и закрытого ключа в формате PEM. Рассмотрим пример того, как выполнить эту задачу с помощью утилиты openssl.
Шаг 1. Извлечение сертификата
Распаковываем сертификат. При выполнении будет запрошен пароль (Import Password), которым защищён PFX контейнер. Вводим пароль.
openssl pkcs12 -in my_ru.pfx -clcerts -nokeys -out my_ru.crt Enter Import Password: ************ MAC verified OK
Шаг 2. Извлечение закрытого ключа
Распаковываем закрытый ключ. При выполнении будет запрошен пароль (Import Password), которым защищён PFX контейнер. Вводим пароль. Далее будет запрошена новая парольная фраза (PEM pass phrase), которой будут зашифрованы данные закрытого ключа при выгрузке. Два раза вводим парольную фразу защиты закрытого ключа.
openssl pkcs12 -in my_ru.pfx -nocerts -out my_ru_encr.key Enter Import Password: ************ MAC verified OK Enter PEM pass phrase: ****** Verifying - Enter PEM pass phrase: ******
Шаг 3. Дешифровка закрытого ключа
Выполняем дешифровку закрытого ключа. При запросе вводим парольную фразу (PEM pass phrase), заданную на шаге 2.
openssl rsa -in my_ru_encr.key -out my_ru.key Enter pass phrase for my_ru_encr.key: ****** writing RSA key
В результате имеем два файла 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
Extract private key from pfx file or certificate store WITHOUT using OpenSSL on Windows
As the title suggests I would like to export my private key without using OpenSSL or any other third party tool. If I need a .cer file or .pfx file I can easily export these via MMC or PowerShell pkiclient but I can’t find a way to get the private key. https://learn.microsoft.com/en-us/powershell/module/pkiclient/export-certificate?view=win10-ps Using an online tool like https://www.sslshopper.com/ssl-converter.html is not OK. PSVersion:
PS C:\Users\oscar> $PSVersionTable Name Value ---- ----- PSVersion 5.1.17134.228 PSEdition Desktop PSCompatibleVersions BuildVersion 10.0.17134.228 CLRVersion 4.0.30319.42000 WSManStackVersion 3.0 PSRemotingProtocolVersion 2.3 SerializationVersion 1.1.0.1
I can get the public key like this:
(Get-PfxCertificate -FilePath C:\Users\oscar\Desktop\localhost.pfx).GetPublicKey()
And export the entire certificate like this:
(Get-PfxCertificate -FilePath C:\Users\oscar\Desktop\localhost.pfx).GetRawCertData()
Result from
PS C:\Users\oscar> $mypwd = ConvertTo-SecureString -String "MyPassword" -Force -AsPlainText PS C:\Users\oscar> $mypfx = Get-PfxData -FilePath C:\Users\oscar\Desktop\localhost.pfx -Password $mypwd PS C:\Users\oscar> $mypfx OtherCertificates EndEntityCertificates ----------------- --------------------- <> $mypfx.EndEntityCertificates Thumbprint Subject ---------- ------- 8ED4971564E35099D6DB490C3756E2AD43AAAAAA CN=localhost
Tested the command from @Brad but I got the error below.
Private key is NOT plain text exportable
certutil -exportPFX -p "myPassword" -privatekey -user my C:\localhost.pfx
Similar to Certificate Export Wizard in MMC certificates, only export to .pfx available if the key is included. 
asked Oct 22, 2018 at 12:49
64.8k 38 38 gold badges 349 349 silver badges 437 437 bronze badges
You certainly need a .pfx file as .cer files don’t store private keys. What’s your $PSVersionTable ? Can you use Get-PfxData -FilePath ‘mycertificate.pfx’ -Password (ConvertTo-SecureString -Force -AsPlainText -String ‘MyClearTextPassword’) ?
Oct 23, 2018 at 5:38
@PetruZaharia Yes I’m aware, wrote that as an example of what you can export. 🙂 Updated the question with PSVersion and what I have tried. I can but I have not found a way to export the private key.
Oct 23, 2018 at 6:19
Regarding certutil , I had the same problem. I could export .pfx file with private key using Powershell: Export-PfxCertificate -Cert cert:\CurrentUser\Root\xyz -Force -FilePath keystore.pfx -Password (ConvertTo-SecureString password -AsPlainText -Force) The hard part: You need to find the cert thumbprint using something like: ls cert:\CurrentUser\Root
Jan 5, 2023 at 13:54
6 Answers 6
I had the same problem and solved it with the help of PSPKI Powershell module from PS Gallery. While I understand that you look for a solution that preferably uses some built in functionality in Windows, installing a module from PS Gallery might be acceptable. At least it was in my case.
First install the PSPKI module (I assume hat the PSGallery repository has already been set up):
Install-Module -Name PSPKI
The PSPKI module provides a Cmdlet Convert-PfxToPem which converts a pfx-file to a pem-file which contains the certificate and pirvate key as base64-encoded text:
Convert-PfxToPem -InputFile C:\path\to\pfx\file.pfx -Outputfile C:\path\to\pem\file.pem
Now, all we need to do is splitting the pem-file with some regex magic. For example, like this:
(Get-Content C:\path\to\pem\file.pem -Raw) -match "(?ms)(\s*((?-----BEGIN PRIVATE KEY-----.*?- ----END PRIVATE KEY-----)|(?-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----))\s*)" $Matches["privatekey"] | Set-Content "C:\path\to\key\file.pem" $Matches["certificate"] | Set-Content "C:\path\to\certificate\file.pem"
answered Nov 3, 2020 at 10:33
Christoph Böhme Christoph Böhme
3,806 1 1 gold badge 19 19 silver badges 29 29 bronze badges
Good answer but I would prefer to not use any third party library as you say. However since this is the best answer so far I will mark it as accepted until there is a better alternative. 🙂
Nov 3, 2020 at 13:12
I added a PowerShell script that incorporates the .NET approach to exporting the private key to a Pkcs8 PEM file. I want to also point out that the PSPKI Convert-PfxToPem is very low level; using PInvoke to call Win32 methods. Since .NET added support for CNG (Crypto Next Gen), we have all the capability we need via the System.Security.Cryptography namespace.
Jul 21, 2021 at 13:21
You can do this without the third party library: $cert = Get-PfxCertificate -FilePath $pfxFilePath; Export-Certificate -FilePath $derFilePath -Cert $cert; certutil -encode $derFilePath $pemFilePath | Out-Null Now that you have pem file follow the rest of the posted answer. (I wish we could format code better in comments. )
Dec 6, 2021 at 16:59
@S.Melted This won’t include the private key.
Jul 15, 2022 at 14:04
I found Panos.G’s answer quite promising, but did not get it to work. All three described methods are not available on my certificate object. After more digging, I came up with the following solution:
Note: It works, if you read the certificate from the certificate store. It does not work, if you read in a .pfx file with Get-PfxCertificate , for example. If you just have it as a file, you can install it in your certificate store to be able to read it from there as follows.
# Read the certificate from the certificate store # In this example, I use the certificate thumbprint to identify the certificate. $cert = Get-ChildItem Cert:\ -Recurse | ? '> # Read the private key into an RSA CNG object: $RSACng = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($cert) # Get the bytes of the private key $KeyBytes = $RSACng.Key.Export([System.Security.Cryptography.CngKeyBlobFormat]::Pkcs8PrivateBlob) # Encode the bytes (Base64) $KeyBase64 = [System.Convert]::ToBase64String($KeyBytes, [System.Base64FormattingOptions]::InsertLineBreaks) # Put it all together $KeyPem = @" -----BEGIN PRIVATE KEY----- $KeyBase64 -----END PRIVATE KEY----- "@
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.
Mark Carpenter
asked Dec 31, 2008 at 15:10
Mark Carpenter Mark Carpenter
17.5k 22 22 gold badges 98 98 silver badges 150 150 bronze badges
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.
openssl pkcs12 -in input.pfx -out mycerts.crt -nokeys -clcerts
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:
openssl x509 -inform pem -in mycerts.crt -outform der -out mycerts.cer
5,622 30 30 silver badges 43 43 bronze badges
answered Jan 1, 2009 at 22:09
Berk D. Demir Berk D. Demir
6,093 3 3 gold badges 18 18 silver badges 11 11 bronze badges
+1 for explaining what the file is in addition to providing the commands.
Feb 28, 2012 at 14:47
«Mac verify error: invalid password?» when I tried it. I don’t know any passwords, I just have the file my vendor supplied.
Apr 14, 2014 at 20:13
IT seems like dropping «-nokeys» works when you are attemtping to convert a certificate with its private keys, say for use with Fiddler
Nov 17, 2016 at 7:46
@Berk, Aside from OpenSSL, does Windows cmd have any way to do it?
Nov 19, 2016 at 22:17
the simple way I believe is to import it then export it, using the certificate manager in Windows Management Console.
answered Dec 31, 2008 at 15:22
Andrew Cox Andrew Cox
10.7k 3 3 gold badges 34 34 silver badges 38 38 bronze badges
i tried doing this but when i select export private key , i am getting .cer (DER encoded) option disabled . and midletsigner utility need provatekey anyhow..
Apr 28, 2010 at 4:38
You have to check the box when you import it, that says «mark this key as exportable»
Apr 28, 2010 at 8:35
How to get to the Certificate Manager in Windows: msdn.microsoft.com/en-us/library/ms788967.aspx
Feb 4, 2011 at 21:35
The easier way to open the Windows certificate manager is to type «certmgr.msc» at the command prompt.
Jul 3, 2015 at 9:00
@AndrewCox, However is there any difference behind-the-scenes between marking it as exportable and not marking it as such. Or is it simply a UI option?
Nov 19, 2016 at 22:16
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:
Get-PfxCertificate -FilePath InputBundle.pfx | Export-Certificate -FilePath OutputCert.der -Type CERT
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 :
-Type Specifies the type of output file for the certificate export as follows. -- SST: A Microsoft serialized certificate store (.sst) file format which can contain one or more certificates. This is the default value for multiple certificates. -- CERT: A .cer file format which contains a single DER-encoded certificate. This is the default value for one certificate. -- P7B: A PKCS#7 file format which can contain one or more certificates.
Заметки: Конвертируем PFX в KEY и CRT

Конвертация PFX в KEY и CRT может потребоваться в том случае, если вы используете какое-либо unix/linux-приложение с поддержкой доступа по SSL . Чаще всего это веб-приложения. В противовес этому подходу Windows использует сертификаты в формате .pfx для хранения закрытого и открытого ключа враз, разумеется с защитой паролем при попытке экспорта.
Регулярно приходится работать с сертификатами и процесс конвертации PFX (PKCS12) в KEY и CRT (PEM) встречается с завидной регулярностью. Которой, тем не менее, не достаточно, чтобы запомнить все нужные команды до автоматизма. Приходится постоянно лезть в маны или гугл за нужными командами. Уже давно пришло время написать статью-шпаргалку. Собственно, вот и она.
Хочется задать вопросы или поделиться знаниями? Приходи в наш закрытый Telegram-чат.
Конвертируем PFX
В статье я рассмотрю лишь базовые сценарии, которые встречаются наиболее часто.
Получаем сертификат
Если у вас все ещё нет сертификата от публичного ЦС, тогда мы идем к вам то самое время его получить. Обычно для этого сначала нужно сделать CSR-запрос. Следующий шаг – отправить его в ЦС и пройти проверку домена/организации (вам отправят письмо с кодом подтверждения на какой-либо админский адрес, либо позвонят на корпоративный номер телефона в зависимости от типа проверки).
Примечание: у меня на блоге вы сможете найти множество статей по сертификатам с помощью тега SSL certificate.
Как только все формальности пройдены, на почту вы получите архив с нужным вам сертификатом в формате .crt (и всей цепочкой промежуточных на всякий случай).
PFX в KEY и CRT
Воспользуемся всем знакомой утилитой openssl, чтобы вытащить открытую часть pfx-сертификата 1 :