Table of Contents
- Installing OpenSSL
- OpenSSL on Linux
- OpenSSL on Windows
- From PEM (pem, cer, crt) to PKCS#12 (p12, pfx)
- From PKCS#12 to PEM
- From DER (.der, cer) to PEM
- From PEM to DER
- From PEM to PKCS#7 (.p7b, .p7c)
- From PKCS#7 to PEM
- From PKCS#7 to PFX
- Online SSL Converters
- Conclusions
In this post, part of our «how to manage SSL certificates on Windows and Linux systems» series, we’ll show how to convert an SSL certificate into the most common formats defined on X.509 standards: the PEM format and the PKCS#12 format, also known as PFX. The conversion process will be accomplished through the use of OpenSSL, a free tool available for Linux and Windows platforms.
Before entering the console commands of OpenSSL we recommend taking a look to our overview of X.509 standard and most popular SSL Certificates file formats — CER, CRT, PEM, DER, P7B, PFX, P12 and so on.
Installing OpenSSL
The first thing to do is to make sure your system has OpenSSL installed: this is a tool that provides an open source implementation of SSL and TLS protocols and that can be used to convert the certificate files into the most popular X.509 v3 based formats.
OpenSSL on Linux
If you’re using Linux, you can install OpenSSL with the following YUM console command:
If your distribution is based on APT instead of YUM, you can use the following command instead:
> apt—get install openssl |
OpenSSL on Windows
If you’re using Windows, you can install one of the many OpenSSL open-source implementations: the one we can recommend is Win32 OpenSSL by Shining Light Production, available as a light or full version, both compiled in x86 (32-bit) and x64 (64-bit) modes . You can install any of these versions, as long as your system support them.
OpenSSL is basically a console application, meaning that we’ll use it from the command-line: after the installation process completes, it’s important to check that the installation folder (C:\Program Files\OpenSSL-Win64\bin for the 64-bit version) has been added to the system PATH (Control Panel > System> Advanced > Environment Variables): if it’s not the case, we strongly recommend to manually add it, so that you can avoid typing the complete path of the executable everytime you’ll need to launch the tool.
Once OpenSSL will be installed, we’ll be able to use it to convert our SSL Certificates in various formats.
From PEM (pem, cer, crt) to PKCS#12 (p12, pfx)
This is the console command that we can use to convert a PEM certificate file (.pem, .cer or .crt extensions), together with its private key (.key extension), in a single PKCS#12 file (.p12 and .pfx extensions):
> openssl pkcs12 —export —in certificate.crt —inkey privatekey.key —out certificate.pfx |
If you also have an intermediate certificates file (for example, CAcert.crt) , you can add it to the «bundle» using the -certfile command parameter in the following way:
> openssl pkcs12 —export —in certificate.crt —inkey privatekey.key —out certificate.pfx —certfile CAcert.cr |
From PKCS#12 to PEM
If you need to «extract» a PEM certificate (.pem, .cer or .crt) and/or its private key (.key)from a single PKCS#12 file (.p12 or .pfx), you need to issue two commands.
The first one is to extract the certificate:
> openssl pkcs12 —in certificate.pfx —nokey —out certificate.crt |
And a second one would be to retrieve the private key:
> openssl pkcs12 —in certificate.pfx —out privatekey.key |
IMPORTANT: the private key obtained with the above command will be in encrypted format: to convert it in RSA format, you’ll need to input a third command:
> openssl rsa —in privatekey.key —out privatekey_rsa.key |
Needless to say, since PKCS#12 is a password-protected format, in order to execute all the above commands you’ll be prompted for the password that has been used when creating the .pfx file.
From DER (.der, cer) to PEM
> openssl x509 —inform der —in certificate.cer —out certificate.pem |
From PEM to DER
> openssl x509 —outform der —in certificate.pem —out certificate.der |
From PEM to PKCS#7 (.p7b, .p7c)
> openssl crl2pkcs7 —nocrl —certfile certificate.pem —out certificate.p7b —certfile CAcert.cer |
From PKCS#7 to PEM
> openssl pkcs7 —print_certs —in certificate.p7b —out certificate.pem |
From PKCS#7 to PFX
> openssl pkcs7 —print_certs —in certificatename.p7b —out certificatename.cer > openssl pkcs12 —export —in certificatename.cer —inkey privateKey.key —out certificatename.pfx —certfile cacert.cer |
Online SSL Converters
If you can’t (or don’t want to) install OpenSSL, you can convert your SSL Certificates using one of these web-based online tools:
- SSL Certificates Converter Tool by SSLShopper.com
- SSL Converter by NameCheap
Both of them work really well and can convert most, if not all, the format detailed above: at the same time, you need to seriously think about the security implications that come with uploading your SSL Certificates (and possibly their private keys) to a third-party service. As trustable and secure those two site have been as of today, we still don’t recommend such move.
Conclusions
That’s it, at least for the time being: we hope that these commands will be helpful to those developers and system administrators who need to convert SSL certificates in the various formats required by their applications.
See you next time!
There are two major encoding schemes for X.509 certificates and keys: PEM (Base64 ASCII), and DER (binary).
- DER (Distinguished Encoding Rules) is a data object encoding schema that can be used to encode certificate objects into binary files.
- PEM (Privacy Enhanced Mail) is an encrypted email encoding schema that can be borrowed to encode certificate DER files into text files.
We can’t always tell what kind of file we are working with just from looking at the filename. We may need to open it in a text editor and take a look for ourselves. We will share more about this later.
Understanding PEM
PEM (originally “Privacy Enhanced Mail”) is the most common format for X.509 certificates, CSRs, and cryptographic keys.
A PEM file is a text file containing one or more items in Base64 ASCII encoding, each with plain-text headers and footers (e.g. —–BEGIN CERTIFICATE—– and —–END CERTIFICATE—–).
Example of PEM
Here is an example of PEM format certificate.
# more certificate.pem
—–BEGIN CERTIFICATE—–
MIIDZTCCAk2gAwIBAgIUYWbWmYiNaGtLhEIhAcBtWO7NubkwDQYJKoZIhvcNAQEL
BQAwQjELMAkGA1UEBhMCVVMxFTATBgNVBAcMDERlZmF1bHQgQ2l0eTEcMBoGA1UE
…….
KtsNSEGDFdAFK7xh/L91l5eHSDSL0OApegcu2AhfUgSOnUBtUxa41yAtdb82Lvow
/deh1GDjgei5H7CKZwIruvN6rYWdfqpnaynAXS+AjRL145FwovHbJjjr/TYENCm0
ewRvyGJyUkJO
—–END CERTIFICATE—–
What is DER Format
DER (Distinguished Encoding Rules) is a binary encoding for X.509 certificates and private keys. Unlike PEM, DER-encoded files do not contain plain text statements such as —–BEGIN CERTIFICATE—–. DER files are most commonly seen in Java contexts.
Those certificate DER files are binary files, which can not be viewed with text editors. But they can be processed by application without any problems.
DER-encoded certificate files are supported by almost all applications.
Difference between PEM and DER
If the certificate is in text format, then it is in PEM format.
We can read the contents of a PEM certificate (cert.cer) using the ‘openssl’ command on Linux or Windows as follows:
- openssl x509 -in cert.cer -text
If the file content is binary, the certificate could be DER. To find out the format, run the following ‘openssl’ commands to open the certificate:
- openssl x509 -in cert.cer -inform DER -text
What is SSL Cer file
A file with .cer extension is a security certificate file that is used by secure websites to establish secure connections from web server to a browser.
If we open a secure website, we see a “lock” icon in the address bar. If we click on it, we can view the details of the installed certificate.
We need to figure out which format is using for this cer file based on the rules we shared above.
Convert Cer certificate to PEM
If our cer certificate is in PEM format, we can use cp cert.cer cert.pem to convert.
- openssl x509 -in cert.cer -out cert.pem
If our cer certificate is in DER format, we need to use the following command to convert to pem.
- openssl x509 -inform der -in cert.cer -out cert.pem
Understanding X509 Certificate with Openssl Command
Many Certificate Authorities (CAs) provide certificates in X.509 format (a file with a CER or CRT extension). A certificate of this type is usually provided in the DER-encoding format. However, the majority of services that use SSL Certificates will only accept certificates in PEM format (Base64 encoded). In this post we will cover how to convert a DER-encoded certificate with a CRT or CER extension to PEM format.
What are PEM and DER certificates?
- PEM (Privacy Enhanced Mail) is the most common format for X.509 certificates. PEM files are plain text-based and supported by most web browsers, servers, and apps. It includes the header and footer lines: —–BEGIN CERTIFICATE—– and —–END CERTIFICATE—–.
- DER (.der, .crt) – is a Binary certificate format. It is less common than PEM, but is still used, especially in Java environments.
Renaming Base64 CRT to PEM
Before converting a CER/CRT certificate file to PEM, check if the file already contains a certificate in Base64-encoded format. Open the certificate file in any text editor. If it contains ASCII text that starts and ends with one of the following prompts, it has already been converted to Base64 PEM format:
-----BEGIN CERTIFICATE----- -----END CERTIFICATE----- ----- BEGIN PRIVATE KEY ----- -----END PRIVATE KEY ------ -----BEGIN PUBLIC KEY ----- -----END PUBLIC KEY -----
Change the certificate file extension from CRT or CER to PEM in this example.
If the certificate file contains binary data, it cannot be viewed as a text file. Such a CER/CRT file containing a certificate in binary format (DER) can be converted to Base64 ASCII certificate format (PEM) using one of the methods described below.
Converting Binary CRT to PEM using the Certificate Export Wizard in Windows
In Windows, you can convert CERs to the PEM certificate file format using the built-in Certificate Export tool. It can be used to convert a CRT file or export an installed certificate from the certificate store.
Locate the CRT file and double-click to open it.
Or run the Certificate Manager MMC snap-in:
- certlm.msc – to export local machine certificate
- certmgr.msc – to export user certificate
Open the certificate properties, navigate to the Detail tab and click Copy to file.
Select Base-64 encoded X.509 (.CER) format in the Certificate Export Wizard and click Next.
Specify the filename to export and click Next (he filename extension will automatically be set to *.cer).
When the export is complete, locate the exported CER file and rename it to change the extension to PEM.
Converting Binary CRT to PEM using OpenSSL
To convert SSL certificates into the appropriate format, you can use the OpenSSL library. OpenSSL is primarily a Linux tool available out-of-the-box in most distros, but you can also use it on Windows. To install OpenSSL, use the OpenSSL for Windows port, or install it using the WinGet package manager:
winget install ShiningLight.OpenSSL.Light
The command and syntax for converting a binary CRT file to PEM is the same whether you’re using Linux or Windows:
openssl x509 -in <BINARY CRT FILE> -inform DER -out <PEM OUTPUT FILE> -outform PEM
Go to the directory with the OpenSSL binaries:
cd "C:\Program Files\OpenSSL-Win64\bin"
Convert the certificate file:
./openssl x509 -in "C:\temp\mycert.cer" -inform DER -out "C:\temp\mycert_converted.pem" -outform PEM
Open the PEM file in any text editor and confirm that it contains ASCII text.
Cyril Kardashevsky
I enjoy technology and developing websites. Since 2012 I’m running a few of my own websites, and share useful content on gadgets, PC administration and website promotion.
Чтобы вы могли без проблем пользоваться SSL-сертификатом на разных платформах и устройствах, иногда требуется изменить его формат. Дело в том, что некоторые форматы лучше подходят для работы с различными видами программного обеспечения. Далее мы расскажем о том, какие форматы бывают, в каких случаях используются и какими способами можно конвертировать один формат сертификата в другой.
Форматы сертификатов
Существует четыре основных формата сертификатов:
PEM — популярный формат используемый Центрами Сертификации для выписки SSL-сертификатов.
Основные расширения этого типа .pem, .crt, .cer, .key. В файлах содержатся строки вида
-----BEGIN CERTIFICATE----- -----END CERTIFICATE----- -----BEGIN PRIVATE KEY----- -----END PRIVATE KEY ------
Сертификаты PEM подходят для установки на веб-серверы nginx, apache2.
DER — это бинарная форма сертификата PEM.
Основные расширения этого типа сертификата .der .cer
Сертификаты DER подходят для установки на серверы Java.
P7B. Файлы P7B кодируются в формате Base64 и имеют расширение .p7b или .p7c.
В файлах содержатся строки вида
-----BEGIN PKCS7----- -----END PKCS7-----
Сертификаты P7B подходят для установки на серверы MS Windows, Java Tomcat
PFX — это сертификат в бинарном формате, выданный для домена, включающий в себя сертификат, цепочку сертификатов (корневые сертификаты) и приватный ключ. Имеют расширение .pfx или .p12.
Сертификаты PFX подходят для установки на серверы Windows, в частности Internet Information Services(IIS).
Способы конвертации
Существует несколько способов конвертации сертификатов, которые отличаются между собой только простотой конвертирования и уровнем безопасности. Мы расскажем о трех из них.
Конвертация SSl сертификатов посредством OpenSSL
OpenSSL — это надежный, коммерческий и полнофункциональный инструментарий для протоколов Transport Layer Security (TLS) и Secure Sockets Layer (SSL). А также библиотека криптографии общего назначения. Конвертация с использованием библиотеки OpenSSL считается одним из самых безопасных способов: все данные будет сохранены непосредственно на устройстве, на котором будут выполняться операции по конвертированию.
Для того чтобы воспользоваться им, вам необходимо перейти в командную строку и выполнить команды.
Предоставленные ниже примеры команд OpenSSL позволяют конвертировать сертификаты и ключи в нужный формат.
Конвертировать PEM в DER можно посредством команды:
openssl x509 -outform der -in site.crt -out site.der
Аналогично, для других типов:
PEM в P7B
openssl crl2pkcs7 -nocrl -certfile site.crt -out site.p7b -certfile site.ca-bundle
PEM в PFX
openssl pkcs12 -export -out site.pfx -inkey site.key -in site.crt -certfile site.ca-bundle
Обращаем ваше внимание, что после выполнения команды, будет запрошена установка пароля ключа.
DER в PEM
openssl x509 -inform der -in site.der -out site.crt
P7B в PEM
openssl pkcs7 -print_certs -in site.p7b -out site.cer
P7B в PFX
openssl pkcs7 -print_certs -in site.p7b -out certificate.ceropenssl pkcs12 -export -in site.cer -inkey site.key -out site.pfx -certfile site.ca-bundle
PFX в PEM
openssl pkcs12 -in site.pfx -out site.crt -nodes
Конвертация при помощи онлайн-сервисов
Для конвертации сертификатов самый удобный способ — использование специальных сайтов. Этот способ считается наименее безопасным методом: никогда не знаешь, сохраняет ли автор сайта ваш приватный ключ при конвертации.
Конвертация с PEM в DER
Для конвертации необходим только файл сертификата .crt, .pem
Конвертация с PEM в P7B
В этом случае существует возможность добавить также цепочку сертификатов.
Что такое цепочка сертификатов и для чего она нужна, можно узнать в статье «Что такое корневой сертификат»
Конвертация с PEM в PFX
В этом случае необходимо обратить внимание на то, что обязателен ключ сертификата, а также необходимо установить пароль ключа.
Конвертация из DER в PEM
Конвертация из P7B в PEM
Конвертация из P7B в PFX
Конвертация из PFX в PEM
Конвертация скриптом openssl-ToolKit
OpenSSL ToolKit — скрипт, который облегчает работу с библиотекой OpenSSL. Работа со скриптом является безопасным решением, т.к сертификаты и ключи сертификата никуда не передаются, а используются непосредственно на вашем сервере.
Для начала работы скрипт необходимо скачать и запустить. Сделать это можно одной командой:
echo https://github.com/tdharris/openssl-toolkit/releases/download/1.1.0/openssl-toolkit-1.1.0.zip \ | xargs wget -qO- -O tmp.zip && unzip -o tmp.zip && rm tmp.zip && ./openssl-toolkit/openssl-toolkit.sh
После выполнения команды откроется следующее окно:
Нас интересует пункт 2. Convert certificates
После перехода в пункт 2. появится следующее меню, с выбором нужного типа конвертирования
После выбора преобразования, в данном случае PEM to FPX, скрипт предложит выбрать директорию с сертификатами на том устройстве, где запускается скрипт.
В нашем случае мы их скачали в директорию /home/ivan/crt/
После корректного ввода директории, скрипт отобразит все файлы в этой директории.
Далее нужно ввести имя сертификата, который будем конвертировать, в нашем случае это site.pem
Обращаю ваше внимание, что для корректной конвертации, с PEM в PFX, необходимо вручную объединить файл сертификата, цепочки и ключа в один файл, иначе будет возникать ошибка конвертации.
Сделать это можно простой командой
cat site.crt site.ca-bundle site.key > site.pem
Данное действие необходимо только для конвертации из PEM в PFX.
Мы рассмотрели пример конвертации PEM в PFX. Этим же путем можно конвертировать сертификаты в другие форматы. Единственное, что вам уже не понадобится шаг с объединением файлов.
Пример конвертации PEM В DER.
Для успешной установки и функционирования SSL сертификатов на различных платформах и устройствах, нередко их необходимо предоставить в разных форматах. Например, серверы Windows используют PFX файлы, для Apache серверов необходимы PEM файлы с расширением .crt или .cer. В этой статье мы поможем вам разобраться в следующих вопросах:
- Какие бывают форматыSSL сертификатов?
- Чем они отличаются?
- Как конвертировать SSL сертификаты из одного формата в другой?
Формат сертификата PEM
PEM – наиболее популярный формат среди сертификационных центров. PEM сертификаты могут иметь расширение .pem, .crt, .cer, и .key (файл приватного ключа). Она представляют собой ASCII файлы, закодированные по схеме Base64. Когда вы открываете файл pem формата в текстовом редакторе, вы можете увидеть, что текст кода в нем начинается с тега «—— BEGIN CERTIFICATE ——» и заканчивая тегом «—— END CERTIFICATE ——«. Apache и другие подобные серверы используют сертификаты в PEM формате. Обратите внимание, что в одном файле может содержатся несколько SSL сертификатов и даже приватный ключ, один под другим. В таком случае каждый сертификат отделен от остальных ранее указанными тегами BEGIN и END. Как правило, для установки SSL сертификата на Apache, сертификаты и приватный ключ должны быть в разных файлах.
Формат сертификата DER
DER формат – это бинарный тип сертификата вместо формата PEM. В PEM формате чаще всего используется расширение файла .cer, но иногда можно встретить и расширение файла .der. Поэтому чтобы отличить SSL сертификат в формате PEM от формата DER, следует открыть его в текстовом редакторе и найти теги начала и окончания сертификата (BEGIN/END). DER SSL сертификаты, как правило, используются на платформах Java.
PKCS # 7 / P7B сертификат
SSL сертификаты в формате PKCS # 7 или P7B — это файлы, которые хранятся в формате Base64 ASCII и имеют расширение файла .p7b или .p7c. P7B сертификаты содержат теги начала сертификата «—— BEGIN PKCS7 ——» и его конца «—— END PKCS7 ——«. Файлы в формате P7B включают в себя только ваш SSL сертификат и промежуточные SSL сертификаты. Приватный ключ при этом идет отдельным файлом. SSL сертификаты в формате PKCS # 7 / P7B поддерживают следующие платформы: Microsoft Windows и Java Tomcat.
PFX сертификат (формат PKCS # 12)
Формат SSL сертификата PKCS # 12 или, как его еще называют, PFX сертификат — бинарный формат, при использовании которого в одном зашифрованном файле хранится не только ваш личный сертификат сервера и промежуточные сертификаты центра сертификации, но и ваш закрытый ключ. PFX файлы, как правило, имеют расширение .pfx или .p12. Обычно, файлы формата PFX используются на Windows серверах для импорта и экспорта файлов сертификатов и вашего приватного ключа.
Конвертация SSL сертификатов в OpenSSL
Данные команды OpenSSL дают возможность преобразовать сертификаты и ключи в разные форматы. Для того чтобы сделать их совместимыми с определенными видами серверов, либо ПО. К примеру, Вам необходимо конвертировать обыкновенный файл PEM, который будет работать с Apache, в формат PFX (PKCS # 12) с целью применения его с Tomcat, либо IIS.
- Конвертировать PEM в DER
openssl x509 -outform der -in certificate.pem -out certificate.der
- Конвертировать PEM в P7B
openssl crl2pkcs7 -nocrl -certfile certificate.cer -out certificate.p7b -certfile CACert.cer
- Конвертировать PEM в PFX
openssl pkcs12 -export -out certificate.pfx -inkey privateKey.key -in certificate.crt -certfile CACert.crt
- Конвертировать DER в PEM
openssl x509 -inform der -in certificate.cer -out certificate.pem
- Конвертировать P7B в PEM
openssl pkcs7 -print_certs -in certificate.p7b -out certificate.cer
- Конвертировать P7B в PFX
openssl pkcs7 -print_certs -in certificate.p7b -out certificate.ceropenssl pkcs12 -export -in certificate.cer -inkey privateKey.key -out certificate.pfx -certfile CACert.cer
- Конвертировать PFX в PEM
openssl pkcs12 -in certificate.pfx -out certificate.cer -nodes
Онлайн конвертер SSL сертификатов
Также существуют онлайн программы для конвертации сертификатов из одного формата в другой. Например, мы можем посоветовать SSL конвертер от SSLShopper. Используйте этот SSL конвертер для преобразования SSL-сертификатов различных форматов, таких как PEM, DER, P7B и PFX. Чтобы использовать SSL-конвертер, просто выберите файл сертификата и его текущий тип (он определяется по формату расширения), затем выберите формат, в какой Вам необходимо преобразовать SSL сертификат и нажмите кнопку “Convert Certificate”. Обратите внимание, что в зависимости от того, в какой формат вам нужно конвертировать SSL сертификат, от вас потребуются разные исходящие файлы.
Конвертация PEM в DER
Для конвертации стандартного сертификата в формате PEM в бинарный формат DER, потребуется только файлSSL сертификата. Обычно, вы его получаете в архиве вместе с промежуточными сертификатами. Как правило, в его названии указано имя вашего домена.
Конвертация PEM в P7B / PKCS#7
Если же вам нужно преобразовать ваш стандартный SSL сертификат в файл формата P7B / PKCS#7, вы можете кроме SSL сертификата вашего домена загрузить также файлы с цепочками сертификатов. Более подробно о том, что такое цепочка SSL сертификатов, мы писали в статье о CA-bundle.
Конвертация PEM в PFX / PKCS#12
Обратите внимание, что для конвертации стандартного формата SSL сертификата необходимо добавить еще один файл – ваш приватный ключ. Приватный ключ – это конфиденциальная информация, которая должна быть только у вас. Поэтому центры сертификации не высылают его месте с файлами вашего сертификата. Приватный ключ создается в момент генерации CSR запроса. Если вы генерируете CSR у себя на сервере, на нем же должен автоматически сохраниться ключ. Если вы создаете CSR запрос в специальном инструменте на нашем сайте (на странице по ссылке или во время заполнения технических данных), ключ показывается вам в конце генерации CSR (или введения технических данных), но не сохраняется в нашей базе данных. Поэтому важно, чтобы вы самостоятельно сохранили приватный ключ.
Конвертация PFX / PKCS#12 в PEM
Если вам необходимо преобразовать SSL сертификат формата PFX в PEM-формат, следует открыть файл сертификата в любом текстовом редакторе и скопировать текст каждого сертификата вместе с тегами BEGIN / END в отдельные файлы, после чего их следует сохранить их как certificate.cer (для сертификата вашего сервера) и cacert.cer (для цепочки промежуточных сертификатов). То же самое следует проделать с текстом приватного ключа и сохранить его под названием privatekey.key.