TL;DR
This guide shows you how to create a PKCS#12 (.P12) file – often needed for applications requiring both your certificate and its private key – using a certificate stored locally and a private key held securely within a Hardware Security Module (HSM). We’ll use OpenSSL, which is available on most systems.
Steps
- Prerequisites: You’ll need:
- OpenSSL installed. Check with
openssl version. If not present, install it using your system’s package manager (e.g., `apt-get install openssl` on Debian/Ubuntu, `brew install openssl` on macOS).
- Your certificate file (usually .crt or .pem format).
- The HSM key pointer/label. This is how your software identifies the private key within the HSM. Important: You won’t directly see the key itself; you’ll interact with it through the HSM interface.
- Access to the HSM and its associated PKCS#11 library (usually a .so or .dll file).
- OpenSSL installed. Check with
- Configure OpenSSL for your HSM: OpenSSL needs to know where to find your HSM’s library. Create an `openssl.cnf` configuration file (or modify an existing one) with the following:
[pkcs11] module = /path/to/your/pkcs11.so pin = your_hsm_pinReplace `/path/to/your/pkcs11.so` with the actual path to your HSM’s PKCS#11 library and `your_hsm_pin` with your HSM user PIN.
- Find the Key Label within the HSM: Use OpenSSL to list the keys available in your HSM.
openssl pkcs11 -t key -v -l | grep -i 'your_key_name'Replace `your_key_name` with a portion of the expected key name. This command will output details about keys in your HSM, including their labels. Note down the exact label that corresponds to the private key you want to use.
- Create the P12 File: Now, combine the certificate and the HSM-backed private key into a .P12 file.
openssl pkcs12 -export -out your_output.p12 -inkey "pkcs11:label=your_key_label" -in your_certificate.crt -certfile your_certificate.crtReplace:
- `your_output.p12`: The desired filename for the P12 file.
- `your_key_label`: The key label you identified in Step 3. Enclose it in double quotes if it contains spaces or special characters.
- `your_certificate.crt`: The path to your certificate file.
You will be prompted for the P12 export password. Choose a strong password and remember it!
- Verify the P12 File: Check that the P12 file contains both the certificate and private key.
openssl pkcs12 -info -in your_output.p12This command will display information about the contents of the .P12 file, including details about the certificate chain and whether a private key is present.
- Important Security Notes:
- Protect your `openssl.cnf` file as it contains your HSM PIN. Restrict access to this file.
- Never share your P12 file with untrusted parties. It grants full control of your private key.
- Consider using a password manager to securely store the P12 export password.

