Блог Сисадмина
Полезная информация об администрировании пользовательских и серверных ОС Windows.
Экспортировать сертификат и ключ полученный через win-acme
Есть такая полезная утилита — win-acme, с помощью которой под Windows можно обновлять сертификат Let’s Encrypt.
Так вот, при обновлении сертификата он нормально устанавливается на Exchange Server, устанавливается в хранилище (Сертификаты — Размещение веб-служб), но при этом закрытый ключ нельзя экспортировать:
Как получить закрытый ключ и возможность экспорта:
- Запускаем wacs, выбираем A (Manage Renewals)

- D (Show details for renewal)

Копируем .pfx password. - Идем в папку C:\ProgramData\win-acme\acme-v02.api.letsencrypt.org\Certificates

- Тут лежат .PFX и .PEM файлы, которые нам нужны. Можно их скопировать прямо отсюда, либо импортировать PFX локально с возможностью экспорта. А если нужны отдельно ключ и сертификат (для установки не на Windows Server например), тогда идём дальше.
Извлекаем ключ и сертификат из .PFX файла
- Конвертировать PFX в .key и .cer можно с помощью программы OpenSSL (для windows).
- Устанавливаем, запускаем, переходим в папку например C:\cert, куда предварительно скопируем наш .PFX файл.
- Запускаем команду:
C:\cert>openssl pkcs12 -in c:\cert\cert.pfx -nocerts -out private.key -nodes
Enter Import Password:
Вводим пароль, скопированный в п.4 выше, получаем файл ключа private.key в той же папке, откуда запускали openssl (C:\cert) - Далее нужно открыть этот файл в блокноте и оставить только содержимое между
——BEGIN PRIVATE KEY—— и ——END PRIVATE KEY—— - Чтобы получить сертификат, вводим команду
C:\cert>openssl pkcs12 -in c:\cert\cert.pfx -clcerts -nokeys -out public.cer
Enter Import Password: - Получаем public.cer. Также в блокноте удаляем всё лишнее.
Экспортировать сертификат и ключ полученный через win-acme : 4 комментария
Спасибо за статью. Очень помогла!
не работает. файлы с ключом и сертификатом получаются нулевой длины.
Спасибо за статью!
На текущий момент, инструкция сработала.
Заодно узнал про программу win-acme
Автор очень выручил.
Раздела доната нет. Поэтому просто прими словестное пиво\сок.
Как из pfx получить cer и key
Copyright: Не задан
Опросы
Сколько вам лет ?
Copyright © 2009-2023 All Rights Reserved.
Копирование материалов допускается только с указанием ссылки на сайт. Полное заимствование документа является нарушением российского и международного законодательства и возможно только с согласия владельца. Согласно статье 1259 Гражданского кодекса Российской Федерации результат творческого труда, также является объектом авторского права. Если вы являетесь правообладателем какого-либо представленного материала и не желаете чтобы он находилась в нашем каталоге, свяжитесь с нами и мы незамедлительно удалим его. Файлы для обмена на сайте предоставлены пользователями сайта, и администрация не несёт ответственности за их содержание. Просьба не загружать файлы, защищенные авторскими правами, а также файлы нелегального содержания!
How to extract the private key, public key and CA cert from PFX
A pfx file is technically a container that contains the private key, public key of an SSL certificate, packed together with the signer CA’s certificate all in one in a password protected single file.
Here are the steps to extract these three in case they are needed, for instance importing them in an apache server, in a load balancer, etc.
If you need to pack the aformentioned three, check out the guide here.
1. Export PFX from an existing server
Run mmc.exe, then import the Certificate snapin, choosing the Computer cert repository.

Right-click on the cert that you want to export, select «All Tasks», then «Export». Include the private key when it’s asked.

Export all properties that will include the CA cert in the PFX export. Specify a password witch which you can open the pfx later. The password is needed to protect the private key from unauthorized people as if malicious parties would get a hold on it, they could decrypt intercepted traffic that happens between the server and clients.

2. Install OpenSSL
We utilize OpenSSL to extract the packed components into a BASE64 encoded plain text format.
Unix systems have the openssl package available, if you system doesn’t have it installed, deploy it as below. On a Windows system follow the path to get the installer:
# Install OpenSSL on Debian and Ubuntu systems
sudo apt install openssl
# Install OpenSSL on RHEL, CentOS
sudo yum install openssl
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 :