Pkcs12 как создать windows

A pkcs12 keystore is commonly used for both S/MIME User Certificates and SSL/TLS Server Certificates. The keystore may contain both private keys and their corresponding certificates with or without a complete chain. The keystore’s purpose is to store the credential of an identity, being a person, client, or server. Common file extensions include .p12 or .pfx for clarity, but may be anything you choose.

If you are in the market of purchasing a new SSL Certificate, start here.

RFC 7292 goes into much much much more detail about the PKCS #12 standard: https://tools.ietf.org/html/rfc7292

Unfortunately, there is not 100% coverage in all commands for maintaining PKCS #12 keystores in either OpenSSL or the Java Keytool so you must use both for comprehensive coverage of all the functions for maintaining your keystore.

The PKCS12 keystore is non-proprietary unlike the JKS and is becoming the most commonly used format. In fact, if you choose to generate a JKS keystore with the Java Keytool you will receive the following warning:

Warning:
The JKS keystore uses a proprietary format. It is recommended to migrate to PKCS12 which is an industry standard format

With that said, this post strives to provide examples to common commands used to create and manage PKCS12 keystores that will hopefully make your life on the job a bit easier.

For numerous examples of converting to and from pkcs12 that may not be covered in this article you can read more here.

Using the Java Keytool, run the following command to create the keystore with a self-signed certificate:

keytool -genkey \
  -alias somealias \
  -keystore keystore.p12 \
  -storetype PKCS12 \
  -keyalg RSA \
  -storepass somepass \
  -validity 730 \
  -keysize 4096

Keystore generation option breakdown:

Keytool option Description
-genkey Generate keystore
-alias Alias of the generated private key entry
-keystore Keystore file to be created
-storetype Type of keystore. PKCS12 in this example
-keyalg Key algorithm of key entry to be generated
-storepass Password to set on both the key entry and keystore
-validity Validity of the certificate associated with the key entry
-keysize Size of the generated private key in bits
Keytool genkey options for PKCS12 keystore

Watch the video below for a visual example of generating a pkcs12 keystore with keytool. Or head over to our focused post on how to generate a keystore with the java keytool.

java keytool generate keystore and self-signed certificate

How do I create a PKCS12 keystore from an existing private key and certificate using openssl?

While some configurations require the certificate and private key to be in separate files with pointers to them, it is becoming more common for configuration to point to a keystore instead. To create the keystore from an existing private key and certificate, run the following command. Note that if the certificate.pem file contains the entire certificate chain it will be imported into the keystore as part of the private key entry. Usually this is what you want. Alternatively, you can import the chain in a later step detailed below with the heading “How do I update the trust chain in an existing keystore for a specific keystore entry?”.

openssl pkcs12 \
  -export \
  -in certificate.pem \
  -inkey key.pem \
  -out keystore.p12
OpenSSL Option Description
pkcs12 Create pkcs12 formatted keystore
-export Export the keystore to a file
-in The existing certificate file. This may include the chain for simplicity to avoid a later step of adding it.
-inkey The existing key file
-out The name of the newly created pkcs12 keystore
OpenSSL options for creating PKCS12 keystore from an existing private key and certificate

If you are creating a keystore for an older version of Windows, older operating system, or software stack, you may be required to use the openssl pkcs12 legacy option.

How do I convert a JKS keystore to PKCS12?

This example uses the importkeystore command. For more details on this command head over to our focused post on importing an existing keystore into another keystore. To convert a Java Keystore to a PKCS #12 Keystore (.jks to .p12), run the following command:

keytool -importkeystore \
  -srckeystore keystore.jks \
  -destkeystore keystore.p12 \
  -srcstoretype JKS \
  -deststoretype PKCS12 \
  -deststorepass password \
  -srcalias alias \
  -destalias alias
Keytool Options Description
-importkeystore Import existing keystore into new keystore
-srckeystore The keystore to be imported
-destkeystore The keystore to accept the import
-srcstoretype The type of keystore to be imported
-deststoretype The type of keystore to accept the import
-deststorepass The password of the new keystore
-srcalias The alias to be imported
-destalias The alias to import to
JKS to PKCS12 keystore conversion example

How do I convert a PKCS12 keystore to JKS?

To convert a PKCS12 keystore to JKS, run the following command:

keytool -importkeystore \
  -srckeystore example.p12 \
  -srcstoretype PKCS12 \
  -destkeystore example.jks \
  -deststoretype JKS

Read more about using java keytool to import a keystore into another keystore.

How do I change the password of a PKCS12 keystore?

To change the password of a PKCS #12 keystore (make sure to also change the password of the key, if not, the keystore will be corrupt), run the following commands:

First, change the keystore password:

keytool -storepasswd -keystore keystore.p12

Finally, change the key password in that keystore for each alias:

keytool -keypasswd -alias alias -keystore keystore.p12

How do I change an alias name in a keystore?

When generating a keystore, the default alias is 1 if not explicitly set. This default value may vary based on the software used to generate the keystore. We have a focused post on changing an alias here for even more details on this command. To change the alias, run the following command:

keytool -changealias -keystore keystore.p12 -alias alias

How do I list the contents of a keystore?

It is useful and recommended to verify any changes made to a keystore. The simplest way is to just list the contents. To list the contents of the PKCS #12 keystore run the following command:

keytool -list -v -keystore keystore.p12

Some software requires a stand alone private key instead of a keystore for authentication, signing, etc. To extract the private key from a keystore, run the following command:

openssl pkcs12 -in keystore.p12 -nocerts -nodes

Note that secret keys are not supported with openssl in a pkcs12 keystore. If you attempt to extract a secret key entry you will receive the following exception: Warning unsupported bag type: secretBag.

View the video on extracting a private key from a keystore with OpenSSL for a step by step walk through.

Extract a private key from a pkcs12 keystore with openssl

Similar to requiring a stand alone key, some software requires stand alone certificate files to be used instead of a keystore. To extract a certificate or certificate chain from a PKCS12 keystore using openssl, run the following command:

openssl pkcs12 -in example.p12 -nokeys

Where -in example.p12 is the keystore and -nokeys means only extract the certificates and not the keys.

How do I update the trust chain in an existing keystore for a specific keystore entry?

You may find it useful or necessary to update a trust chain to an existing keystore entry. For example, in the event of an expiring trust chain due to a cross signed root or intermediate, you may have an expiring chain installed and need to replace it (like with the AddTrust root expiration) with Sectigo. To update the trust chain for a given alias in a pkcs12 keystore, run the following command:

keytool -import \
  -trustcacerts \
  -alias alias_to_be_updated \
  -file chain.pem \
  -keystore keystore.p12

Where -trustcacerts means the trust chain is being added to the existing entry, -alias alias_to_be_updated is the entry being updated, -file chain.pem is the complete certificate chain including the end entity certificate, all intermediate certificates, and the root certificate, and -keystore keystore.p12 is the keystore being updated.

If you encounter Error: “java.lang.exception: failed to establish chain from reply” it is likely you have not included the correct chain or the complete chain, including the root. Also, check the formatting of the chain as it is easy to miss a character in the header and/or footer of each certificate in the chain.

How to create pkcs12 truststore using OpenSSL

The key (no pun intended) to creating a pkcs12 (.p12 or .pfx) truststore or keystore is to use the -nokeys flag. Run the following command to import only a certificate into a new keystore:

openssl pkcs12 -export -out test.pfx -nokeys -in test.pem

If you encounter the following error then that means you did not supply the -nokeys flag.

unable to load private key
140022995109184:error:0909006C:PEM routines:get_name:no start line:../crypto/pem/pem_lib.c:745:Expecting: ANY PRIVATE KEY

Keystore Exceptions – PKCS12, JKS, or any type

When operating on a keystore, you will likely enter invalid input or find your keystore in a corrupt state at some point. Here are some common exceptions you may see.

When listing a keystore (and likely other operations), you may encounter this error:

keytool error: java.security.KeyStoreException: This keystore does not support probing and must be loaded with a specified type

keytool error: java.security.KeyStoreException: This keystore does not support probing and must be loaded with a specified type
java.security.KeyStoreException: This keystore does not support probing and must be loaded with a specified type
at java.base/java.security.KeyStore.getInstance(KeyStore.java:1816)
at java.base/java.security.KeyStore.getInstance(KeyStore.java:1687)
at java.base/sun.security.tools.keytool.Main.doCommands(Main.java:924)
at java.base/sun.security.tools.keytool.Main.run(Main.java:409)
at java.base/sun.security.tools.keytool.Main.main(Main.java:402)

To move past this error, simply specify the keystore type with -storetype PKCS12 (or the store type of your keystore) in your command.

Create PKCS12 keystore with Java

There are many reasons you may need to generate a keystore with Java instead of on the command line. As part of your Java application you may be issuing certificates, keys, keystores, etc. and need to generate a keystore programmatically. Additionally it may be useful to generate a new keystore in a test environment to not have a static keystore sitting around that will likely contain expired certificates at some point.

Here is some Java code to programmatically create the Keystore. For the complete example, review the GitHub project at https://github.com/misterpki/generate-keystore

public static KeyStore generatePKCS12KeyStore(final String password)
    throws KeyStoreException, NoSuchAlgorithmException, IOException, CertificateException, OperatorCreationException
  {
    final KeyStore keyStore = KeyStore.getInstance("PKCS12");
    keyStore.load(null, password.toCharArray());
    // Create Symmetric key entry
    final KeyGenerator aesGenerator = KeyGenerator.getInstance("AES");
    aesGenerator.init(128);
    final KeyStore.SecretKeyEntry aesSecretKey = new KeyStore.SecretKeyEntry(aesGenerator.generateKey());
    final KeyStore.ProtectionParameter aesSecretKeyPassword =
      new KeyStore.PasswordProtection(password.toCharArray());
    // Add symmetric key to keystore
    keyStore.setEntry("symm-key", aesSecretKey, aesSecretKeyPassword);
    // Create Asymmetric key pair
    final KeyPair asymmetricKeys = KeyPairGenerator.getInstance("RSA").generateKeyPair();
    final KeyStore.PrivateKeyEntry privateKey =
      new KeyStore.PrivateKeyEntry(
        asymmetricKeys.getPrivate(),
        new X509Certificate[]{generateX509Certificate(asymmetricKeys)});
    final KeyStore.ProtectionParameter privateKeyPassword =
      new KeyStore.PasswordProtection(password.toCharArray());
    // Add asymmetric key to keystore
    keyStore.setEntry("asymm-key", privateKey, privateKeyPassword);
    return keyStore;
  }

Another example (not recommended) but for general demonstration.

package com.misterpki;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SignatureException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import sun.security.tools.keytool.CertAndKeyGen;
import sun.security.x509.X500Name;
public class Main {
  public static void main(String[] args) throws Exception {
    try (final FileOutputStream stream = new FileOutputStream("keyStore.p12")) {
      generatePKCS12().store(stream, "changeit".toCharArray());
    }
  }
  private static KeyStore generatePKCS12() throws NoSuchProviderException,
    NoSuchAlgorithmException,
    KeyStoreException,
    InvalidKeyException,
    IOException,
    CertificateException,
    SignatureException
  {
    final KeyStore keyStore = KeyStore.getInstance("PKCS12");
    keyStore.load(null, new char[0]);
    final CertAndKeyGen certGenerator = new CertAndKeyGen("RSA", "SHA256WithRSA", null);
    certGenerator.generate(4096);
    //validity of 1 year
    final long validSecs = (long) 365 * 24 * 60 * 60;
    final X509Certificate certificate = certGenerator.getSelfCertificate(
      new X500Name("CN=some_name,O=some_org,L=some_city,C=some_country"), validSecs);
    keyStore.setKeyEntry("alias",
      certGenerator.getPrivateKey(),
      "changeit".toCharArray(),
      new X509Certificate[]{certificate});
    return keyStore;
  }
}

Conclusion

Please comment with questions and suggestions for additional pkcs12 openssl and java keytool commands that may be helpful so that we may provide as valuable content as possible.

Read all blog content.

This post is about creating PKCS #12 to serve e.g. your content via HTTPS in your application itself or in another web container (such a Tomcat or another application server).

The PKCS #12 format is a binary format for storing cryptography objects. It usually contains the server certificate, any intermediate certificates (i.e. chain of trust), and the private key, all of them in a single file. A PKCS #12 file may be encrypted and signed. PKCS #12 files are usually found with the extensions .pfx and .p12.

The PKCS #12 is similar to JKS format, but you can use it not only in Java but also in other libraries in C, C++ or C# etc, so I prefer this type of a keystore to be more general.

To use PKCS #12 inside your application, you have two way how to do it:

  • Create your own self-signed SSL certificate
  • Create a certificate using the Certificate Signing Request (CSR, a.k.a PKCS #10)

The first option is fast and simple, but not suitable for production environment. The second option is about creating CSR to be signed by any trusted Certificate Authority (CA).

Create your own self-signed SSL certificate

When you need to create a new certificate as quickly as possible, run the following two commands:

Generate a private key and a certificate in separated files using PEM format

openssl req -x509 -newkey rsa:4096 -keyout myPrivateKey.pem -out myCertificate.crt -days 3650 -nodes

openssl – the command for executing OpenSSL.

req – certificate request and certificate generating utility in OpenSSL.

-x509 – used to generate a self-signed certificate.

-newkey rsa:4096 — option to create a new certificate request and a new private key, rsa:4096 means generating an RSA key nbits in size.

-keyout myPrivateKey.pem – use the private key file myPrivateKey.pem as the private key to combining with the certificate.

-out myCertificate.crt – use myCertificate.crt as the output certificate name.

-days 3650 – specifies the number of days to certify the certificate for.

-nodes — a created private key will not be encrypted.

Combine a private key and a certificate into one key store in the PKCS #12 format

openssl pkcs12 -export -out keyStore.p12 -inkey myPrivateKey.pem -in myCertificate.crt

openssl – the command for executing OpenSSL.

pkcs12 – the PKCS #12 utility in OpenSSL.

-export — the option specifies that a PKCS #12 file will be created.

-out keyStore.p12 – specifies a filename to write the PKCS #12 file to.

-inkey myPrivateKey.pem – file to read private key from.

-in myCertificate.crt – the filename to read the certificate.

The wizard will prompt you for an export password. If filled, this password will be used as a key store password.

And that is all you need, use keyStore.p12 in your application.

Create a certificate using the Certificate Signing Request

Generate a private key and a certificate signing request into separated files

openssl req -new -newkey rsa:4096 -out request.csr -keyout myPrivateKey.pem -nodes

openssl – the command for executing OpenSSL.

req – certificate request and certificate generating utility in OpenSSL.

-newkey rsa:4096 — option to create a new certificate request and a new private key, rsa:4096 means generating an RSA key nbits in size.

-keyout myPrivateKey.pem – use the private key file myPrivateKey.pem as the private key to combining with the certificate.

-out request.csr – use request.csr as the certificate signing request in the PKCS #10 format.

-nodes — a created private key will not be encrypted.

Generate a certificate signing request from an existing private key

openssl req -new -key myPrivateKey.pem -out request.csr

openssl – the command for executing OpenSSL.

req – certificate request and certificate generating utility in OpenSSL.

-new — generates a new certificate request.

-key myPrivateKey.pem – specifies the file to read the private key from.

-out request.csr – use request.csr as the certificate signing request in the PKCS#10 format.

Now it is time to send request.csr as a result of the previous step to your CA (Certificate Authority) to be signed.

You are almost done. When you get a new certificate for your request.csr from your CA, use it together with a private key to create a PKCS#12 file:

Combine a private key and a certificate into one key store in the PKCS #12 format

openssl pkcs12 -export -out keyStore.p12 -inkey privateKey.pem -in certificate.crt -certfile CA.crt

openssl – the command for executing OpenSSL.

pkcs12 – the PKCS #12 utility in OpenSSL.

-export — the option specifies that a PKCS #12 file will be created.

-out keyStore.p12 – specifies a filename to write the PKCS #12 file to.

-inkey myPrivateKey.pem – file to read private key from.

-in myCertificate.crt – the filename to read the certificate.

-certfile CA.crt – optional parameter to read additional certificates from, useful to create a complete trust chain.

The output file keyStore.p12 is what you need to add to your application. When you filled an export password use it as a key store password in a configuration file.

The following instructions will guide you through the process of generating a PFX or P12 file using OpenSSL commands.

OpenSSL Instructions

To complete the instructions below you will need to have OpenSSL installed on your computer. Windows users can download a copy of the OpenSSL installer here: Wiki OpenSSL

For OSX users, OpenSSL should be installed by default on your machine. 

After you have downloaded and installed the exe or MSI file, click on the Windows key or on your keyboard or click on the Windows Icon in your lower left corner of your screen and type: OpenSSL

The following result should be displayed: Win64 OpenSSL Command Prompt app.

Clicking the app will open a command line console as shown, the default location will be c:\users\%username%\

Please note, this is the default location where your CSR and Private key will be saved.

To create an P12 file or a PFX file, copy the following to the command line with your own specifics:

Create a PFX file:

openssl pkcs12 -export -out certificate.pfx -inkey privateKey.key -in certificate.crt

Create a P12 file:

openssl pkcs12 -export -out certificate.p12 -inkey privateKey.key -in certificate.crt

  1. Certificate.pfx = The PFX file that will be created after the query has been completed successful. You can change it also to .p12 extension id needed.
  2. PrivateKey.key = The Private key you have saved after creating your CSR.
  3. Certificate.crt = The certificate file you received after completing all validation steps in the order.

Example:

Here is the plain text version of the example, we have copied and paste into our terminal:

openssl pkcs12 -export -out c:\createpfx\certificate.pfx -inkey c:\createpfx\private.key -in c:\createpfx\certificate.crt

Note:  This openssl command created 1 file certificate.pfx in the folder c:\createpfx.

Example P12 and PFX:

Note: This article does not apply to SSL.com code signing and document signing certificates. These types of certificates cannot be generated as .pfx files and their private keys cannot be exported. SSL.com code signing and document signing certificates and their private keys can only be generated and stored in the eSigner cloud signing environment, a Yubikey device, or a supported Cloud HSM.

In cryptography, the PKCS#12 or PFX format is a binary format often used to store all elements of the chain of trust, such as the server certificate, any intermediate certificates, and the private key into a single encryptable file. PFX files are usually found with the extensions .pfx and .p12. PFX files are typically used on Windows and macOS machines to import and export certificates and private keys.

Requirements

  • The original private key used for the certificate
  • A PEM (.pem, .crt, .cer) or PKCS#7/P7B (.p7b, .p7c) File
  • OpenSSL (included with Linux/Unix and macOS, and easily installed on Windows with Cygwin)

The commands below demonstrate examples of how to create a .pfx/.p12 file in the command line using OpenSSL:

PEM (.pem, .crt, .cer) to PFX

openssl pkcs12 -export -out certificate.pfx -inkey privateKey.key -in certificate.crt -certfile more.crt

Breaking down the command:

  • openssl – the command for executing OpenSSL
  • pkcs12 – the file utility for PKCS#12 files in OpenSSL
  • -export -out certificate.pfx – export and save the PFX file as certificate.pfx
  • -inkey privateKey.key – use the private key file privateKey.key as the private key to combine with the certificate.
  • -in certificate.crt – use certificate.crt as the certificate the private key will be combined with.
  • -certfile more.crt – This is optional, this is if you have any additional certificates you would like to include in the PFX file.

After entering the command, you will be prompted to enter and verify an export password to protect the PFX file. Remember this password! You will need it when you wish to export the certificates and key.

If you are creating a PFX to install on Azure Web Apps, or another service requiring a PFX file for SSL/TLS installation, it is recommended to include a full chain of trust in your PFX. You can do this by downloading the Apache download link from your SSL.com account, and including both your website certificate and the file named ca-bundle-client.crt in your PFX file. For example:

openssl pkcs12 -export -out certificate.pfx -inkey privateKey.key -in certificate.crt -certfile ca-bundle-client.crt

PKCS#7/P7B (.p7b, .p7c) to PFX

P7B files cannot be used to directly create a PFX file. P7B files must be converted to PEM. Once converted to PEM, follow the above steps to create a PFX file from a PEM file.

openssl pkcs7 -print_certs -in certificate.p7b -out certificate.crt

Breaking down the command:

  • openssl – the command for executing OpenSSL
  • pkcs7 – the file utility for PKCS#7 files in OpenSSL
  • -print_certs -in certificate.p7b – prints out any certificates or CRLs contained in the file.
  • -out certificate.crt – output the file as certificate.crt

Note: You can also use OpenSSL to extract the certificates and private key from a PKCS#12/PFX file.

Video

Thank you for choosing SSL.com! If you have any questions, please contact us by email at Support@SSL.com, call 1-877-SSL-SECURE, or just click the chat link at the bottom right of this page. You can also find answers to many common support questions in our knowledgebase.

For more helpful how-tos and the latest cybersecurity news, subscribe to SSL.com’s newsletter here: 

Create a pkcs12 (.pfx or .p12) from OpenSSL files (.pem , .cer, .crt…)

You have a private key file in an openssl format and have received your SSL certificate. You’d like now to create a PKCS12 (or .pfx) to import your certificate in an other software?

Here is the procedure!

  • Retrieve the private key file (xxx.key) (previously generated along with the CSR).

    NOTE: you can convert your .pkey file in a .key one with our tool to decipher private keys.

    The command can handle a .pkey as well. You’ll have to provide the key password in this case.
  • Download the .pem file on your certificate status page («View certificate» button then «View the X509 certificate with its chain» and click the download link).
  • Create the pkcs12 file that will contain your private key and the certification chain:
    openssl pkcs12 -export -legacy -inkey your_private_key.key -in pem-file.pem -name my_name -out final_result.pfx
    

    You will be asked to define an encryption password for the archive (it is mandatory to be able to import the file in IIS). You may also be asked for the private key password if there is one!

You can now use the result_final.pfx file in any software that accepts pkcs12 as input!

Alternatively, if you want to generate a PKCS12 from a certificate file (cer/pem), a certificate chain (generally pem or txt), and your private key, you need to use the following command:

openssl pkcs12 -export -legacy -inkey your_private_key.key -in your_certificate.cer -certfile your_chain.pem -out final_result.pfx

You get the «pkcs12: Unrecognized flag legacy» error?

In this case, remove the «-legacy» parameter from the commands above

The version 3 of openSSL needs the «-legacy» parameter to generate a PFX compatible with older software. The version 1 of openSSL generate a compatible PFX directly.

Technical parameters of a PFX

use the following command to display the technical parameters of a PFX for debug:

openssl pkcs12 -noout -info -in file.pfx

Linked Documentation:

  • Make sure your certificate matches the private key
  • Extract the private key and its certificate (PEM format) from a PFX or P12 file (#PKCS12 format)
  • Install a certificate (PEM / X509, P7B, PFX, P12) on several server platforms
  • Install Open SSL on windows
  • OpenSSL manual
  • Harica tool to create a p12 file from certificate and private key files

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Сравнение смартфонов windows phone
  • Офисные программы для windows обучение
  • Как проверить видеокарту на ошибки в windows 10
  • Стандартный просмотрщик изображений для windows 10
  • Windows store проверьте подключение