Linux pfx to key

junxy / Howto convert a PFX to a seperate .key & .crt file.md

What this command does is extract the private key from the .pfx file. Once entered you need to type in the importpassword of the .pfx file. This is the password that you used to protect your keypair when you created your .pfx file. If you cannot remember it anymore you can just throw your .pfx file away, cause you won’t be able to import it again, anywhere!. Once you entered the import password OpenSSL requests you to type in another password, twice!. This new password will protect your .key file.

Now let’s extract the certificate:

openssl pkcs12 -in [yourfile.pfx] -clcerts -nokeys -out [certificate.crt]

Just press enter and your certificate appears.

Now as I mentioned in the intro of this article you sometimes need to have an unencrypted .key file to import on some devices. I probably don’t need to mention that you should be carefully. If you store your unencrypted keypair somewhere on an unsafe location anyone can have a go with it and impersonate for instance a website or a person of your company. So always be extra careful when it comes to private keys! Just throw the unencrypted keyfile away when you’re done with it, saving just the encrypted one.

openssl rsa -in Linux pfx to key -out Linux pfx to key

  • When you first extract the key, apply a new password (probably the same as you used to extract it) and then create an unencrypted key with the rsa command above
  • Use an encrypted key file for NGINX otherwise it’ll ask for the password every time it is restarted.
  • Check the top of the extract .crt file for extra bits above the —-BEING. line and remove if necessary
  • This certificated needs to be concatenated with the full chain of certificate authorities cat domain.crt CA_bundle.crt > final.crt
  • test the cert with openssl s_client -showcerts -connect www.domain.com:443

Источник

Вики 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 в большинстве случаев не требуется и может быть удалён.

Читайте также:  Zoom linux на русском

Проверено на следующих конфигурациях:

Автор первичной редакции:
Алексей Максимов
Время публикации: 14.12.2021 18:24

Источник

How to convert a .pfx to .crt & .key file using OpenSSL with a few commands

Looking for a way to convert a .pfx certificate file into a .crt & .key file using OpenSSL? Look no further! This short and easy step-by-step guide will show you how it’s done in only 3 commands.

Convert .pfx to .crt & key file, .pfx to .crt, .pfx to .key

In this tutorial, I will show you how to convert a .pfx file to a .crt & .key file for use on your server or computer’s certificate store using OpenSSL. The best part of this is that OpenSSL is absolutely FREE to use! 🥳

Introduction 🚀

Every year our certificates must be renewed and I just encountered this task myself in one of my production environments. I thought writing a quick tutorial on how this is done on a Linux server using OpenSSL would be a good idea.

OpenSSL is a robust and well-documented, full-featured toolbox for working with the Secure Socket Layer (SSL) and Transport Layer Security (TLS) protocols for security. OpenSSL contains a lot of tools for handling cryptography which makes it an ideal choice when we have to work with certificates on both Linux and Windows.

In this case, I already had the .pfx certificate issued by a trusted public certificate authority like DigiCert. There are plenty of certificate authorities out there providing different pricing levels, etc. I’m sure you already got the certificate since you are here.

Below are the commands you have to perform to convert your .pfx certificate to a .crt and .key file without getting a headache. Before we begin, let’s have a look at some requirements.

Requirements 🗳️

Below is a list of the things you must bring together in order to follow along in this tutorial.

  • OpenSSL has to be installed on your machine. You can read more here: https://www.openssl.org/source/
  • The .pfx file and the import password for the certificate.
  • A server/computer with either Linux or Windows installed to run the OpenSSL package for converting the certificate.

Get the private .key from the .pfx certificate

The command below will extract the private key from the .pfx file using OpenSSL. All you have to do is enter the command and the import password you created when the certificate was issued originally.

Читайте также:  Linux write file to socket

When you are prompted to enter a PEM pass phrase for protecting the .key file, you are free to specify any password you would like. I prefer to use the same as the one I have set for the import password as it makes it easier to remember. But it’s totally up to you. 🙌

openssl pkcs12 -in [certificate.pfx] -nocerts -out Linux pfx to key

What’s happening above? 🤔

  • openssl — This is the command used to invoke the OpenSSL toolkit.
  • pkcs12 — It is an OpenSSL command that handles PKCS 12 files, which are a type of archive format used to store cryptographic objects such as certificates, private keys, and related information.
  • -in [certificate.pfx] — This option specifies the input PKCS 12 file, denoted by [certificate.pfx] . The file you provide here should be in the PKCS 12 format and contain one or more certificates, along with the corresponding private key and possibly additional information. This is the .pfx certificate file you got from your certificate authority.
  • -nocerts — This option tells OpenSSL to exclude the certificates from the output. When this flag is used, only the private key and any additional private key-related information will be processed and included in the output file.
  • -out Linux pfx to key — This option specifies the output file where the encrypted private key will be stored. The Linux pfx to key represents the filename you want to give to the encrypted private key file. OpenSSL will generate or overwrite this file with the encrypted private key.

You should get an output like mine below.

[email protected]:~/certificates$ openssl pkcs12 -in twc-certificate.pfx -nocerts -out twc-private.key Enter Import Password: Enter PEM pass phrase: Verifying — Enter PEM pass phrase: [email protected]:~/certificates$

When you enter the password in the Import Password and PEM pass phrase , you won’t be able to see the password, but it’s there. Just hit ENTER when you are done typing in your password. You will be asked to enter it twice to make sure you don’t make any typos.

Get the decrypted .key file from the encrypted private .key file

To get the decrypted .key file for the certificate ( .crt ) we will extract in a moment, we have to run a simple command and provide the PEM password we specified before.

The output will be the decrypted-certificate.key file you can use in combination with the .crt file. Below is the command you have to perform to get the decrypted .key file.

openssl rsa -in Linux pfx to key -out Linux pfx to key 

What happens in the command above? 🤔

  • openssl — This is the command used to invoke the OpenSSL toolkit.
  • rsa — This OpenSSL command specifically deals with RSA keys.
  • -in Linux pfx to key — This option specifies the input file containing the encrypted RSA private key. The Linux pfx to key represents the filename of the encrypted private key file you want to decrypt.
  • -out Linux pfx to key — This option specifies the output file where the decrypted RSA private key will be saved. The Linux pfx to key represents the filename you want to give to the decrypted private key file. OpenSSL will create or overwrite this file with the decrypted private key.
Читайте также:  Linux с сохранением настроек

You should get an output like mine below.

[email protected]:~/certificates$ openssl rsa -in twc-private.key -out twc-decrypted.key Enter pass phrase for twc-private.key: writing RSA key

You now have a decrypted .key file that you can use with your .crt file. Let’s go and extract the .crt from the .pfx file.

Get the .crt file from the .pfx file

Now that we have extracted the private .key file from our .pfx file , we should get the .crt file . Run the command below and adjust it according to your namings.

openssl pkcs12 -in [certificate.pfx] -clcerts -nokeys -out [certificate.crt]

What happens in the command above? 🤔

  • openssl — This is the command used to invoke the OpenSSL toolkit.
  • pkcs12 — This OpenSSL command deals with PKCS 12 files.
  • -in [certificate.pfx] — This option specifies the input PKCS 12 file from which the command will extract certificates.
  • -clcerts — This option instructs OpenSSL to include only the client (user) certificates from the PKCS#12 file. It excludes any CA (Certificate Authority) certificates that might be present. This option is useful when you want to extract only the user certificates for use in client authentication scenarios, for example, when configuring a client to present its certificate to a server.
  • -nokeys — This option tells OpenSSL not to include any private keys in the output. It ensures that only certificates are processed and included in the resulting file.
  • -out [certificate.crt] — This option specifies the output file where the extracted certificate(s) will be saved. The [certificate.crt] represents the filename you want to give to the certificate file. OpenSSL will create or overwrite this file with the extracted certificate(s).

You should get an output like mine below.

[email protected]:~/certificates$ openssl pkcs12 -in twc-certificate.pfx -clcerts -nokeys -out twc-certificate.crt Enter Import Password: 

Bam! 💪 You can now use the .crt file with the .key file on your server/computer to host web applications securely. Install them and power up your solution. 🔥

Summary

In this quick tutorial about converting/extracting a .pfx file to a .crt and .key file you learned a few simple commands. These commands will make it easy for you to perform the extraction process of the certificate files.

If you got any issues, questions, or suggestions for this tutorial, please let me know in the comments below. (available once you sign up for TWC) — Until next time — Happy engineering! ✌️

Christian Schou

My name is Christian. I am a 27-year-old pragmatic software engineer with a passion for .NET, Cloud, and Containers. In my spare time, I share my knowledge and love teaching other people about tech.

Источник

Оцените статью
Adblock
detector