A certificate is public: you hand it to every visitor. The private key is the secret that makes the certificate worth anything. Anyone with a CA’s private key can issue any certificate, and anyone with a server’s private key can impersonate that server. All the algorithms and protocols in this tutorial are strong; what usually fails in real incidents is that someone got hold of a key. That is why protecting keys is the real job of PKI.
Where can a private key live?
| Storage | How it works | Key can be stolen by | Typical use |
|---|---|---|---|
| Software key | A file or database row on disk (0600, maybe encrypted) | Anyone who reads the file, a backup, or the process memory | Dev and test, low-risk leaf keys, many servers |
| OS keystore / TPM / Secure Enclave | Key is created in and used by the device’s chip | Malware can use it while logged in, but cannot copy it | Laptop and device identity, attestation |
| HSM (hardware security module) | A tamper-resistant appliance or card that does crypto; keys never leave | Someone with physical and admin access and the credentials | CA keys, code signing |
| Cloud KMS | The same idea as a service (AWS KMS, Google Cloud KMS, Azure Key Vault / Managed HSM) | An attacker with permission to call the sign API | CA keys in cloud, envelope encryption |
The key principle: use, but not export. With an HSM or KMS you ask it to sign this hash; it returns a signature; the key never appears in your software. Compare a safe with a teller window: with a file on disk, an attacker who breaks into the server walks away with the key. With an HSM they can only ask the teller to sign things while they hold access, and when you cut that access, they can no longer sign anything. A server compromise becomes an incident you can end, instead of a permanent loss of the key.
Software keys, done properly
Software keys are not forbidden; for most short-lived server certificates they are the right choice. They need discipline:
- Generate on the machine that uses it; never email or chat a private key. Every copy is another place it can leak, and a key that never travelled cannot be intercepted in transit.
- Permissions
0600, owned by the service user (chmod 600 *.key), so other users and processes on the machine cannot read it. - Encrypt at rest with a key-encryption key (KEK) that is stored elsewhere. The CA’s keys sit encrypted in a database, and the KEK is held separately, so a database dump or a stolen backup is useless alone. This is what BastionXP does.
- Keep keys out of git, container images, logs and tickets. These are copied, cached and searched by many people and tools, and deleting a key from git history does not un-leak it.
- Rotate regularly, and have a tested procedure for when one leaks. Rotation limits how long a stolen key is useful. A leak plan you have never rehearsed will not work at 3 a.m.
Envelope encryption
A KMS or HSM is slow compared with a CPU, limits how much data you can send it, and may charge per call, so you do not send it your database to encrypt. Apps use envelope encryption instead, like keeping documents in a locked box and the box key in a bank vault:
- The app generates a random data key and encrypts the data with it (fast, local AES-GCM).
- The app sends only the small data key to the KMS, which encrypts it with a master key that never leaves the KMS (this is the “wrapped” key).
- You store the wrapped data key next to the data.
- To read the data, ask the KMS to unwrap the data key, then decrypt locally.
The benefit: control sits in one place. Revoking the KMS permission instantly makes all the data unreadable, and every unwrap is logged.
HSMs
An HSM is a computer built for one job, holding keys and doing crypto with them, and built so that secrets cannot be extracted: tamper-evident or tamper-responding (it wipes itself when opened), with hardware random-number generation and a strict role model, so that even a system administrator cannot just read the keys. Think of it as a bank vault with a teller window: you pass in a request, it returns an answer, and nobody takes the keys out.
| Form | Examples | Notes |
|---|---|---|
| Network appliance | Thales Luna, Entrust nShield, Utimaco | Shared by many servers; high throughput |
| PCIe card | nShield Solo, Luna PCIe | In one server |
| USB token | YubiKey HSM 2, Nitrokey HSM | Cheap; good for a root CA |
| Cloud HSM | AWS CloudHSM, Azure Managed HSM, Google Cloud HSM | Dedicated, customer-controlled |
HSM vocabulary:
- Partition / slot / token: a logical HSM inside the device, so one appliance can serve several teams who cannot see each other’s keys.
- Security Officer (SO): manages the HSM (creates partitions, sets policy) but cannot use the keys. This separates “who runs the vault” from “who uses what is inside”.
- User: uses the keys, authenticates with a PIN.
- Key ceremony: the documented, witnessed event where a root key is generated and backed up, often with M-of-N smart cards (“3 of 5 custodians must be present”). No single person can use or recover the key alone, and a record shows it was done correctly. Auditors will ask for it.
- Wrapping: exporting a key encrypted under another HSM’s key for backup or clustering. The key never exists in cleartext outside.
PKCS#11 (Cryptoki)
Every HSM maker has its own hardware and its own internal commands. If each
one needed its own integration, every application would have to be rewritten
for every vendor. PKCS#11 is the standard C API that fixes this, like
a universal plug socket: applications speak PKCS#11, and each vendor ships a
module, a shared library (libsofthsm2.so, libCryptoki2_64.so,
opensc-pkcs11.so, …), that translates to its hardware. Your software loads
the module and calls the same functions regardless of vendor, so you can
swap an HSM without changing the application.
The model:
| Concept | Meaning |
|---|---|
| Module | The vendor library you load |
| Slot | A reader or logical partition |
| Token | The thing in the slot that holds keys |
| Session | A connection; you log in with the user PIN |
| Object | A key or certificate; has attributes |
| Mechanism | An operation: ECDSA, RSA-PKCS-PSS, AES-GCM, … |
Every object in the token carries attributes, settings that the HSM enforces. They are how “never exported” is made real rather than a promise. Important attributes of a private key object:
| Attribute | Meaning |
|---|---|
CKA_SENSITIVE | The value can never be shown in cleartext |
CKA_EXTRACTABLE | If false, it can never leave, not even wrapped |
CKA_TOKEN | Persistent (true) or temporary session object (false) |
CKA_SIGN, CKA_DECRYPT, … | What the key may be used for |
CKA_LABEL / CKA_ID | How you find it |
Hands-on with SoftHSM
SoftHSM is a software HSM that implements PKCS#11, so you can learn the
workflow with no hardware (install softhsm2 and OpenSC’s pkcs11-tool).
The commands are identical for a real HSM; only the module path and PIN
differ.
$ export SOFTHSM2_CONF=$PWD/softhsm2.conf # points at a token directory
$ softhsm2-util --init-token --free --label demo --so-pin 5678 --pin 1234
The token has been initialized and is reassigned to slot 1301670441
Generate an EC key inside the token:
$ M=/opt/homebrew/lib/softhsm/libsofthsm2.so # path varies by OS
$ pkcs11-tool --module $M --login --pin 1234 --keypairgen \
--key-type EC:prime256v1 --label ca-key --id 01
Key pair generated:
Private Key Object; EC
label: ca-key
ID: 1 (0x01)
Usage: decrypt, sign, signRecover, unwrap, derive
Access: sensitive, always sensitive, never extractable, local
uri: pkcs11:model=SoftHSM%20v2;...;token=demo;id=%01;object=ca-key;type=private
Public Key Object; EC EC_POINT 256 bits
...
Read the access line: sensitive, never extractable, local. The key was created inside and cannot leave. Try to take it:
$ pkcs11-tool --module $M --login --pin 1234 --read-object --type privkey --label ca-key -o x
sorry, reading private keys not (yet) supported
You can export the public key and look at it with OpenSSL:
$ pkcs11-tool --module $M --login --pin 1234 --read-object --type pubkey --label ca-key -o hsm.pub.der
$ openssl pkey -pubin -inform DER -in hsm.pub.der -text -noout | head -3
Public-Key: (256 bit field, 128 bit security level)
pub:
04:a9:09:1c:10:be:7f:56:2b:f4:95:e3:da:8d:90:de:
And ask the token to sign:
$ echo hello > h.txt
$ pkcs11-tool --module $M --login --pin 1234 --sign --mechanism ECDSA-SHA256 \
--label ca-key -i h.txt -o h.sig
Using signature algorithm ECDSA-SHA256
List what the token supports (a real HSM lists many more, and the list depends on its FIPS mode):
$ pkcs11-tool --module $M --list-mechanisms | head -4
Supported mechanisms:
AES-CBC, keySize={16,32}, encrypt, decrypt, wrap
AES-CBC-ENCRYPT-DATA, derive
AES-CBC-PAD, keySize={16,32}, encrypt, decrypt, wrap, unwrap
PKCS#11 URIs
Rather than a file path, a key is named with a URI (RFC 7512), like the
uri: line above: pkcs11:token=demo;object=ca-key;type=private. Tools
that support it (OpenSSL via the pkcs11 provider, curl, ssh, p11tool)
take this where they would take a key file. The PIN is supplied separately
(pin-value= or an environment variable), never baked into configs you
commit.
Using the HSM from OpenSSL
Needs the pkcs11-provider (OpenSSL 3+) or the older libp11 engine,
configured to load your module. Then, for example, make a CSR for a key that
lives in the HSM:
$ openssl req -new -provider pkcs11 -provider default \
-key "pkcs11:token=demo;object=ca-key;type=private?pin-value=1234" \
-subj "/CN=hsm-test" -out hsm.csr
(The exact provider setup differs by distribution. Check your package’s docs; the PIN in a URL like this is for a lab only.)
Using the HSM in BastionXP
BastionXP can keep its CA keys in an HSM, through the vendor’s PKCS#11 library, or in AWS KMS, Google Cloud KMS or Azure Key Vault. The CA keys are created inside the HSM or KMS, and BastionXP asks it to sign; the keys never leave. Choose where the keys live before you create the CA, because a key stays where it was created: a key made in software cannot later be “moved” into an HSM without effectively making a new CA.
Cloud KMS in short
| AWS KMS | Google Cloud KMS | Azure Key Vault / Managed HSM | |
|---|---|---|---|
| Asymmetric signing keys | Yes (RSA, ECC) | Yes | Yes |
| FIPS 140 validated | Yes (140-3, per region; check the current list) | Yes (HSM protection level) | Key Vault Premium and Managed HSM |
| Authentication | IAM roles | IAM service accounts | Entra ID managed identities |
| Audit | CloudTrail | Cloud Audit Logs | Azure Monitor |
Nice properties: no hardware to run, fine-grained IAM, audit logs. The
trade-off: your trust is in the cloud provider, and the permission to call
Sign is the new “key”. Guard that IAM role like a private key.
Mistakes to avoid
- A CA key in a cloud KMS with
kms:*open to every admin. The key cannot be copied, but anyone with permission to callSigncan use it. The permission is the key. - The HSM PIN in the same file or repository as the config that uses it. Then the hardware protects nothing, because whoever reads the config can log in to the HSM.
- No backup of the HSM key (HSM dies, the CA is gone) or too many copies. Both extremes are failures: one means data loss, the other means more places for the key to leak. Use a documented, split-custody backup.
- Never testing the disaster recovery procedure. An untested restore is a hope, not a plan.
- Root CA online “just for now”. “Just for now” tends to last years, and the root is the one key that must never be reachable from a network.
- No logging of every signing operation. Without logs you cannot tell whether a certificate that you did not expect was issued by your CA.
About BastionXP
BastionXP is a cloud-native private PKI CA and device identity management platform that eliminates passwords and shared secrets by issuing hardware-attested certificates to mobile devices and laptops. Secure access to your Wi-Fi, VPN, and SaaS applications in your enterprise network. Replace legacy SCEP with automated ACME Device Attestation. No shared secrets. Zero credential theft. Learn more about BastionXP →