Конвертирование сертификатов при помощи OpenSSL
Как только возникает необходимость выполнить конвертирование одного формата сертификата в другой, каждый раз возникает вопрос: «Как это сделать?». Наиболее удобно для этого использовать OpenSSL ( openssl.org ), этот сайт содержит исходные коды, если нет желания выполнять компилирование исходных кодов, то можно взять скомпилированный вариант OpenSSL, его можно скачать по ссылке: https://slproweb.com/products/Win32OpenSSL.html . Необходимость выполнять конвертирование возникает, если имеющийся формат сертификата не подходит для ПО или оборудования.
Итак, если необходимо выполнить конвертирование одного формата сертификата в другой, то надо скачать и установить OpenSSL на локальном компьютере. Далее, рекомендуется скопировать с папку с OpenSSL имеющиеся файлы сертификата, для которого необходимо выполнить конвертирование, открыть командную строку и перейти в папку с установленным OpenSSL.
Часто используемые форматы сертификатов:
PEM — очень часто используется в Linux based системах или оборудовании, файлы такого формата сертификата используют расширение .cer, .crt, and .pem.
DER — двоичная формат сертификата. DER формат не содержит текста «BEGIN CERTIFICATE/END CERTIFICATE», формат DER чаще всего использует расширение .der
PKCS#7 или P7B — эти форматы сертификата хранятся в формате Base64 ASCII и чаще всего имеют расширения файлов .p7b или .p7c. Файл P7B, кроме самого сертификата содержит цепочку сертификатов (открытых ключей) выпускающих центров сертификации (Intermediate CAs). Этот формат поддерживается в Microsoft Windows и Java Tomcat.
PKCS#12 или PFX — эти форматы представляют собой двоичный формат для хранения сертификата сервера, промежуточных сертификатов и закрытого ключа в одном зашифрованном файле. Файлы такого формата сертификата используют расширение .pfx and .p12. PFX файлы обычно используются на windows машинах для импорта/экспорта сертификатов и закрытого ключа.
Для выполнения конвертирования необходимо выполнить одну (или две) команду из списка ниже, в зависимости от исходного формата сертификата и целевого.
Конвертирование x509 в PEM
Конвертирование PEM в DER
Конвертирование DER в PEM
Конвертирование PEM в P7B
Конвертирование PKCS7 в PEM
Конвертирование pfx в PEM
Конвертирование PFX в PKCS#8
Для этого требуется выполнение двух команд
Step 1: Конвертирование PFX в PEM
Step 2: Конвертирование PEM в PKCS8
Конвертирование P7B в PFX
Для этого требуется выполнение двух команд
1. Конвертирование P7B в CER
2. Конвертирование CER и закрытого ключа в PFX
Windows — конвертация SSL сертификата PEM в формат PFX (PKCS#12) с помощью подсистемы Linux
Будем собирать PFX файл в Windows 10 с помощью подсистемы Linux. У нас есть:
- Сертификат, cert.pem.
- Ключ, key.pem.
- Цепочка, certnew.p7b.
Включаем bash в Windows:
На диске C создаём папку C:\keys, переносим туда все нужные файлы:
Цепочка у нас в формате p7b, это стандартный формат, когда мы скачиваем цепочку с центра сертификации Windows. Переведём цепочку в PEM формат.
Запускаем bash. Для запуска bash нужно выполнить команду «bash» или «bash.exe».
Проверим что пакет openssl установлен:
Если не установлен, то пакет ставится через apt-get:
У меня openssl уже стоит, Переходим в папку /mnt/c/keys/
Convert a CERT/PEM certificate to a PFX certificate
I’ve seen a couple questions about how to convert a PFX to a cert file, but I need to go the other way.
I’d like to convert them to a single .pfx file. Is there a tool that does this?
4 Answers 4
Here is how to do this on Windows without third-party tools:
Import certificate to the certificate store. In Windows Explorer select «Install Certificate» in context menu. Follow the wizard and accept default options «Local User» and «Automatically».
Find your certificate in certificate store. On Windows 10 run the «Manage User Certificates» MMC. On Windows 2013 the MMC is called «Certificates». On Windows 10 by default your certificate should be under «Personal»->»Certificates» node.
Export Certificate. In context menu select «Export. » menu:
Select «Yes, export the private key»:
You will see that .PFX option is enabled in this case:
Converting pfx to pem using openssl
How to generate a .pem CA certificate and client certificate from a PFX file using OpenSSL.
3 Answers 3
You can use the OpenSSL Command line tool. The following commands should do the trick
If you want your file to be password protected etc, then there are additional options.
You can read the entire documentation here.
Another perspective for doing it on Linux. here is how to do it so that the resulting single file contains the decrypted private key so that something like HAProxy can use it without prompting you for passphrase.
Then you can configure HAProxy to use the file.pem file.
This is an EDIT from previous version where I had these multiple steps until I realized the -nodes option just simply bypasses the private key encryption. But I’m leaving it here as it may just help with teaching.
- The 1st step prompts you for the password to open the PFX.
- The 2nd step prompts you for that plus also to make up a passphrase for the key.
- The 3rd step prompts you to enter the passphrase you just made up to store decrypted.
- The 4th puts it all together into 1 file.
Then you can configure HAProxy to use the file.combo.pem file.
The reason why you need 2 separate steps where you indicate a file with the key and another without the key, is because if you have a file which has both the encrypted and decrypted key, something like HAProxy still prompts you to type in the passphrase when it uses it.
How do I convert a pem to pfx file?
Do this dumps out a single plain text file.
Now how do I convert this plain text pem back to pfx?
The only commands I see to convert to pfx require the cer and private keys in separate files:
2 Answers 2
Although I concur this is not really programming and arguably offtopic, numerous similar Qs about commandline tools (openssl, keytool, certutil etc) for (crypto) keys and certs are apparently accepted by the community (upvoted) — but none I’ve seen directly addresses this point.
The different options on openssl pkcs12 -export allow you to provide the pieces in different files, but that is not required. If you do have the privatekey and chain of certs in one PEM file, as output by default by pkcs12 [not -export] , you can let everything be read from that one file:
and you can even combine the pieces ‘on the fly’ as long as you put privatekey first:
You can use the command below to convert PEM (.pem, .crt, .cer) to PFX:
This will be very generic for all above mentioned files.
Convert .pem and .pub to .pfx file
I have a .pem file and a .pub file, I used following commands to create them
Now I want to make them to a one .pfx file which is binary and contains both private and public key. Is it possible? how? (I have tested som openssl commands but the file was empty).
I used this command
it generates this error:
unable to load private key 17880:error:0906D06C:PEM routines:PEM_read_bio:no start line:.\crypto\pem\pem_li b.c:703:Expecting: ANY PRIVATE KEY
2 Answers 2
You get the error because, for the -inkey argument, you have to specify a private key; not a public key.
OpenSSL’s pkcs12 command doesn’t provide a way to consolidate public and private keys into a single file. It is specifically used to consolidate certificates and private keys into a single file. In the above case, what you have is a public key, not a certificate.
-in filename The filename to read certificates and private keys from, standard input by default. They must all be in PEM format. The order doesn’t matter but one private key and its corresponding certificate should be present. If additional certificates are present they will also be included in the PKCS#12 file.
Note that it specifically mentions that one private key and its corresponding certificate should be present. The command that I typically use to generate a PKCS#12 file is: