---
title: "Installing and configuring the Cloud HSM PKCS#11 driver"
description: "Set up the Cloud HSM PKCS#11 driver with OVHcloud IAM authorisation and endpoint failover, and find supported functions, mechanisms, attributes and limits"
url: https://docs.ovhcloud.com/en/guides/manage-and-operate/cloud-hsm/pkcs11-driver
lang: en
lastUpdated: 2026-12-02
---
> For AI agents: the complete documentation index is available at https://docs.ovhcloud.com/en/llms.txt, the full documentation bundle is available at https://docs.ovhcloud.com/en/llms-full.txt.

# Installing and configuring the Cloud HSM PKCS#11 driver

**Warning:** **Beta version** — Cloud HSM is currently in beta. Features, interfaces and procedures may change until general availability (GA), and this guide will be updated along with them. To find out more about the beta or to request access, visit the [Cloud HSM page on OVHcloud Labs](https://labs.ovhcloud.com/en/cloud-hsm/).

## Objective

Your applications use Cloud HSM through the **OVHcloud PKCS#11 driver**, a library that implements the PKCS#11 v2.40 standard (Cryptoki). Any PKCS#11-compatible application can load it, and the driver translates its calls into requests to the endpoints of your Cloud HSM cluster.

**This guide explains how to install and configure the driver, how to authorise your applications with OVHcloud IAM, and what the driver supports.**

## Requirements

- A Cloud HSM cluster with the status `READY`, its ID and the endpoints of its partitions. See [Getting started with Cloud HSM](https://docs.ovhcloud.com/en/guides/manage-and-operate/cloud-hsm/quick-start.md).
- An OVHcloud IAM token (Personal Access Token or service account OAuth2 access token) for an identity authorised on the cluster.
- A machine that can reach the endpoints of your cluster on TCP port 5697, running Linux on amd64 or arm64 with glibc 2.28 or later. These are the platforms for which the driver is provided during the beta. A Linux container or virtual machine is also suitable.

## Instructions

### Installing the driver

During the beta, the driver is provided directly to the participants, as a precompiled library for Linux on **amd64** (x86\_64) and **arm64** (aarch64): `libovhcloud_pkcs11_driver-<version>-linux-x86_64.so` or `libovhcloud_pkcs11_driver-<version>-linux-aarch64.so`. Use the build that matches the architecture of your machine. It requires glibc 2.28 or later (for example RHEL 8, Debian 10, Ubuntu 20.04 or later).

1. Copy the library to the machine that runs your application, for example to `/usr/local/lib/libovhcloud_pkcs11_driver.so`.
2. Point your PKCS#11 application at this path. Depending on the application, this is a `module`, `library` or `provider` setting, or a parameter of the function that loads the PKCS#11 library.

The driver needs no other component on the machine. The certificate presented by the Cloud HSM endpoints is issued by a public certification authority, so the system trust store is enough to validate it.

### Configuring the driver

The driver reads its configuration once, when your application initialises it (`C_Initialize`), from one of two sources:

- a **YAML file**, whose path you set in the `PKCS_CONF_FILE` environment variable. This is the recommended method: it lets you configure every endpoint of your cluster, for failover, and several slots.
- **environment variables**, when `PKCS_CONF_FILE` is not set. They configure a single slot (slot 0) with a single endpoint.

If the configuration is missing or invalid, `C_Initialize` returns `CKR_ARGUMENTS_BAD` and writes the reason to the standard error output, whatever the log level.

The driver exposes each slot as a token labelled `OVHcloud Cloud HSM <slot number>`, for example `OVHcloud Cloud HSM 0`.

#### Configuration with a YAML file (recommended)

The YAML file declares one or more **slots**. Each slot is an independent PKCS#11 token, with its own endpoints, credentials and login state.

```yaml
pkcs11:
  LogLevel: error
  Slots:
    0:
      Type: HSMGW
      AuthMethod: token
      ClusterId: "<cluster ID>"
      ServerUrl:
        - "<endpoint-a>:5697"
        - "<endpoint-b>:5697"
        - "<endpoint-c>:5697"
      Timeout: 30s
      RetryTimeout: 5s
```

```bash
export PKCS_CONF_FILE=/etc/cloud-hsm/pkcs11.yaml
```

| Parameter      | Description                                                                                                                                                                                                                                                     |
| -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `LogLevel`     | Level of the logs written to the standard error output: `off` (default), `error`, `warn`, `info`, `debug` or `trace`. When set, it takes precedence over `PKCS11_LOG_LEVEL`. An unknown value disables the logs.                                                |
| `Type`         | Always `HSMGW` for Cloud HSM.                                                                                                                                                                                                                                   |
| `AuthMethod`   | Always `token` for Cloud HSM.                                                                                                                                                                                                                                   |
| `ClusterId`    | ID of your Cloud HSM cluster (a UUID).                                                                                                                                                                                                                          |
| `ServerUrl`    | One endpoint, or a list of endpoints of your cluster, in order of preference.                                                                                                                                                                                   |
| `Pin`          | Optional. IAM token used when your application never logs in with a PIN.                                                                                                                                                                                        |
| `Timeout`      | Optional, default `30s`. Connection timeout for each endpoint, and deadline of each request. A request, its automatic retries included, ends within 3 × `Timeout`. Set it above your slowest operation, for example the generation of an RSA 4096-bit key pair. |
| `RetryTimeout` | Optional, default `5s`. After a connection to an endpoint fails (endpoint unreachable, timeout, connection lost), the driver skips this endpoint for this duration. If every endpoint is being skipped, it tries them all.                                      |

Durations are written with a unit, for example `500ms`, `30s` or `1m`.

**Warning:** If you store an IAM token in the `Pin` parameter, protect the configuration file like a password: restrict its permissions to the account that runs your application.

#### Configuration with environment variables

If `PKCS_CONF_FILE` is not set, the driver reads the following environment variables instead. This alternative configures a single slot (slot 0) with a single endpoint, without failover: use it for a quick test.

| Variable                  | Required | Description                                                                                                                                                                            |
| ------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `PKCS11_HSMGW_ENDPOINT`   | Yes      | Endpoint of a partition of your cluster, in the form `host:5697`, with the host name shown in the details of your cluster (not an IP address: it is used to validate the certificate). |
| `PKCS11_HSMGW_CLUSTER_ID` | Yes      | ID of your Cloud HSM cluster (a UUID).                                                                                                                                                 |
| `PKCS11_HSMGW_TOKEN`      | No       | IAM token used when your application never logs in with a PIN. See [Authentication](#authentication).                                                                                  |
| `PKCS11_LOG_LEVEL`        | No       | Level of the logs written to the standard error output: `off` (default), `error`, `warn`, `info`, `debug` or `trace`.                                                                  |

```bash
export PKCS11_HSMGW_ENDPOINT="<endpoint>:5697"
export PKCS11_HSMGW_CLUSTER_ID="<cluster ID>"
export PKCS11_LOG_LEVEL=error
```

#### Configuring several endpoints

List every endpoint of your cluster in `ServerUrl`, starting with the one closest to your application. The driver connects to the first available endpoint. When the connection to an endpoint fails, the driver skips it for the duration of `RetryTimeout` and uses the next one. Once `RetryTimeout` has expired, new connections go back to the first endpoint. A refusal returned by Cloud HSM (for example an authorisation error) does not make the driver skip an endpoint.

If the connection to an endpoint is lost during a session, the driver reconnects to the next available endpoint without closing the session. It automatically re-sends, up to 3 times, the requests that change nothing: signature, verification, encryption, decryption, wrapping, search and attribute reads. A key creation, import, unwrap, deletion or attribute change interrupted this way fails with `CKR_DEVICE_ERROR`, because Cloud HSM may already have performed it. Your keys remain valid on every endpoint. See the "[High availability and failover](https://docs.ovhcloud.com/en/guides/manage-and-operate/cloud-hsm/architecture.md#high-availability-and-failover)" section of the "Cloud HSM - Architecture and high availability" guide.

We recommend that your application:

- retries the operations that fail with `CKR_DEVICE_ERROR`, with an increasing delay between attempts, after checking that an interrupted key creation did not take effect;
- retries the operations that fail with `CKR_FUNCTION_FAILED` only after checking the driver logs: an IAM refusal or an IP allowlist refusal also returns `CKR_FUNCTION_FAILED`, and retrying them is useless;
- closes the session and opens a new one if an endpoint keeps returning `CKR_DEVICE_ERROR` or `CKR_SESSION_HANDLE_INVALID`;
- does not retry the operations refused for a functional reason (for example `CKR_KEY_TYPE_INCONSISTENT` or `CKR_MECHANISM_INVALID`).

**Warning:** When the last open session of a slot closes, the driver logs the slot out, and every object handle becomes invalid. After opening a new session, call `C_Login` again and find your keys again with `C_FindObjects`.

#### Connections and parallelism

Each open PKCS#11 session uses its own TLS connection to an endpoint, and the requests of a session run one at a time: open several sessions to run operations in parallel. The connections of closed sessions are kept for 60 seconds to be reused. The driver does not keep the connection of an idle session alive, and endpoints close idle connections after 10 minutes. If a firewall, a NAT gateway or a load balancer sits between your application and Cloud HSM, set its idle timeout above 10 minutes.

**Warning:** If a key creation (`C_GenerateKey`, `C_GenerateKeyPair`, `C_CreateObject` or `C_UnwrapKey`) is interrupted by a timeout or a lost connection, your application cannot know whether the key was created. Give each new key a `CKA_ID` of your choice and, before retrying the creation, search for that `CKA_ID` with `C_FindObjects`: if the key exists, use it instead of creating a second one.

### Authentication

The driver authenticates every request with an **OVHcloud IAM token**: a [Personal Access Token (PAT)](https://docs.ovhcloud.com/en/guides/manage-and-operate/iam/configure-personal-access-token-pat.md) of an IAM local user, or an OAuth2 access token obtained with a [service account](https://docs.ovhcloud.com/en/guides/account-and-service-management/account-information/authenticate-api-with-service-account.md).

The IAM token is the **PIN** of the PKCS#11 token: your application passes it to `C_Login`, and the driver sends it with every request until `C_Logout`. `C_Login` checks the token immediately with a search request, so the identity needs the `cloudHSM:pkcs11:read` action to log in. For applications that never call `C_Login`, set the token in the `Pin` parameter of the slot or in the `PKCS11_HSMGW_TOKEN` variable. A token passed to `C_Login` takes precedence over the configured one.

| Situation                                                                                    | Result                                                                                                                                                          |
| -------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| No token (no `C_Login` and no configured token)                                              | Every operation that reaches Cloud HSM returns `CKR_USER_NOT_LOGGED_IN`. Digest operations, computed locally, still work.                                       |
| Token invalid or expired                                                                     | `CKR_PIN_INCORRECT`, returned by `C_Login` or by the operation.                                                                                                 |
| Identity not authorised for the operation, or IP address not in the allowlist of the cluster | `CKR_FUNCTION_FAILED`, also at `C_Login` if the identity lacks `cloudHSM:pkcs11:read`. See [Authorisation with OVHcloud IAM](#authorisation-with-ovhcloud-iam). |

PIN management functions (`C_InitToken`, `C_InitPIN`, `C_SetPIN`) are not supported: tokens are managed in OVHcloud IAM.

### Authorisation with OVHcloud IAM

Before running a request, Cloud HSM checks with OVHcloud IAM that the identity of the token is authorised to perform it on the cluster. The administrator of the OVHcloud account holds every right. For other identities, create IAM policies in the [OVHcloud Console](https://docs.ovhcloud.com/en/guides/account-and-service-management/account-information/iam-policy-ui.md) or with the [IAM API](https://docs.ovhcloud.com/en/guides/account-and-service-management/account-information/iam-policies-api.md).

#### Cloud HSM IAM actions

**PKCS#11 operations** (`cloudHSM:pkcs11:*`):

| PKCS#11 functions                                      | Required IAM actions                                   |
| ------------------------------------------------------ | ------------------------------------------------------ |
| `C_GenerateKey`, `C_GenerateKeyPair`, `C_CreateObject` | `cloudHSM:pkcs11:create`                               |
| `C_UnwrapKey`                                          | `cloudHSM:pkcs11:create` and `cloudHSM:pkcs11:decrypt` |
| `C_FindObjects*`, `C_GetAttributeValue`                | `cloudHSM:pkcs11:read`                                 |
| `C_SetAttributeValue`                                  | `cloudHSM:pkcs11:edit`                                 |
| `C_DestroyObject`                                      | `cloudHSM:pkcs11:delete`                               |
| `C_Encrypt*`                                           | `cloudHSM:pkcs11:encrypt`                              |
| `C_Decrypt*`                                           | `cloudHSM:pkcs11:decrypt`                              |
| `C_Sign*`                                              | `cloudHSM:pkcs11:sign`                                 |
| `C_Verify*`                                            | `cloudHSM:pkcs11:verify`                               |
| `C_WrapKey`                                            | `cloudHSM:pkcs11:read` and `cloudHSM:pkcs11:encrypt`   |

The driver also sends read requests on its own: a search at `C_Login`, and an attribute read the first time it uses a key. Every identity therefore needs `cloudHSM:pkcs11:read`.

**Cluster management** with the OVHcloud API v2 (`cloudHSM:apiovh:*`):

| API call                                                        | Required IAM action             |
| --------------------------------------------------------------- | ------------------------------- |
| `GET /cloudHSM/resource`, `GET /cloudHSM/resource/{cloudHSMId}` | `cloudHSM:apiovh:resource/get`  |
| `PUT /cloudHSM/resource/{cloudHSMId}` (IP allowlist)            | `cloudHSM:apiovh:resource/edit` |

#### Example IAM policies

Apply these templates to your cluster. Its URN, in the form `urn:v1:eu:resource:cloudHSM:<cluster ID>`, is returned in the `iam.urn` field of `GET /cloudHSM/resource/{cloudHSMId}`. Replace `<identity_urn>` and `<cluster_urn>` with your values.

**Full admin**: manages the cluster and its keys, and uses the keys for every operation.

```json
{
  "name": "cloud-hsm-full-admin",
  "description": "Full access to a Cloud HSM cluster and its keys",
  "identities": ["<identity_urn>"],
  "resources": [{ "urn": "<cluster_urn>" }],
  "action": ["cloudHSM:apiovh:*", "cloudHSM:pkcs11:*"]
}
```

**Read only**: views the cluster, lists the keys and reads their public attributes, without creating, changing, deleting or using any key.

```json
{
  "name": "cloud-hsm-read-only",
  "description": "Read-only access to a Cloud HSM cluster and its keys",
  "identities": ["<identity_urn>"],
  "resources": [{ "urn": "<cluster_urn>" }],
  "action": [
    "cloudHSM:apiovh:resource/get",
    "cloudHSM:pkcs11:read"
  ]
}
```

**Crypto user**: uses existing keys to encrypt, decrypt, sign and verify, without creating, changing or deleting keys.

```json
{
  "name": "cloud-hsm-crypto-user",
  "description": "Cryptographic operations with existing Cloud HSM keys",
  "identities": ["<identity_urn>"],
  "resources": [{ "urn": "<cluster_urn>" }],
  "action": [
    "cloudHSM:pkcs11:read",
    "cloudHSM:pkcs11:encrypt",
    "cloudHSM:pkcs11:decrypt",
    "cloudHSM:pkcs11:sign",
    "cloudHSM:pkcs11:verify"
  ]
}
```

**Tip:** Narrow the crypto user profile to what each application does: an application that only signs needs `cloudHSM:pkcs11:read` and `cloudHSM:pkcs11:sign`. Always keep `cloudHSM:pkcs11:read`: without it, `C_Login` fails.

### Supported PKCS#11 functions

The driver implements Cryptoki v2.40. Unsupported functions return `CKR_FUNCTION_NOT_SUPPORTED`, except `C_SeedRandom`, which returns `CKR_RANDOM_SEED_NOT_SUPPORTED`.

| Category                   | Supported                                                                                                                                                                                                 | Not supported                                                                                    |
| -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ |
| General                    | `C_Initialize`, `C_Finalize`, `C_GetInfo`, `C_GetFunctionList`                                                                                                                                            | —                                                                                                |
| Slots and tokens           | `C_GetSlotList`, `C_GetSlotInfo`, `C_GetTokenInfo`, `C_GetMechanismList`, `C_GetMechanismInfo`, `C_WaitForSlotEvent` (slots are static: `CKR_NO_EVENT` in non-blocking mode, blocking mode not supported) | `C_InitToken`, `C_InitPIN`, `C_SetPIN`                                                           |
| Sessions                   | `C_OpenSession`, `C_CloseSession`, `C_CloseAllSessions`, `C_GetSessionInfo`, `C_Login`, `C_Logout`                                                                                                        | `C_GetOperationState`, `C_SetOperationState`                                                     |
| Objects                    | `C_CreateObject`, `C_DestroyObject`, `C_GetObjectSize`, `C_GetAttributeValue`, `C_SetAttributeValue`, `C_FindObjectsInit`, `C_FindObjects`, `C_FindObjectsFinal`                                          | `C_CopyObject`                                                                                   |
| Encryption and decryption  | `C_EncryptInit`, `C_Encrypt`, `C_EncryptUpdate`, `C_EncryptFinal`, `C_DecryptInit`, `C_Decrypt`, `C_DecryptUpdate`, `C_DecryptFinal`                                                                      | —                                                                                                |
| Signature and verification | `C_SignInit`, `C_Sign`, `C_SignUpdate`, `C_SignFinal`, `C_VerifyInit`, `C_Verify`, `C_VerifyUpdate`, `C_VerifyFinal`                                                                                      | `C_SignRecover*`, `C_VerifyRecover*`                                                             |
| Key management             | `C_GenerateKey`, `C_GenerateKeyPair`, `C_WrapKey`, `C_UnwrapKey`                                                                                                                                          | `C_DeriveKey`                                                                                    |
| Random numbers             | —                                                                                                                                                                                                         | `C_SeedRandom`, `C_GenerateRandom`                                                               |
| Digest (computed locally)  | `C_DigestInit`, `C_Digest`, `C_DigestUpdate`, `C_DigestFinal`                                                                                                                                             | `C_DigestKey`                                                                                    |
| Dual-function              | —                                                                                                                                                                                                         | `C_DigestEncryptUpdate`, `C_DecryptDigestUpdate`, `C_SignEncryptUpdate`, `C_DecryptVerifyUpdate` |

### Supported mechanisms

| Mechanism                                                                                           | Usage                                | Key size (bits) | Notes                                                                                                                                                                                                       |
| --------------------------------------------------------------------------------------------------- | ------------------------------------ | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `CKM_AES_KEY_GEN`                                                                                   | Key generation                       | 128, 192, 256   |                                                                                                                                                                                                             |
| `CKM_AES_CBC`, `CKM_AES_CBC_PAD`                                                                    | Encryption, decryption               | 128 – 256       | An IV is required.                                                                                                                                                                                          |
| `CKM_AES_GCM`                                                                                       | Encryption, decryption, wrap, unwrap | 128 – 256       | The HSM generates the IV. See [AES-GCM IV](#aes-gcm-iv). Tag length: 32, 64, 96, 104, 112, 120 or 128 bits.                                                                                                 |
| `CKM_AES_KEY_WRAP_KWP`, `CKM_AES_KEY_WRAP_PAD`                                                      | Wrap, unwrap                         | 128 – 256       | RFC 5649.                                                                                                                                                                                                   |
| `CKM_GENERIC_SECRET_KEY_GEN`                                                                        | Key generation                       | 8 – 4096        | Generates the keys used for HMAC.                                                                                                                                                                           |
| `CKM_SHA_1_HMAC`, `CKM_SHA224_HMAC`, `CKM_SHA256_HMAC`, `CKM_SHA384_HMAC`, `CKM_SHA512_HMAC`        | Signature, verification              | 8 – 4096        | Generic secret keys (`CKK_GENERIC_SECRET`) only. Size the key to the digest you use.                                                                                                                        |
| `CKM_RSA_PKCS_KEY_PAIR_GEN`                                                                         | Key pair generation                  | 2048 – 4096     | Public exponent 65537. Smaller keys are refused by the FIPS partitions (`CKR_KEY_SIZE_RANGE`).                                                                                                              |
| `CKM_RSA_PKCS`                                                                                      | Signature, verification              | 2048 – 4096     | Encryption and decryption with this mechanism are refused: use `CKM_RSA_PKCS_OAEP`.                                                                                                                         |
| `CKM_SHA256_RSA_PKCS`, `CKM_SHA384_RSA_PKCS`, `CKM_SHA512_RSA_PKCS`                                 | Signature, verification              | 2048 – 4096     |                                                                                                                                                                                                             |
| `CKM_RSA_PKCS_PSS`, `CKM_SHA256_RSA_PKCS_PSS`, `CKM_SHA384_RSA_PKCS_PSS`, `CKM_SHA512_RSA_PKCS_PSS` | Signature, verification              | 2048 – 4096     | SHA-256, SHA-384 or SHA-512, MGF1 with the same hash. The salt length is always the length of the hash: the `sLen` parameter is ignored, and `C_Verify` only accepts signatures made with this salt length. |
| `CKM_RSA_PKCS_OAEP`                                                                                 | Encryption, decryption, wrap, unwrap | 2048 – 4096     | SHA-1, SHA-256, SHA-384 or SHA-512. The OAEP hash and the MGF1 hash must be the same algorithm (`CKR_MECHANISM_PARAM_INVALID` otherwise). No label (`pSourceData`).                                         |
| `CKM_EC_KEY_PAIR_GEN`                                                                               | Key pair generation                  | 256 – 521       | Curves P-256 (`secp256r1`), P-384 (`secp384r1`) and P-521 (`secp521r1`).                                                                                                                                    |
| `CKM_ECDSA`, `CKM_ECDSA_SHA256`, `CKM_ECDSA_SHA384`, `CKM_ECDSA_SHA512`                             | Signature, verification              | 256 – 521       |                                                                                                                                                                                                             |
| `CKM_SHA_1`, `CKM_SHA256`, `CKM_SHA384`, `CKM_SHA512`, `CKM_MD5`                                    | Digest                               | —               | Computed locally by the driver, without a request to Cloud HSM.                                                                                                                                             |

#### AES-GCM IV

For AES-GCM encryption and wrapping, the HSM generates the IV itself. The driver writes it back into the `pIv` buffer of your `CK_GCM_PARAMS` structure when the operation completes (`C_Encrypt`, `C_EncryptFinal` or `C_WrapKey`):

- size the `pIv` buffer to **16 bytes**;
- keep the `CK_GCM_PARAMS` structure and its `pIv` buffer allocated until the operation ends, not only until `C_EncryptInit` returns, otherwise the driver writes into freed memory;
- store the IV with the ciphertext or the wrapped key: you need it to decrypt or unwrap.

### Keys and attributes

Every object is a token object, stored in your cluster: `CKA_TOKEN = CK_FALSE` is refused. Key pairs are returned as two objects (`CKO_PUBLIC_KEY` and `CKO_PRIVATE_KEY`) that share the same `CKA_ID`.

#### Attributes accepted when creating a key

- `CKA_LABEL`, `CKA_ID`, `CKA_CLASS`, `CKA_KEY_TYPE`;
- the usages `CKA_ENCRYPT`, `CKA_DECRYPT`, `CKA_SIGN`, `CKA_VERIFY`, `CKA_WRAP`, `CKA_UNWRAP`;
- `CKA_VALUE_LEN` (AES and generic secret keys), `CKA_MODULUS_BITS` (RSA), `CKA_EC_PARAMS` (EC, curve OID in DER);
- to import a public key with `C_CreateObject`: `CKA_MODULUS` and `CKA_PUBLIC_EXPONENT` (RSA), or `CKA_EC_PARAMS` and `CKA_EC_POINT` (EC, uncompressed point wrapped in a DER OCTET STRING: a compressed point or a bare point returns `CKR_ATTRIBUTE_VALUE_INVALID`);
- `CKA_SENSITIVE` (`CK_TRUE` only: `CK_FALSE` is refused with `CKR_ATTRIBUTE_VALUE_INVALID`), `CKA_EXTRACTABLE`.

Default values when the template does not state them:

| Attribute                             | Default                                                                                                                                                                                                |
| ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `CKA_SENSITIVE`                       | `CK_TRUE`                                                                                                                                                                                              |
| `CKA_EXTRACTABLE`                     | `CK_FALSE`: the key cannot be wrapped. Set `CKA_EXTRACTABLE = CK_TRUE` at creation if you need to wrap it.                                                                                             |
| Usages, when the template states none | AES key: encrypt and decrypt (not wrap and unwrap). Generic secret key: sign and verify. Private key: sign. Public key: verify. State `CKA_WRAP` and `CKA_UNWRAP` explicitly for a key-encryption key. |

`CKA_ID` is the identifier you choose for a key: it is stored, and you can search for the key with it. Choose one for every key you create: it lets your application find the key again, in particular after an interrupted creation. When you unwrap a secret key, state its `CKA_VALUE_LEN` in the template.

`CKA_DERIVE` is accepted in a template but ignored: no key gets the derive usage, since key derivation is not available.

#### Attributes you can change

With `C_SetAttributeValue`, in a read/write session:

| Attribute                                                                        | Change allowed                                                                                                  |
| -------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- |
| `CKA_LABEL`                                                                      | Any value                                                                                                       |
| `CKA_ID`                                                                         | Any value. Both halves of a key pair always share the same `CKA_ID`: changing it on one half changes the other. |
| `CKA_ENCRYPT`, `CKA_DECRYPT`, `CKA_SIGN`, `CKA_VERIFY`, `CKA_WRAP`, `CKA_UNWRAP` | Either way, among the usages defined for the class of the key. A key must keep at least one usage.              |
| `CKA_EXTRACTABLE`                                                                | From `CK_TRUE` to `CK_FALSE` only. This change cannot be undone.                                                |

`CKA_DERIVE` can only be set to `CK_FALSE`. Every other attribute is read-only (`CKR_ATTRIBUTE_READ_ONLY`). If one of the changes of a `C_SetAttributeValue` call is refused, the driver undoes the others, on a best-effort basis.

#### Attributes you can read

`C_GetAttributeValue` returns the label, the key type, the usages, `CKA_ID`, `CKA_UNIQUE_ID`, the size of the key (`CKA_VALUE_LEN`, `CKA_MODULUS_BITS` or `CKA_EC_PARAMS`), and the protection attributes `CKA_SENSITIVE`, `CKA_EXTRACTABLE`, `CKA_ALWAYS_SENSITIVE` and `CKA_NEVER_EXTRACTABLE`.

- **Public keys**: `CKA_MODULUS` and `CKA_PUBLIC_EXPONENT` (RSA), `CKA_EC_POINT` (EC). Use them to export a public key, for example to build a certificate signing request.
- **Private and secret keys**: the key material (`CKA_VALUE`, private exponent, etc.) is never returned: reading it returns `CKR_ATTRIBUTE_SENSITIVE`.
- `CKA_UNIQUE_ID` is the identifier that Cloud HSM gives the key. It differs between the two halves of a key pair.
- `CKA_ALLOWED_MECHANISMS` is not available, and `CKA_KEY_GEN_MECHANISM` returns `CK_UNAVAILABLE_INFORMATION`.

#### Searching for keys

`C_FindObjects` returns the keys that match every attribute of the template. You can search on the class, the key type, the label, `CKA_ID`, `CKA_UNIQUE_ID`, the key size, the curve, the usages and the protection attributes. A search on another attribute returns no result.

### Wrapping and unwrapping keys

`C_WrapKey` exports a key encrypted under another key of your cluster, and `C_UnwrapKey` imports a wrapped key into your cluster. Unwrapping is the way to import your existing secret and private keys into Cloud HSM.

| Mechanism                                       | Wrapping key                                    | Notes                                                                                                                           |
| ----------------------------------------------- | ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| `CKM_AES_KEY_WRAP_KWP` / `CKM_AES_KEY_WRAP_PAD` | AES key                                         | RFC 5649. No parameters.                                                                                                        |
| `CKM_AES_GCM`                                   | AES key                                         | The HSM generates the IV: pass a 16-byte `pIv` buffer to `C_WrapKey` and keep the IV it returns, then pass it to `C_UnwrapKey`. |
| `CKM_RSA_PKCS_OAEP`                             | RSA public key (wrap), RSA private key (unwrap) | Same constraints as for encryption: identical OAEP and MGF1 hashes, no label.                                                   |

Limits:

- The wrapping key must have the `CKA_WRAP` usage, and the unwrapping key the `CKA_UNWRAP` usage. Otherwise, the operation returns `CKR_KEY_TYPE_INCONSISTENT`.
- Only extractable keys (`CKA_EXTRACTABLE = CK_TRUE`, which is not the default) can be wrapped. Otherwise, `C_WrapKey` returns `CKR_KEY_UNEXTRACTABLE`.
- The partitions do not export private keys: wrapping an RSA or EC private key is refused.
- `CKM_AES_KEY_WRAP` (RFC 3394, without padding) is not supported: use `CKM_AES_KEY_WRAP_KWP`.
- State `CKA_CLASS`, `CKA_KEY_TYPE` and, for a secret key, `CKA_VALUE_LEN` in the unwrap template. Without `CKA_CLASS`, the key is unwrapped as a secret key, and without `CKA_KEY_TYPE`, as an AES key.
- A wrapped key larger than the size limit of an operation returns `CKR_WRAPPED_KEY_LEN_RANGE`.
- After you set `CKA_EXTRACTABLE` to `CK_FALSE`, the key can still be wrapped through another endpoint for about 30 seconds. See the "[Consistency of changes](https://docs.ovhcloud.com/en/guides/manage-and-operate/cloud-hsm/architecture.md#consistency-of-changes)" section of the "Cloud HSM - Architecture and high availability" guide.

To import a secret key, retrieve an RSA public key of your cluster (with `CKA_WRAP`), wrap your key with it outside Cloud HSM using RSA-OAEP, then unwrap it in your cluster with the matching private key (with `CKA_UNWRAP`). RSA-OAEP can only wrap a small key (about 190 bytes with an RSA 2048-bit key and SHA-256), and the partitions refuse the import of a secret or private key in plaintext.

To import an RSA or EC private key, which is too large for RSA-OAEP, proceed in two steps:

1. Import an AES key as described above, with the `CKA_UNWRAP` usage.
2. Outside Cloud HSM, wrap your private key, in PKCS#8 format (DER), with this AES key using AES-KWP (RFC 5649). Then unwrap it in your cluster with `CKM_AES_KEY_WRAP_KWP`, stating `CKA_CLASS = CKO_PRIVATE_KEY` and the matching `CKA_KEY_TYPE` (`CKK_RSA` or `CKK_EC`) in the template.

The imported private key, like any private key of your cluster, can never be exported.

### Logs

Set the `PKCS11_LOG_LEVEL` variable (or `LogLevel` in the YAML file) to have the driver write its logs to the standard error output. At the `error` level, each error is logged with its context: session, mechanism, key, template (secret values masked) and, for errors returned by Cloud HSM, the request ID (`req_id`). Include this request ID when you report a problem.

### Known limits

- **No random number generation or key derivation**: `C_GenerateRandom` and `C_DeriveKey` are not supported.
- **Size of an operation**: an operation can process at most 1 MiB − 16 KiB (1,032,192 bytes) of data, AES-GCM additional data included. Beyond that, the driver returns, before sending anything, `CKR_DATA_LEN_RANGE` for the data of an encryption, a signature or a verification, `CKR_ENCRYPTED_DATA_LEN_RANGE` for the ciphertext of a decryption and, at `C_Verify`, `CKR_SIGNATURE_LEN_RANGE` when the data and the signature together exceed the limit. Use envelope encryption for larger data.
- **Multi-part operations are not streamed**: for encryption, decryption, HMAC and the raw signature mechanisms, the driver buffers the data, `C_EncryptUpdate` and `C_DecryptUpdate` return no data, and the whole result is returned by `C_EncryptFinal` or `C_DecryptFinal`. The size limit applies to the whole data. Only the hash-and-sign mechanisms (`CKM_SHA*_RSA_PKCS`, `CKM_SHA*_RSA_PKCS_PSS`, `CKM_ECDSA_SHA*`) hash the data locally and accept any size.
- **Listing objects is slow on large partitions**: reading the attributes of every object costs one request per object. On a partition with thousands of keys, search for keys by `CKA_ID` or label instead of listing them all.
- **`fork()`**: call `C_Finalize`, or close every session, before your process forks. The child process must call `C_Initialize` itself.
- **AES-GCM IV**: a 16-byte `pIv` buffer, kept allocated until the end of the operation. See [AES-GCM IV](#aes-gcm-iv).
- **RSA-OAEP**: the OAEP hash and the MGF1 hash must be the same algorithm, and labels are not supported.
- **RSA PKCS#1 v1.5 encryption** (`CKM_RSA_PKCS` for encryption and decryption) is refused: use `CKM_RSA_PKCS_OAEP`. Signature with `CKM_RSA_PKCS` works.
- **HMAC** works only with generic secret keys (`CKM_GENERIC_SECRET_KEY_GEN`), not with AES keys.
- **Consistency between endpoints**: a deleted or modified key can keep its previous state on the other endpoints for about 30 seconds. A new key is usable on every endpoint immediately. See the "[Consistency of changes](https://docs.ovhcloud.com/en/guides/manage-and-operate/cloud-hsm/architecture.md#consistency-of-changes)" section of the "Cloud HSM - Architecture and high availability" guide.

## Go further

[Cloud HSM - Architecture and high availability](https://docs.ovhcloud.com/en/guides/manage-and-operate/cloud-hsm/architecture.md)

[Getting started with Cloud HSM](https://docs.ovhcloud.com/en/guides/manage-and-operate/cloud-hsm/quick-start.md)

[How to use IAM policies using the OVHcloud Console](https://docs.ovhcloud.com/en/guides/account-and-service-management/account-information/iam-policy-ui.md)

Join our [community of users](https://community.ovhcloud.com/).
