- Converting Existing PFX SSL Certificate to PEM SSL Certificate
- Конвертирование сертификатов при помощи OpenSSL
- How can I convert a PFX certificate file for use with Apache on a linux server?
- 5 Answers 5
- How To Convert Windows PFX Certificate Files Into PEM Format On Linux
- Pre-requisites
- Export Certificate from Windows
- Convert PFX File Format to PEM Format
- Copy PEM and KEY Files to Linux
- Import Certificates into Amazon Certificate Manager
- Blue Label Labs Is Hiring
- You might also like
Converting Existing PFX SSL Certificate to PEM SSL Certificate
Sometimes you will have an existing PFX file that you want to convert to PEM format. Usually this is due to specific server requirements .
- To find the password used when the PFX was exported, use the following commands:
Linux | $ openssl pkcs12 -in [yourfile.pfx] -nocerts -out Convert pfx to pem linux $ openssl pkcs12 -in [yourfile.pfx] -nocerts -nodes -out Convert pfx to pem linux # use this command if the first command generates empty certificate. |
---|---|
Windows | C:\xampp\apache\bin\openssl pkcs12 -in [yourfile.pfx] -nocerts -out Convert pfx to pem linux C:\xampp\apache\bin\openssl pkcs12 -in [yourfile.pfx] -nocerts -nodes -out Convert pfx to pem linux # use this command if the first command generates empty certificate. |
Linux | $ openssl rsa -in Convert pfx to pem linux -out server.key |
---|---|
Windows | C:\xampp\apache\bin\ openssl rsa -in Convert pfx to pem linux -out server.key |
Linux | $ openssl pkcs12 -in [yourfile.pfx] -clcerts -nokeys -out server.crt |
---|---|
Windows | C:\xampp\apache\bin\ openssl pkcs12 -in [yourfile.pfx] -clcerts -nokeys -out server.crt |
Linux | $ openssl pkcs12 -in [certificate.pfx] -cacerts -nokeys -out [server-ca.crt] |
---|---|
Windows | C:\xampp\apache\bin\openssl pkcs12 -in [certificate.pfx] -cacerts -nokeys -out [server-ca.crt] |
Linux | $ openssl pkcs7 -print_certs -in [yourfile.p7b] -out server.crt |
---|---|
Windows | C:\xampp\apache\bin\ openssl pkcs7 -print_certs -in [yourfile.p7b] -out server.crt |
Now you can use the server.crt, server-ca.crt and server.key files appropriately.
Конвертирование сертификатов при помощи OpenSSL
Как только возникает необходимость выполнить конвертирование одного формата сертификата в другой, каждый раз возникает вопрос: «Как это сделать?». Наиболее удобно для этого использовать OpenSSL ( openssl.org ), этот сайт содержит исходные коды, если нет желания выполнять компилирование исходных кодов, то можно взять скомпилированный вариант OpenSSL, его можно скачать по ссылке: https://slproweb.com/products/Win32OpenSSL.html . Необходимость выполнять конвертирование возникает, если имеющийся формат сертификата не подходит для ПО или оборудования.
Итак, если необходимо выполнить конвертирование одного формата сертификата в другой, то надо скачать и установить OpenSSL на локальном компьютере. Далее, рекомендуется скопировать с папку с OpenSSL имеющиеся файлы сертификата, для которого необходимо выполнить конвертирование, открыть командную строку и перейти в папку с установленным OpenSSL.
Рекомендуется запускать командную строку с от имени администратора (Run As Administrator), это позволит избежать возможных ошибок, если на машине включен UAC.
Часто используемые форматы сертификатов:
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 машинах для импорта/экспорта сертификатов и закрытого ключа.
Для выполнения конвертирования необходимо выполнить одну (или две) команду из списка ниже, в зависимости от исходного формата сертификата и целевого.
Конвертирование PEM в PFX
openssl pkcs12 -inkey privkey.pem -in cert.pem -export -out cert.pfx
openssl x509 -in certificate.cer -outform PEM -out certificate.pem
openssl x509 -outform der -in certificate.pem -out certificate.der
openssl x509 -inform der -in certificate.der -out certificate.pem
openssl crl2pkcs7 -nocrl -certfile certificate.pem -out certificate.p7b -certfile CACert.cer
openssl pkcs7 -print_certs -in certificate.p7b -out certificate.pem
openssl pkcs12 -in certificate.pfx -out certificate.pem
Конвертирование PFX в PKCS#8
Для этого требуется выполнение двух команд
Step 1: Конвертирование PFX в PEM
openssl pkcs12 -in certificate.pfx -nocerts -nodes -out certificate.pem
openSSL pkcs8 -in certificate.pem -topk8 -nocrypt -out certificate.pk8
Конвертирование P7B в PFX
Для этого требуется выполнение двух команд
1. Конвертирование P7B в CER
openssl pkcs7 -print_certs -in certificate.p7b -out certificate.cer
openssl pkcs12 -export -in certificate.cer -inkey privateKey.key -out certificate.pfx -certfile cacert.cer
How can I convert a PFX certificate file for use with Apache on a linux server?
How can I convert a PFX certificate file for use with Apache on a linux server? I created the PFX from Windows Certificate Services. The PFX contains the entire certificate chain. (Which is just a root and the main cert, no intermediate.) Lead me, wise ones.
5 Answers 5
With OpenSSL you can convert pfx to Apache compatible format with next commands:
openssl pkcs12 -in domain.pfx -clcerts -nokeys -out domain.cer openssl pkcs12 -in domain.pfx -nocerts -nodes -out domain.key
First command extracts public key to domain.cer .
Second command extracts private key to domain.key .
Update your Apache configuration file with:
. SSLEngine on SSLCertificateFile /path/to/domain.cer SSLCertificateKeyFile /path/to/domain.key .
This is missing the command to generate the certificate authority file. The answer below is more complete.
openssl pkcs12 -in domain.pfx -clcerts -nokeys -out domain.cer openssl pkcs12 -in domain.pfx -nocerts -nodes -out domain.key
I also generated Certificate Authority (CA) certificate:
openssl pkcs12 -in domain.pfx -out domain-ca.crt -nodes -nokeys -cacerts
And included it in Apache config file:
. SSLEngine on SSLCertificateFile /path/to/domain.cer SSLCertificateKeyFile /path/to/domain.key SSLCACertificateFile /path/to/domain-ca.crt .
@Andron when I use the third command to create the CA certificate the result is an empty crt file. I tried using both the serverSSL pfx file and the rootCA pfx file for input. (bitnami wamp) The final result is that firefox gives me a The certificate is not trusted because the issuer certificate is unknown SEC_ERROR_UNKNOWN_ISSUER error.
@khargoosh as I reported in the comment: if it is empty — just don’t use/include this line. I had the same situation.
To get it to work with Apache, we needed one extra step.
openssl pkcs12 -in domain.pfx -clcerts -nokeys -out domain.cer openssl pkcs12 -in domain.pfx -nocerts -nodes -out domain_encrypted.key openssl rsa -in domain_encrypted.key -out domain.key
The final command decrypts the key for use with Apache. The domain.key file should look like this:
-----BEGIN RSA PRIVATE KEY----- MjQxODIwNTFaMIG0MRQwEgYDVQQKEwtFbnRydXN0Lm5ldDFAMD4GA1UECxQ3d3d3 LmVudHJ1c3QubmV0L0NQU18yMDQ4IGluY29ycC4gYnkgcmVmLiAobGltaXRzIGxp YWIuKTElMCMGA1UECxMcKGMpIDE5OTkgRW50cnVzdC5uZXQgTGltaXRlZDEzMDEG A1UEAxMqRW50cnVzdC5uZXQgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgKDIwNDgp MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArU1LqRKGsuqjIAcVFmQq -----END RSA PRIVATE KEY-----
How To Convert Windows PFX Certificate Files Into PEM Format On Linux
A common task we have to perform in our iPhone and Android app development projects is moving certificates around mixed platform environments, namely from Windows to Linux, or from Windows to Amazon Web Services (AWS).
For example, you may have a certificate and private key installed on a Windows Server machine and used by IIS, but how do you export it so you can then use it within Apache or NGINX running on a Linux server?
Or what about importing the certificate so you can use it to secure a HTTPs endpoint on AWS Application Load Balancer?
In this post, I will show you very quickly how to export and transform a certificate used in Windows so that it can be used in non-Windows environments.
Pre-requisites
- A Windows Server machine with an installed certificate and private key pair. The private key must have been imported and marked as Exportable, otherwise this tutorial will not work.
- OpenSSL module installed for PowerShell.
Export Certificate from Windows
1.) Open up the local machine Certificate Manager (run “certmgr” from the Windows Search box)
2.) Find your installed certificate within one of your local certificate stores, right click on it, go to All Tasks -> Export.
3.) This launches the “Certificate Export Wizard”. Within this, click Next and make sure to check the “Yes, export the private key” option.
4.) For the Export File Format, make sure to check “Personal Information Exchange – PKCS #12” and accept the default checked values underneath it.
5.) Set a password that will be used to protect the exported PFX file, note this down for later.
6.) Choose a file location and name, and hit “Finish”.
At this point you now have a .PFX file exported that contains both the public and private keys for the certificate we are looking to convert.
Convert PFX File Format to PEM Format
1.) Open up a PowerShell Command window.
2.) The first step is to export the private key from the PFX file, to do that type:
openssl pkcs12 -in .pfx -nocerts -out key.pem
This will ask you to input the password you set on the PFX file in Step 5 of the previous section. You will also be prompted to provide a new password for the generated key.pem file, just pick any password for now, we are going to remove it at the end of the tutorial.
3.) Next, we will export the certificate from the pfx file itself and put it into its own .PEM file:
openssl pkcs12 -in .pfx -clcerts -nokeys -out cert.pem
4.) Finally, we will take the output of step 2 and remove the passphrase from it:
openssl rsa -in key.pem -out server.key
The cert.pem file contains the public key of your certificate. The server.key contains the private key associated with that certificate.
Copy PEM and KEY Files to Linux
1.) Copy the cert.pem and server.key files to your Linux instance.
2.) Ensure the right permissions are set on both files:
- Set the directory permission to 700.
- Set the file permission on both the .pem and .key files to 600.
- Ensure the directory and files themselves are owned by the root user.
3.) Modify Apache or NGINX configurations to reference the above copied files.
Import Certificates into Amazon Certificate Manager
If you are looking to use the certificate within AWS as a SSL certificate on an Application Load Balancer, then you will need to first import the certificates into Amazon Certificate Manager.
2.) Click on Import Certificate
3.) In the box labelled “Certificate Body”, paste the contents of cert.pem file.
4.) In the box labelled “Certificate Private Key”, paste the contents of the server.key file.
5.) If there is an intermediate certificate authority used by your certificate then copy and paste the public key of any intermediate certificates into the Certificate Chain box.
6.) Modify your Application Load Balancer listener endpoints to use the certificate you imported in step 5.
Blue Label Labs Is Hiring
We are looking for exceptional people to join our exceptional team and build great things together.
You might also like
4.8/5
Overall Rating
© 2023 BlueLabel | All Rights Reserved – Total Rating 4.8 out of 5 based on 40+ reviews