

# Using previous SDK version to work with AWS CloudHSM
<a name="choose-client-sdk"></a>

****  
 SDK versions 5.8.0 and earlier have reached their end of support. After March 31, 2025 documentation for SDK versions 3.4.4 and earlier will no longer be available.

 AWS CloudHSM includes two major Client SDK versions: 
+ Client SDK 5: This is our latest and default Client SDK. For information on the benefits and advantages it provides, see [Benefits of AWS CloudHSM Client SDK 5](client-sdk-5-benefits.md).
+ Client SDK 3: This is our older Client SDK. It includes a full set of components for platform and language-based applications compatibility and management tools.

For instructions on migrating from Client SDK 3 to Client SDK 5, see [Migrating from AWS CloudHSM Client SDK 3 to Client SDK 5](client-sdk-migration.md).

This topic describes Client SDK 3. To see what version of Client SDK you're using, see [Check your AWS CloudHSM Client SDK versionTo check the client daemon version](check-client_version.md).

To download, see [Downloads for AWS CloudHSM Client SDK](client-history.md).

**Topics**
+ [Upgrade AWS CloudHSM Client SDK 3 on Linux](client-upgrade.md)
+ [AWS CloudHSM Client SDK 3 supported platforms](sdk3-support.md)
+ [PKCS \$111 library for AWS CloudHSM Client SDK 3](pkcs11-v3-library.md)
+ [OpenSSL Dynamic Engine for AWS CloudHSM Client SDK 3](openssl3-install.md)
+ [JCE provider for AWS CloudHSM Client SDK 3](java-library_3.md)
+ [Cryptography API: Next Generation (CNG) and key storage providers (KSP) for AWS CloudHSM](ksp-v3-library.md)

# Upgrade AWS CloudHSM Client SDK 3 on Linux
<a name="client-upgrade"></a>

****  
 SDK versions 5.8.0 and earlier have reached their end of support. After March 31, 2025 documentation for SDK versions 3.4.4 and earlier will no longer be available.

With AWS CloudHSM Client SDK 3.1 and higher, the version of the client daemon and any components you install must match to upgrade. For all Linux-based systems, you must use a single command to batch upgrade the client daemon with the same version of the PKCS \$111 library, the Java Cryptographic Extension (JCE) provider, or the OpenSSL Dynamic Engine. This requirement does not apply to Windows-based systems because the binaries for the CNG and KSP providers are already included in the client daemon package. 

## To check the client daemon version
<a name="check-client-version"></a>
+ On a Red Hat-based Linux system (including Amazon Linux and CentOS), use the following command:

  ```
  rpm -qa | grep ^cloudhsm
  ```
+ On an Debian-based Linux system, use the following command:

  ```
  apt list --installed | grep ^cloudhsm
  ```
+ On a Windows system, use the following command:

  ```
  wmic product get name,version
  ```

**Topics**
+ [Prerequisites](#client-upgrade-prerequisites)
+ [Step 1: Stop the client daemon](#client-stop)
+ [Step 2: Upgrade the client SDK](#upgrade-commands)
+ [Step 3: Start the client daemon](#client-start)

## Prerequisites
<a name="client-upgrade-prerequisites"></a>

Download the latest version of AWS CloudHSM client daemon and choose your components.

**Note**  
You do not have to install all the components. For every component you have installed, you must upgrade that component to match the version of the client daemon.

### Latest Linux client daemon
<a name="download-client"></a>

------
#### [ Amazon Linux ]

```
wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/EL6/cloudhsm-client-latest.el6.x86_64.rpm
```

------
#### [ Amazon Linux 2 ]

```
wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/EL7/cloudhsm-client-latest.el7.x86_64.rpm
```

------
#### [ CentOS 7 ]

```
sudo yum install wget
```

```
wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/EL7/cloudhsm-client-latest.el7.x86_64.rpm
```

------
#### [ CentOS 8 ]

```
sudo yum install wget
```

```
wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/EL8/cloudhsm-client-latest.el8.x86_64.rpm
```

------
#### [ RHEL 7 ]

```
sudo yum install wget
```

```
wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/EL7/cloudhsm-client-latest.el7.x86_64.rpm
```

------
#### [ RHEL 8 ]

```
sudo yum install wget
```

```
wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/EL8/cloudhsm-client-latest.el8.x86_64.rpm
```

------
#### [ Ubuntu 16.04 LTS ]

```
wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/Xenial/cloudhsm-client_latest_amd64.deb
```

------
#### [ Ubuntu 18.04 LTS ]

```
wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/Bionic/cloudhsm-client_latest_u18.04_amd64.deb
```

------

### Latest PKCS \$111 library
<a name="download-pkcs11"></a>

------
#### [ Amazon Linux ]

```
$ wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/EL6/cloudhsm-client-pkcs11-latest.el6.x86_64.rpm
```

------
#### [ Amazon Linux 2 ]

```
$ wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/EL7/cloudhsm-client-pkcs11-latest.el7.x86_64.rpm
```

------
#### [ CentOS 7 ]

```
$ wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/EL7/cloudhsm-client-pkcs11-latest.el7.x86_64.rpm
```

------
#### [ CentOS 8 ]

```
$ wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/EL8/cloudhsm-client-pkcs11-latest.el8.x86_64.rpm
```

------
#### [ RHEL 7 ]

```
$ wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/EL7/cloudhsm-client-pkcs11-latest.el7.x86_64.rpm
```

------
#### [ RHEL 8 ]

```
$ wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/EL8/cloudhsm-client-pkcs11-latest.el8.x86_64.rpm
```

------
#### [ Ubuntu 16.04 LTS ]

```
$ wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/Xenial/cloudhsm-client-pkcs11_latest_amd64.deb
```

------
#### [ Ubuntu 18.04 LTS ]

```
$ wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/Bionic/cloudhsm-client-pkcs11_latest_u18.04_amd64.deb
```

------

### Latest OpenSSL Dynamic Engine
<a name="download-openssl"></a>

------
#### [ Amazon Linux ]

```
$ wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/EL6/cloudhsm-client-dyn-latest.el6.x86_64.rpm
```

------
#### [ Amazon Linux 2 ]

```
$ wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/EL7/cloudhsm-client-dyn-latest.el7.x86_64.rpm
```

------
#### [ CentOS 7 ]

```
$ wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/EL7/cloudhsm-client-dyn-latest.el7.x86_64.rpm
```

------
#### [ RHEL 7 ]

```
$ wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/EL7/cloudhsm-client-dyn-latest.el7.x86_64.rpm
```

------
#### [ Ubuntu 16.04 LTS ]

```
$ wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/Xenial/cloudhsm-client-dyn_latest_amd64.deb
```

------

### Latest JCE provider
<a name="download-java"></a>

------
#### [ Amazon Linux ]

```
$ wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/EL6/cloudhsm-client-jce-latest.el6.x86_64.rpm
```

------
#### [ Amazon Linux 2 ]

```
$ wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/EL7/cloudhsm-client-jce-latest.el7.x86_64.rpm
```

------
#### [ CentOS 7 ]

```
$ wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/EL7/cloudhsm-client-jce-latest.el7.x86_64.rpm
```

------
#### [ CentOS 8 ]

```
$ wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/EL8/cloudhsm-client-jce-latest.el8.x86_64.rpm
```

------
#### [ RHEL 7 ]

```
$ wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/EL7/cloudhsm-client-jce-latest.el7.x86_64.rpm
```

------
#### [ RHEL 8 ]

```
$ wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/EL8/cloudhsm-client-jce-latest.el8.x86_64.rpm
```

------
#### [ Ubuntu 16.04 LTS ]

```
$ wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/Xenial/cloudhsm-client-jce_latest_amd64.deb
```

------
#### [ Ubuntu 18.04 LTS ]

```
$ wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/Bionic/cloudhsm-client-jce_latest_u18.04_amd64.deb
```

------

## Step 1: Stop the client daemon
<a name="client-stop"></a>

Use the following command to stop the client daemon.

------
#### [ Amazon Linux ]

```
$ sudo stop cloudhsm-client
```

------
#### [ Amazon Linux 2 ]

```
$ sudo service cloudhsm-client stop
```

------
#### [ CentOS 7 ]

```
$ sudo service cloudhsm-client stop
```

------
#### [ CentOS 8 ]

```
$ sudo service cloudhsm-client stop
```

------
#### [ RHEL 7 ]

```
$ sudo service cloudhsm-client stop
```

------
#### [ RHEL 8 ]

```
$ sudo service cloudhsm-client stop
```

------
#### [ Ubuntu 16.04 LTS ]

```
$ sudo service cloudhsm-client stop
```

------
#### [ Ubuntu 18.04 LTS ]

```
$ sudo service cloudhsm-client stop
```

------

## Step 2: Upgrade the client SDK
<a name="upgrade-commands"></a>

The following command shows the syntax required to upgrade the client daemon and components. Before you run the command, remove any components you don't intend to upgrade.

------
#### [ Amazon Linux ]

```
$ sudo yum install ./cloudhsm-client-latest.el6.x86_64.rpm \
              <./cloudhsm-client-pkcs11-latest.el6.x86_64.rpm> \
              <./cloudhsm-client-dyn-latest.el6.x86_64.rpm> \
              <./cloudhsm-client-jce-latest.el6.x86_64.rpm>
```

------
#### [ Amazon Linux 2 ]

```
$ sudo yum install ./cloudhsm-client-latest.el7.x86_64.rpm \
              <./cloudhsm-client-pkcs11-latest.el7.x86_64.rpm> \
              <./cloudhsm-client-dyn-latest.el7.x86_64.rpm> \
              <./cloudhsm-client-jce-latest.el7.x86_64.rpm>
```

------
#### [ CentOS 7 ]

```
$ sudo yum install ./cloudhsm-client-latest.el7.x86_64.rpm \
              <./cloudhsm-client-pkcs11-latest.el7.x86_64.rpm> \
              <./cloudhsm-client-dyn-latest.el7.x86_64.rpm> \
              <./cloudhsm-client-jce-latest.el7.x86_64.rpm>
```

------
#### [ CentOS 8 ]

```
$ sudo yum install ./cloudhsm-client-latest.el8.x86_64.rpm \
              <./cloudhsm-client-pkcs11-latest.el8.x86_64.rpm> \              
              <./cloudhsm-client-jce-latest.el8.x86_64.rpm>
```

------
#### [ RHEL 7 ]

```
$ sudo yum install ./cloudhsm-client-latest.el7.x86_64.rpm \
              <./cloudhsm-client-pkcs11-latest.el7.x86_64.rpm> \
              <./cloudhsm-client-dyn-latest.el7.x86_64.rpm> \
              <./cloudhsm-client-jce-latest.el7.x86_64.rpm>
```

------
#### [ RHEL 8 ]

```
$ sudo yum install ./cloudhsm-client-latest.el8.x86_64.rpm \
              <./cloudhsm-client-pkcs11-latest.el8.x86_64.rpm> \
              <./cloudhsm-client-jce-latest.el8.x86_64.rpm>
```

------
#### [ Ubuntu 16.04 LTS ]

```
$ sudo apt install ./cloudhsm-client_latest_amd64.deb \
              <cloudhsm-client-pkcs11_latest_amd64.deb> \
              <cloudhsm-client-dyn_latest_amd64.deb> \
              <cloudhsm-client-jce_latest_amd64.deb>
```

------
#### [ Ubuntu 18.04 LTS ]

```
$ sudo apt install ./cloudhsm-client_latest_u18.04_amd64.deb \
              <cloudhsm-client-pkcs11_latest_amd64.deb> \
              <cloudhsm-client-jce_latest_amd64.deb>
```

------

## Step 3: Start the client daemon
<a name="client-start"></a>

Use the following command to start the client daemon.

------
#### [ Amazon Linux ]

```
$ sudo start cloudhsm-client
```

------
#### [ Amazon Linux 2 ]

```
$ sudo systemctl start cloudhsm-client
```

------
#### [ CentOS 7 ]

```
$ sudo systemctl start cloudhsm-client
```

------
#### [ CentOS 8 ]

```
$ sudo systemctl start cloudhsm-client
```

------
#### [ RHEL 7 ]

```
$ sudo systemctl start cloudhsm-client
```

------
#### [ RHEL 8 ]

```
$ sudo systemctl start cloudhsm-client
```

------
#### [ Ubuntu 16.04 LTS ]

```
$ sudo systemctl start cloudhsm-client
```

------
#### [ Ubuntu 18.04 LTS ]

```
$ sudo systemctl start cloudhsm-client
```

------
#### [ Ubuntu 20.04 LTS ]

```
$ sudo systemctl start cloudhsm-client
```

------

# AWS CloudHSM Client SDK 3 supported platforms
<a name="sdk3-support"></a>

****  
 SDK versions 5.8.0 and earlier have reached their end of support. After March 31, 2025 documentation for SDK versions 3.4.4 and earlier will no longer be available.

AWS CloudHSM Client SDK 3 requires a client daemon and offers command-line tools including, CloudHSM Management Utility (CMU), key management utility (KMU), and the configure tool. 

Base support is different for each version of the AWS CloudHSM Client SDK. Typically platform support for components in an SDK matches base support, but not always. To determine platform support for a given component, first make sure the platform you want appears in the base section for the SDK, then check for any exclusions or any other pertinent information in the component section.

Platform support changes over time. Earlier versions of the CloudHSM Client SDK may not support all the operating systems listed here. Use release notes to determine the operating system support for previous versions of the CloudHSM Client SDK. For more information, see [Downloads for AWS CloudHSM Client SDK](client-history.md).

AWS CloudHSM supports only 64-bit operating systems.

**Topics**
+ [Linux support for AWS CloudHSM Client SDK 3](sdk3-linux.md)
+ [Windows support for AWS CloudHSM Client SDK 3](sdk3-windows.md)
+ [HSM compatibility for AWS CloudHSM Client SDK 3](sdk3-hsm-types.md)

# Linux support for AWS CloudHSM Client SDK 3
<a name="sdk3-linux"></a>

AWS CloudHSM Client SDK 3 supports the following Linux operating systems and platforms.
+ Amazon Linux
+ Amazon Linux 2
+ CentOS 6.10\$1 2
+ CentOS 7.3\$1
+ CentOS 8 1,4
+ Red Hat Enterprise Linux (RHEL) 6.10\$1 2
+ Red Hat Enterprise Linux (RHEL) 7.3\$1
+ Red Hat Enterprise Linux (RHEL) 8 1
+ Ubuntu 16.04 LTS 3
+ Ubuntu 18.04 LTS 1

[1] No support for OpenSSL Dynamic Engine. For more information, see [OpenSSL Dynamic Engine](sdk3-compare.md#openssl-collapse).

[2] No support for Client SDK 3.3.0 and later.

[3] SDK 3.4 is the last supported release on Ubuntu 16.04.

[4] SDK 3.4 is the last supported release on CentOS 8.3\$1.

# Windows support for AWS CloudHSM Client SDK 3
<a name="sdk3-windows"></a>

AWS CloudHSM Client SDK 3 supports the following versions of Windows Server.
+ Microsoft Windows Server 2012
+ Microsoft Windows Server 2012 R2
+ Microsoft Windows Server 2016
+ Microsoft Windows Server 2019

# HSM compatibility for AWS CloudHSM Client SDK 3
<a name="sdk3-hsm-types"></a>

The following table describes AWS CloudHSM Client SDK 3 compatibility for HSMs.


| hsm1.medium | hsm2m.medium | 
| --- | --- | 
| Compatible with Client version SDK 3.1.0 and later. |  Not supported.  | 

# PKCS \$111 library for AWS CloudHSM Client SDK 3
<a name="pkcs11-v3-library"></a>

PKCS \$111 is a standard for performing cryptographic operations on hardware security modules (HSM) in AWS CloudHSM.

For information about bootstrapping, see [Connecting to the cluster](cluster-connect.md).

**Topics**
+ [Install the PKCS \$111 library](install-pkcs11-v3.md)
+ [Authenticate to the PKCS \$111 library](pkcs11-v3-pin.md)
+ [Key types](pkcs11-v3-key-types.md)
+ [Mechanisms](pkcs11-v3-mechanisms.md)
+ [API operations](pkcs11-v3-apis.md)
+ [Key attributes](pkcs11-v3-attributes.md)
+ [Code samples](pkcs11-v3-samples.md)

# Install the PKCS \$111 library for AWS CloudHSM Client SDK 3
<a name="install-pkcs11-v3"></a>

This topic provides instructions for installing the PKCS \$111 library for the AWS CloudHSM Client SDK 3 version series. For more information about the Client SDK or PKCS \$111 library, see [Using the Client SDK](use-hsm.md) and [PKCS \$111 library](pkcs11-library.md).

## Prerequisites for Client SDK 3
<a name="pkcs11-library-prerequisites"></a>

The PKCS \$111 library requires the AWS CloudHSM client.

If you haven't installed and configured the AWS CloudHSM client, do that now by following the steps at [Install the client (Linux)](cmu-install-and-configure-client-linux.md). After you install and configure the client, use the following command to start it. 

------
#### [ Amazon Linux ]

```
$ sudo start cloudhsm-client
```

------
#### [ Amazon Linux 2 ]

```
$ sudo systemctl start cloudhsm-client
```

------
#### [ CentOS 7 ]

```
$ sudo systemctl start cloudhsm-client
```

------
#### [ CentOS 8 ]

```
$ sudo systemctl start cloudhsm-client
```

------
#### [ RHEL 7 ]

```
$ sudo systemctl start cloudhsm-client
```

------
#### [ RHEL 8 ]

```
$ sudo systemctl start cloudhsm-client
```

------
#### [ Ubuntu 16.04 LTS ]

```
$ sudo systemctl start cloudhsm-client
```

------
#### [ Ubuntu 18.04 LTS ]

```
$ sudo systemctl start cloudhsm-client
```

------
#### [ Ubuntu 20.04 LTS ]

```
$ sudo systemctl start cloudhsm-client
```

------

## Install the PKCS \$111 library for Client SDK 3
<a name="install-pkcs11-library"></a>

The following command downloads and installs the PKCS \$111 library.

------
#### [ Amazon Linux ]

```
$ wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/EL6/cloudhsm-client-pkcs11-latest.el6.x86_64.rpm
```

```
$ sudo yum install ./cloudhsm-client-pkcs11-latest.el6.x86_64.rpm
```

------
#### [ Amazon Linux 2 ]

```
$ wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/EL7/cloudhsm-client-pkcs11-latest.el7.x86_64.rpm
```

```
$ sudo yum install ./cloudhsm-client-pkcs11-latest.el7.x86_64.rpm
```

------
#### [ CentOS 7 ]

```
$ wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/EL7/cloudhsm-client-pkcs11-latest.el7.x86_64.rpm
```

```
$ sudo yum install ./cloudhsm-client-pkcs11-latest.el7.x86_64.rpm
```

------
#### [ CentOS 8 ]

```
$ wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/EL8/cloudhsm-client-pkcs11-latest.el8.x86_64.rpm
```

```
$ sudo yum install ./cloudhsm-client-pkcs11-latest.el8.x86_64.rpm
```

------
#### [ RHEL 7 ]

```
$ wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/EL7/cloudhsm-client-pkcs11-latest.el7.x86_64.rpm
```

```
$ sudo yum install ./cloudhsm-client-pkcs11-latest.el7.x86_64.rpm
```

------
#### [ RHEL 8 ]

```
$ wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/EL8/cloudhsm-client-pkcs11-latest.el8.x86_64.rpm
```

```
$ sudo yum install ./cloudhsm-client-pkcs11-latest.el8.x86_64.rpm
```

------
#### [ Ubuntu 16.04 LTS ]

```
$ wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/Xenial/cloudhsm-client-pkcs11_latest_amd64.deb
```

```
$ sudo apt install ./cloudhsm-client-pkcs11_latest_amd64.deb
```

------
#### [ Ubuntu 18.04 LTS ]

```
$ wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/Bionic/cloudhsm-client-pkcs11_latest_u18.04_amd64.deb
```

```
$ sudo apt install ./cloudhsm-client-pkcs11_latest_u18.04_amd64.deb
```

------
+ If the EC2 instance on which you installed the PKCS \$111 library has no other components from Client SDK 3 installed, you must bootstrap Client SDK 3. You only have to do this once on each instance with a component from Client SDK 3.
+ You can find the PKCS \$111 library files in the following locations:

  Linux binaries, configuration scripts, certificates, and log files:

  ```
  /opt/cloudhsm/lib
  ```

# Authenticate to the PKCS \$111 library for AWS CloudHSM Client SDK 3
<a name="pkcs11-v3-pin"></a>

When you use the PKCS \$111 library, your application runs as a particular [crypto user (CU)](manage-hsm-users.md) in your HSMs in AWS CloudHSM. Your application can view and manage only the keys that the CU owns and shares. You can use an existing CU in your HSMs or create a new CU. For information on managing CUs, see [Managing HSM users with CloudHSM CLI](manage-hsm-users-chsm-cli.md) and [Managing HSM users with CloudHSM Management Utility (CMU)](manage-hsm-users-cmu.md).

To specify the CU to PKCS \$111 library, use the pin parameter of the PKCS \$111 [C\$1Login function](http://docs.oasis-open.org/pkcs11/pkcs11-base/v2.40/os/pkcs11-base-v2.40-os.html#_Toc385057915). For AWS CloudHSM, the pin parameter has the following format:

```
<CU_user_name>:<password>
```

For example, the following command sets the PKCS \$111 library pin to the CU with user name `CryptoUser` and password `CUPassword123!`.

```
CryptoUser:CUPassword123!
```

# Supported key types for PKCS \$111 library for AWS CloudHSM Client SDK 3
<a name="pkcs11-v3-key-types"></a>

The PKCS \$111 library supports the following key types with AWS CloudHSM Client SDK 3.


****  

| Key Type | Description | 
| --- | --- | 
| RSA | Generate 2048-bit to 4096-bit RSA keys, in increments of 256 bits. | 
| EC | Generate keys with the secp224r1 (P-224), secp256r1 (P-256), secp256k1 (Blockchain), secp384r1 (P-384), and secp521r1 (P-521) curves. | 
| AES | Generate 128, 192, and 256-bit AES keys.  | 
| DES3 (Triple DES) | Generate 192-bit DES3 keys. See note [1](#pkcs11-v3-key-note) below for an upcoming change. | 
| GENERIC\$1SECRET | Generate 1 to 64 bytes generic secrets. | 
+ [1] In accordance with NIST guidance, this is disallowed for clusters in FIPS mode after 2023. For clusters in non-FIPS mode, it is still allowed after 2023. See [FIPS 140 Compliance: 2024 Mechanism Deprecation](compliance-dep-notif.md#compliance-dep-notif-1) for details.

# Supported mechanisms for AWS CloudHSM Client SDK 3
<a name="pkcs11-v3-mechanisms"></a>

The PKCS \$111 library supports the following algorithms for AWS CloudHSM Client SDK 3:
+ **Encryption and decryption** – AES-CBC, AES-CTR, AES-ECB, AES-GCM, DES3-CBC, DES3-ECB, RSA-OAEP, and RSA-PKCS
+ **Sign and verify** – RSA, HMAC, and ECDSA; with and without hashing
+ **Hash/digest** – SHA1, SHA224, SHA256, SHA384, and SHA512
+ **Key wrap** – AES Key Wrap,[4](#pkcs11-v3-mech4) AES-GCM, RSA-AES, and RSA-OAEP
+ **Key derivation** – ECDH,[5](#pkcs11-v3-mech5) SP800-108 CTR KDF

## The PKCS \$111 library mechanism-function table
<a name="pkcs11-v3-mech-function"></a>

The PKCS \$111 library is compliant with version 2.40 of the PKCS \$111 specification. To invoke a cryptographic feature using PKCS \$111, call a function with a given mechanism. The following table summarizes the combinations of functions and mechanisms supported by AWS CloudHSM.

**Interpreting the supported PKCS \$111 mechanism-function table**  
A ✔ mark indicates that AWS CloudHSM supports the mechanism for the function. We do not support all possible functions listed in the PKCS \$111 specification. A ✖ mark indicates that AWS CloudHSM does not yet support the mechanism for the given function, even though the PKCS \$111 standard allows it. Empty cells indicate that PKCS \$111 standard does not support the mechanism for the given function.


**Supported PKCS \$111 library mechanisms and functions**  
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/cloudhsm/latest/userguide/pkcs11-v3-mechanisms.html)

**Mechanism annotations**
+ [1] Single-part operations only.
+ [2] Mechanism is functionally identical to the `CKM_RSA_PKCS_KEY_PAIR_GEN` mechanism, but offers stronger guarantees for `p` and `q` generation.
+ [3.1] AWS CloudHSM approaches hashing differently based on the Client SDK. For Client SDK 3, where we do the hashing depends on data size and whether you’re using single-part or multipart operations.

  **Single-part operations in Client SDK 3**

  Table 3.1 lists the maximum data set size for each mechanism for Client SDK 3. The entire hash is computed inside the HSM. No support for data sizes greater than 16KB.  
**Table 3.1, Maximum data set size for single-part operations**    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/cloudhsm/latest/userguide/pkcs11-v3-mechanisms.html)

  **Multipart operations Client SDK 3**

  Support for data sizes greater than 16 KB, but data size determines where the hashing takes place. Data buffers less than 16 KB are hashed inside the HSM. Buffers between 16 KB and the maximum data size for your system are hashed locally in software. *Remember*: Hash functions do not require cryptographic secrets, so you can safely compute them outside of the HSM.
+ [3.2] AWS CloudHSM approaches hashing differently based on the Client SDK. For Client SDK 3, where we do the hashing depends on data size and whether you’re using single-part or multipart operations.

  **Single-part operations Client SDK 3**

  Table 3.2 lists the maximum data set size for each mechanism for Client SDK 3. No support for data sizes greater than 16KB.  
**Table 3.2, Maximum data set size for single-part operations**    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/cloudhsm/latest/userguide/pkcs11-v3-mechanisms.html)

  **Multipart operations Client SDK 3**

  Support for data sizes greater than 16 KB, but data size determines where the hashing takes place. Data buffers less than 16 KB are hashed inside the HSM. Buffers between 16 KB and the maximum data size for your system are hashed locally in software. *Remember*: Hash functions do not require cryptographic secrets, so you can safely compute them outside of the HSM.
+ [3.3] When operating on data by using any of the following mechanisms, if the data buffer exceeds the maximum data size, the operation results in an error. For these mechanisms, all the data processing must occur inside the HSM. The following table lists maximum data size set for each mechanism:  
**Table 3.3, Maximum data set size**    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/cloudhsm/latest/userguide/pkcs11-v3-mechanisms.html)
+ [4] When performing AES-GCM encryption, the HSM does not accept initialization vector (IV) data from the application. You must use an IV that it generates. The 12-byte IV provided by the HSM is written into the memory reference pointed to by the pIV element of the `CK_GCM_PARAMS` parameters structure that you supply. To prevent user confusion, PKCS \$111 SDK in version 1.1.1 and later ensures that pIV points to a zeroized buffer when AES-GCM encryption is initialized.
+ [5] **Client SDK 3 only**. Mechanism is implemented to support SSL/TLS offload cases and is executed only partially within the HSM. Before using this mechanism, see "Issue: ECDH key derivation is executed only partially within the HSM" in [Known issues for the PKCS \$111 library for AWS CloudHSMKnown issues for the PKCS \$111 library](ki-pkcs11-sdk.md). `CKM_ECDH1_DERIVE` does not support the secp521r1 (P-521) curve.
+ [6] The following `CK_MECHANISM_TYPE` and `CK_RSA_PKCS_MGF_TYPE` are supported as `CK_RSA_PKCS_OAEP_PARAMS` for `CKM_RSA_PKCS_OAEP`:
  + `CKM_SHA_1` using `CKG_MGF1_SHA1`
  + `CKM_SHA224` using `CKG_MGF1_SHA224`
  + `CKM_SHA256` using `CKG_MGF1_SHA256`
  + `CKM_SHA384` using `CKM_MGF1_SHA384`
  + `CKM_SHA512` using `CKM_MGF1_SHA512`
+ [7.1] Vendor-defined mechanism. In order to use the CloudHSM vendor defined mechanisms, PKCS\$111 applications must include `/opt/cloudhsm/include/pkcs11/cloudhsm_pkcs11_vendor_defs.h` during compilation. 

  `CKM_CLOUDHSM_AES_GCM`: This proprietary mechanism is a programmatically safer alternative to the standard `CKM_AES_GCM`. It prepends the IV generated by the HSM to the ciphertext instead of writing it back into the `CK_GCM_PARAMS` structure that is provided during cipher initialization. You can use this mechanism with `C_Encrypt`, `C_WrapKey`, `C_Decrypt`, and `C_UnwrapKey` functions. When using this mechanism, the pIV variable in the `CK_GCM_PARAMS` struct must be set to `NULL`. When using this mechanism with `C_Decrypt` and `C_UnwrapKey`, the IV is expected to be prepended to the ciphertext that is being unwrapped.

  `CKM_CLOUDHSM_AES_KEY_WRAP_PKCS5_PAD`: AES Key Wrap with PKCS \$15 Padding

  `CKM_CLOUDHSM_AES_KEY_WRAP_ZERO_PAD`: AES Key Wrap with Zero Padding

  For additional information regarding AES key wrapping, see [AES Key Wrapping](manage-aes-key-wrapping.md). 
+ [8] In accordance with NIST guidance, this is disallowed for clusters in FIPS mode after 2023. For clusters in non-FIPS mode, it is still allowed after 2023. See [FIPS 140 Compliance: 2024 Mechanism Deprecation](compliance-dep-notif.md#compliance-dep-notif-1) for details.

# Supported API operations for AWS CloudHSM Client SDK 3
<a name="pkcs11-v3-apis"></a>

The PKCS \$111 library supports the following PKCS \$111 API operations for AWS CloudHSM Client SDK 3.
+ `C_CloseAllSessions`
+ `C_CloseSession`
+ `C_CreateObject`
+ `C_Decrypt`
+ `C_DecryptFinal`
+ `C_DecryptInit`
+ `C_DecryptUpdate`
+ `C_DeriveKey`
+ `C_DestroyObject`
+ `C_Digest`
+ `C_DigestFinal`
+ `C_DigestInit`
+ `C_DigestUpdate`
+ `C_Encrypt`
+ `C_EncryptFinal`
+ `C_EncryptInit`
+ `C_EncryptUpdate`
+ `C_Finalize`
+ `C_FindObjects`
+ `C_FindObjectsFinal`
+ `C_FindObjectsInit`
+ `C_GenerateKey`
+ `C_GenerateKeyPair`
+ `C_GenerateRandom`
+ `C_GetAttributeValue`
+ `C_GetFunctionList`
+ `C_GetInfo`
+ `C_GetMechanismInfo`
+ `C_GetMechanismList`
+ `C_GetSessionInfo`
+ `C_GetSlotInfo`
+ `C_GetSlotList`
+ `C_GetTokenInfo`
+ `C_Initialize`
+ `C_Login`
+ `C_Logout`
+ `C_OpenSession`
+ `C_Sign`
+ `C_SignFinal`
+ `C_SignInit`
+ `C_SignRecover` (Client SDK 3 support only)
+ `C_SignRecoverInit` (Client SDK 3 support only)
+ `C_SignUpdate`
+ `C_UnWrapKey`
+ `C_Verify`
+ `C_VerifyFinal`
+ `C_VerifyInit`
+ `C_VerifyRecover` (Client SDK 3 support only)
+ `C_VerifyRecoverInit` (Client SDK 3 support only)
+ `C_VerifyUpdate`
+ `C_WrapKey`

# Key attributes in the PKCS \$111 library for AWS CloudHSM Client SDK 3
<a name="pkcs11-v3-attributes"></a>

A key object can be a public, private, or secret key. Actions permitted on a key object are specified through attributes. Attributes are defined when the key object is created. When you use the PKCS \$111 library for AWS CloudHSM, we assign default values as specified by the PKCS \$111 standard.

AWS CloudHSM does not support all attributes listed in the PKCS \$111 specification. We are compliant with the specification for all attributes we support. These attributes are listed in the respective tables.

Cryptographic functions such as `C_CreateObject`, `C_GenerateKey`, `C_GenerateKeyPair`, `C_UnwrapKey`, and `C_DeriveKey` that create, modify, or copy objects take an attribute template as one of their parameters. For more information about passing an attribute template during object creation, see [Generate keys through PKCS \$111 library](https://github.com/aws-samples/aws-cloudhsm-pkcs11-examples/tree/master/src/generate) sample.

The following topics provide more information about AWS CloudHSM key attributes for Client SDK 3.

**Topics**
+ [Attributes table](pkcs11-v3-attributes-interpreting.md)
+ [Modifying attributes](pkcs11-v3-modify-attr.md)
+ [Interpreting PKCS \$111 library error codes for AWS CloudHSM Client SDK 3](pkcs11-v3-attr-errors.md)

# PKCS \$111 library attributes table for AWS CloudHSM Client SDK 3
<a name="pkcs11-v3-attributes-interpreting"></a>

The PKCS \$111 library table for AWS CloudHSM Client SDK 3 contains a list of attributes that differ by key types. It indicates whether a given attribute is supported for a particular key type when using a specific cryptographic function with AWS CloudHSM.

**Legend:**
+ ✔ indicates that CloudHSM supports the attribute for the specific key type.
+ ✖ indicates that CloudHSM does not support the attribute for the specific key type.
+ R indicates that the attribute value is set to read-only for the specific key type.
+ S indicates that the attribute cannot be read by the `GetAttributeValue` as it is sensitive.
+ An empty cell in the Default Value column indicates that there is no specific default value assigned to the attribute.

## GenerateKeyPair
<a name="pkcs11-v3-generatekeypair"></a>

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/cloudhsm/latest/userguide/pkcs11-v3-attributes-interpreting.html)

## GenerateKey
<a name="pkcs11-v3-generatekey"></a>

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/cloudhsm/latest/userguide/pkcs11-v3-attributes-interpreting.html)

## CreateObject
<a name="pkcs11-v3-createobject"></a>

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/cloudhsm/latest/userguide/pkcs11-v3-attributes-interpreting.html)

## UnwrapKey
<a name="pkcs11-v3-unwrapkey"></a>

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/cloudhsm/latest/userguide/pkcs11-v3-attributes-interpreting.html)

## DeriveKey
<a name="pkcs11-v3-derivekey"></a>

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/cloudhsm/latest/userguide/pkcs11-v3-attributes-interpreting.html)

## GetAttributeValue
<a name="pkcs11-v3-getattributevalue"></a>

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/cloudhsm/latest/userguide/pkcs11-v3-attributes-interpreting.html)

**Attribute annotations**
+ [1] This attribute is partially supported by the firmware and must be explicitly set only to the default value.
+ [2] Mandatory attribute.
+ [3] **Client SDK 3 only**. The `CKA_SIGN_RECOVER` attribute is derived from the `CKA_SIGN` attribute. If being set, it can only be set to the same value that is set for `CKA_SIGN`. If not set, it derives the default value of `CKA_SIGN`. Since CloudHSM only supports RSA-based recoverable signature mechanisms, this attribute is currently applicable to RSA public keys only.
+ [4] **Client SDK 3 only**. The `CKA_VERIFY_RECOVER` attribute is derived from the `CKA_VERIFY` attribute. If being set, it can only be set to the same value that is set for `CKA_VERIFY`. If not set, it derives the default value of `CKA_VERIFY`. Since CloudHSM only supports RSA-based recoverable signature mechanisms, this attribute is currently applicable to RSA public keys only.

# Modifying PKCS \$111 library attributes for AWS CloudHSM Client SDK 3
<a name="pkcs11-v3-modify-attr"></a>

Some attributes of an object can be modified after the object has been created, whereas some cannot. To modify attributes, use the [setAttribute](cloudhsm_mgmt_util-setAttribute.md) command from cloudhsm\$1mgmt\$1util. You can also derive a list of attributes and the constants that represent them by using the [listAttribute](cloudhsm_mgmt_util-listAttributes.md) command from cloudhsm\$1mgmt\$1util.

The following list displays attributes that are allowed for modification after object creation:
+ `CKA_LABEL`
+ `CKA_TOKEN`
**Note**  
Modification is allowed only for changing a session key to a token key. Use the [setAttribute](key_mgmt_util-setAttribute.md) command from key\$1mgmt\$1util to change the attribute value.
+ `CKA_ENCRYPT`
+ `CKA_DECRYPT`
+ `CKA_SIGN`
+ `CKA_VERIFY`
+ `CKA_WRAP`
+ `CKA_UNWRAP`
+ `CKA_LABEL`
+ `CKA_SENSITIVE`
+ `CKA_DERIVE`
**Note**  
This attribute supports key derivation. It must be `False` for all public keys and cannot be set to `True`. For secret and EC private keys, it can be set to `True` or `False`.
+ `CKA_TRUSTED`
**Note**  
This attribute can be set to `True` or `False` by Crypto Officer (CO) only.
+ `CKA_WRAP_WITH_TRUSTED`
**Note**  
Apply this attribute to an exportable data key to specify that you can only wrap this key with keys marked as `CKA_TRUSTED`. Once you set `CKA_WRAP_WITH_TRUSTED` to true, the attribute becomes read-only and you cannot change or remove the attribute.

# Interpreting PKCS \$111 library error codes for AWS CloudHSM Client SDK 3
<a name="pkcs11-v3-attr-errors"></a>

Specifying in the template a PKCS \$111 library attribute that is not supported by a specific key results in an error. The following table contains error codes that are generated when you violate specifications:

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/cloudhsm/latest/userguide/pkcs11-v3-attr-errors.html)

# Code samples for the PKCS \$111 library for AWS CloudHSM Client SDK 3
<a name="pkcs11-v3-samples"></a>

The code samples on GitHub show you how to accomplish basic tasks using the PKCS \$111 library for AWS CloudHSM. 

## Sample code prerequisites
<a name="pkcs11-v3-samples-prereqs"></a>

Before running the samples, perform the following steps to set up your environment:
+ Install and configure the [PKCS \$111 library](install-pkcs11-v3.md) for Client SDK 3.
+ Set up a [cryptographic user (CU)](manage-hsm-users.md). Your application uses this HSM account to run the code samples on the HSM.

## Code samples
<a name="pkcs11-v3-samples-code"></a>

Code Samples for the AWS CloudHSM Software Library for PKCS\$111 are available on [GitHub](https://github.com/aws-samples/aws-cloudhsm-pkcs11-examples). This repository includes examples on how to do common operations using PKCS\$111 including encryption, decryption, signing and verifying.
+ [Generate keys (AES, RSA, EC)](https://github.com/aws-samples/aws-cloudhsm-pkcs11-examples/tree/master/src/generate)
+ [List key attributes](https://github.com/aws-samples/aws-cloudhsm-pkcs11-examples/blob/master/src/attributes/)
+ [Encrypt and decrypt data with AES GCM](https://github.com/aws-samples/aws-cloudhsm-pkcs11-examples/blob/master/src/encrypt/aes_gcm.c)
+ [Encrypt and decrypt data with AES\$1CTR](https://github.com/aws-samples/aws-cloudhsm-pkcs11-examples/tree/master/src/encrypt/aes_ctr.c) 
+ [Encrypt and decrypt data with 3DES](https://github.com/aws-samples/aws-cloudhsm-pkcs11-examples/tree/master/src/encrypt/des_ecb.c) 
+ [Sign and verify data with RSA](https://github.com/aws-samples/aws-cloudhsm-pkcs11-examples/blob/master/src/sign/rsa_sign.c)
+ [Derive keys using HMAC KDF](https://github.com/aws-samples/aws-cloudhsm-pkcs11-examples/blob/master/src/derivation/hmac_kdf.c)
+ [Wrap and unwrap keys with AES using PKCS \$15 padding](https://github.com/aws-samples/aws-cloudhsm-pkcs11-examples/blob/master/src/wrapping/aes_wrapping.c)
+ [Wrap and unwrap keys with AES using no padding](https://github.com/aws-samples/aws-cloudhsm-pkcs11-examples/blob/master/src/wrapping/aes_no_padding_wrapping.c)
+ [Wrap and unwrap keys with AES using zero padding](https://github.com/aws-samples/aws-cloudhsm-pkcs11-examples/blob/master/src/wrapping/aes_zero_padding_wrapping.c)
+ [Wrap and unwrap keys with AES-GCM](https://github.com/aws-samples/aws-cloudhsm-pkcs11-examples/tree/master/src/wrapping/aes_gcm_wrapping.c)
+ [Wrap and unwrap keys with RSA](https://github.com/aws-samples/aws-cloudhsm-pkcs11-examples/blob/master/src/wrapping/rsa_wrapping.c)

# OpenSSL Dynamic Engine for AWS CloudHSM Client SDK 3
<a name="openssl3-install"></a>

The AWS CloudHSM OpenSSL Dynamic Engine enables you to offload cryptographic operations to your CloudHSM cluster through the OpenSSL API.

AWS CloudHSM Client SDK 3 does require a client daemon to connect to the cluster. It supports:
+ RSA key generation for 2048, 3072, and 4096-bit keys.
+ RSA sign/verify.
+ RSA encrypt/decrypt.
+ Random number generation that is cryptographically secure and FIPS-validated.

  Use the following sections to install and configure the AWS CloudHSM dynamic engine for OpenSSL.

**Topics**
+ [Prerequisites for OpenSSL Dynamic Engine with AWS CloudHSM Client SDK 3](openssl3-install-dyn3-prereqs.md)
+ [Install the OpenSSL Dynamic Engine for AWS CloudHSM Client SDK 3](openssl3-install-openssl-library.md)
+ [Use the OpenSSL Dynamic Engine for AWS CloudHSM Client SDK 3](openssl3-use-library.md)

# Prerequisites for OpenSSL Dynamic Engine with AWS CloudHSM Client SDK 3
<a name="openssl3-install-dyn3-prereqs"></a>

For information about platform support, see [AWS CloudHSM Client SDK 3 supported platforms](sdk3-support.md).

Before you can use the AWS CloudHSM dynamic engine for OpenSSL with Client SDK 3, you need the AWS CloudHSM client. 

The client is a daemon that establishes end-to-end encrypted communication with the HSMs in your cluster, and the OpenSSL engine communicates locally with the client. To install and configure the AWS CloudHSM client, see [Install the client (Linux)](cmu-install-and-configure-client-linux.md). Then use the following command to start it. 

------
#### [ Amazon Linux ]

```
$ sudo start cloudhsm-client
```

------
#### [ Amazon Linux 2 ]

```
$ sudo systemctl start cloudhsm-client
```

------
#### [ CentOS 6 ]

```
$ sudo systemctl start cloudhsm-client
```

------
#### [ CentOS 7 ]

```
$ sudo systemctl start cloudhsm-client
```

------
#### [ RHEL 6 ]

```
$ sudo systemctl start cloudhsm-client
```

------
#### [ RHEL 7 ]

```
$ sudo systemctl start cloudhsm-client
```

------
#### [ Ubuntu 16.04 LTS ]

```
$ sudo systemctl start cloudhsm-client
```

------

# Install the OpenSSL Dynamic Engine for AWS CloudHSM Client SDK 3
<a name="openssl3-install-openssl-library"></a>

The following steps describe how to install and configure the AWS CloudHSM dynamic engine for OpenSSL with Client SDK 3. For information about upgrading, see [Upgrade Client SDK 3](client-upgrade.md).

**To install and configure the OpenSSL engine**

1. Use the following commands to download and install the OpenSSL engine.

------
#### [ Amazon Linux ]

   ```
   $ wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/EL6/cloudhsm-client-dyn-latest.el6.x86_64.rpm
   ```

   ```
   $ sudo yum install ./cloudhsm-client-dyn-latest.el6.x86_64.rpm
   ```

------
#### [ Amazon Linux 2 ]

   ```
   $ wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/EL7/cloudhsm-client-dyn-latest.el7.x86_64.rpm
   ```

   ```
   $ sudo yum install ./cloudhsm-client-dyn-latest.el7.x86_64.rpm
   ```

------
#### [ CentOS 6 ]

   ```
   $ wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/EL6/cloudhsm-client-dyn-latest.el6.x86_64.rpm
   ```

   ```
   $ sudo yum install ./cloudhsm-client-dyn-latest.el6.x86_64.rpm
   ```

------
#### [ CentOS 7 ]

   ```
   $ wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/EL7/cloudhsm-client-dyn-latest.el7.x86_64.rpm
   ```

   ```
   $ sudo yum install ./cloudhsm-client-dyn-latest.el7.x86_64.rpm
   ```

------
#### [ RHEL 6 ]

   ```
   $ wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/EL6/cloudhsm-client-dyn-latest.el6.x86_64.rpm
   ```

   ```
   $ sudo yum install ./cloudhsm-client-dyn-latest.el6.x86_64.rpm
   ```

------
#### [ RHEL 7 ]

   ```
   $ wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/EL7/cloudhsm-client-dyn-latest.el7.x86_64.rpm
   ```

   ```
   $ sudo yum install ./cloudhsm-client-dyn-latest.el7.x86_64.rpm
   ```

------
#### [ Ubuntu 16.04 LTS ]

   ```
   $ wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/Xenial/cloudhsm-client-dyn_latest_amd64.deb
   ```

   ```
   $ sudo apt install ./cloudhsm-client-dyn_latest_amd64.deb
   ```

------

   The OpenSSL engine is installed at `/opt/cloudhsm/lib/libcloudhsm_openssl.so`.

1. Use the following command to set an environment variable named `n3fips_password` that contains the credentials of a crypto user (CU). 

   ```
   $ export n3fips_password=<HSM user name>:<password>
   ```

# Use the OpenSSL Dynamic Engine for AWS CloudHSM Client SDK 3
<a name="openssl3-use-library"></a>

To use the AWS CloudHSM dynamic engine for OpenSSL from an OpenSSL-integrated application, ensure that your application uses the OpenSSL dynamic engine named `cloudhsm`. The shared library for the dynamic engine is located at `/opt/cloudhsm/lib/libcloudhsm_openssl.so`.

To use the AWS CloudHSM dynamic engine for OpenSSL from the OpenSSL command line, use the `-engine` option to specify the OpenSSL dynamic engine named `cloudhsm`. For example:

```
$ openssl s_server -cert <server.crt> -key <server.key> -engine cloudhsm
```

# JCE provider for AWS CloudHSM Client SDK 3
<a name="java-library_3"></a>

The AWS CloudHSM JCE provider is a provider implementation built from the Java Cryptographic Extension (JCE) provider framework. The JCE allows you to perform cryptographic operations using the Java Development Kit (JDK). In this guide, the AWS CloudHSM JCE provider is sometimes referred to as the JCE provider. Use the JCE provider and the JDK to offload cryptographic operations to the HSM. 

**Topics**
+ [Install the JCE provider for AWS CloudHSM Client SDK 3](java-library-install.md)
+ [Key management basics in the JCE provider for AWS CloudHSM Client SDK 3](java-library-key-basics.md)
+ [Supported mechanisms for Client SDK 3 for AWS CloudHSM Client SDK 3](java-lib-supported.md)
+ [Supported Java key attributes for AWS CloudHSM Client SDK 3](java-lib-attributes.md)
+ [Code samples for the AWS CloudHSM software library for Java for Client SDK 3](java-samples_3.md)
+ [AWS CloudHSM KeyStore Java class for Client SDK 3](alternative-keystore.md)

# Install the JCE provider for AWS CloudHSM Client SDK 3
<a name="java-library-install"></a>

Before you can use the JCE provider, you need the AWS CloudHSM client. 

The client is a daemon that establishes end-to-end encrypted communication with the HSMs in your cluster. The JCE provider communicates locally with the client. If you haven't installed and configured the AWS CloudHSM client package, do that now by following the steps at [Install the client (Linux)](cmu-install-and-configure-client-linux.md). After you install and configure the client, use the following command to start it. 

Note that the JCE provider is supported only on Linux and compatible operating systems. 

------
#### [ Amazon Linux ]

```
$ sudo start cloudhsm-client
```

------
#### [ Amazon Linux 2 ]

```
$ sudo systemctl start cloudhsm-client
```

------
#### [ CentOS 7 ]

```
$ sudo systemctl start cloudhsm-client
```

------
#### [ CentOS 8 ]

```
$ sudo systemctl start cloudhsm-client
```

------
#### [ RHEL 7 ]

```
$ sudo systemctl start cloudhsm-client
```

------
#### [ RHEL 8 ]

```
$ sudo systemctl start cloudhsm-client
```

------
#### [ Ubuntu 16.04 LTS ]

```
$ sudo systemctl start cloudhsm-client
```

------
#### [ Ubuntu 18.04 LTS ]

```
$ sudo systemctl start cloudhsm-client
```

------
#### [ Ubuntu 20.04 LTS ]

```
$ sudo systemctl start cloudhsm-client
```

------

Use the following sections to install, validate, and provide credentials to the provider.

**Topics**
+ [Step 1: Install the JCE provider](#install-java-library)
+ [Step 2: Validate the installation](#validate-install)
+ [Step 3: Provide credentials to the JCE provider](#java-library-credentials)

## Step 1: Install the JCE provider
<a name="install-java-library"></a>

Use the following commands to download and install the JCE provider. This provider is supported only on Linux and compatible operating systems. 

**Note**  
For upgrading, see [Upgrade Client SDK 3](client-upgrade.md).

------
#### [ Amazon Linux ]

```
$ wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/EL6/cloudhsm-client-jce-latest.el6.x86_64.rpm
```

```
$ sudo yum install ./cloudhsm-client-jce-latest.el6.x86_64.rpm
```

------
#### [ Amazon Linux 2 ]

```
$ wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/EL7/cloudhsm-client-jce-latest.el7.x86_64.rpm
```

```
$ sudo yum install ./cloudhsm-client-jce-latest.el7.x86_64.rpm
```

------
#### [ CentOS 7 ]

```
$ wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/EL7/cloudhsm-client-jce-latest.el7.x86_64.rpm
```

```
$ sudo yum install ./cloudhsm-client-jce-latest.el7.x86_64.rpm
```

------
#### [ CentOS 8 ]

```
$ wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/EL8/cloudhsm-client-jce-latest.el8.x86_64.rpm
```

```
$ sudo yum install ./cloudhsm-client-jce-latest.el8.x86_64.rpm
```

------
#### [ RHEL 7 ]

```
$ wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/EL7/cloudhsm-client-jce-latest.el7.x86_64.rpm
```

```
$ sudo yum install ./cloudhsm-client-jce-latest.el7.x86_64.rpm
```

------
#### [ RHEL 8 ]

```
$ wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/EL8/cloudhsm-client-jce-latest.el8.x86_64.rpm
```

```
$ sudo yum install ./cloudhsm-client-jce-latest.el8.x86_64.rpm
```

------
#### [ Ubuntu 16.04 LTS ]

```
$ wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/Xenial/cloudhsm-client-jce_latest_amd64.deb
```

```
$ sudo apt install ./cloudhsm-client-jce_latest_amd64.deb
```

------
#### [ Ubuntu 18.04 LTS ]

```
$ wget https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/Bionic/cloudhsm-client-jce_latest_u18.04_amd64.deb
```

```
$ sudo apt install ./cloudhsm-client-jce_latest_u18.04_amd64.deb
```

------

After you run the preceding commands, you can find the following JCE provider files:
+ `/opt/cloudhsm/java/cloudhsm-<version>.jar`
+ `/opt/cloudhsm/java/cloudhsm-test-<version>.jar`
+ `/opt/cloudhsm/java/hamcrest-all-1.3.jar`
+ `/opt/cloudhsm/java/junit.jar`
+ `/opt/cloudhsm/java/log4j-api-2.17.1.jar`
+ `/opt/cloudhsm/java/log4j-core-2.17.1.jar`
+ `/opt/cloudhsm/lib/libcaviumjca.so`

## Step 2: Validate the installation
<a name="validate-install"></a>

Perform basic operations on the HSM to validate the installation.

**To validate JCE provider installation**

1. (Optional) If you don't already have Java installed in your environment, use the following command to install it. 

------
#### [ Linux (and compatible libraries) ]

   ```
   $ sudo yum install java-1.8.0-openjdk
   ```

------
#### [ Ubuntu ]

   ```
   $ sudo apt-get install openjdk-8-jre
   ```

------

1. Use the following commands to set the necessary environment variables. Replace *<HSM user name>* and *<password>* with the credentials of a crypto user (CU).

   ```
   $ export LD_LIBRARY_PATH=/opt/cloudhsm/lib
   ```

   ```
   $ export HSM_PARTITION=PARTITION_1
   ```

   ```
   $ export HSM_USER=<HSM user name>
   ```

   ```
   $ export HSM_PASSWORD=<password>
   ```

1. Use the following command to run the basic functionality test. If successful, the command's output should be similar to the one that follows.

   ```
   $ java8 -classpath "/opt/cloudhsm/java/*" org.junit.runner.JUnitCore TestBasicFunctionality
   
   JUnit version 4.11
   .2018-08-20 17:53:48,514 DEBUG [main] TestBasicFunctionality (TestBasicFunctionality.java:33) - Adding provider.
   2018-08-20 17:53:48,612 DEBUG [main] TestBasicFunctionality (TestBasicFunctionality.java:42) - Logging in.
   2018-08-20 17:53:48,612 INFO [main] cfm2.LoginManager (LoginManager.java:104) - Looking for credentials in HsmCredentials.properties
   2018-08-20 17:53:48,612 INFO [main] cfm2.LoginManager (LoginManager.java:122) - Looking for credentials in System.properties
   2018-08-20 17:53:48,613 INFO [main] cfm2.LoginManager (LoginManager.java:130) - Looking for credentials in System.env
    SDK Version: 2.03
   2018-08-20 17:53:48,655 DEBUG [main] TestBasicFunctionality (TestBasicFunctionality.java:54) - Generating AES Key with key size 256.
   2018-08-20 17:53:48,698 DEBUG [main] TestBasicFunctionality (TestBasicFunctionality.java:63) - Encrypting with AES Key.
   2018-08-20 17:53:48,705 DEBUG [main] TestBasicFunctionality (TestBasicFunctionality.java:84) - Deleting AES Key.
   2018-08-20 17:53:48,707 DEBUG [main] TestBasicFunctionality (TestBasicFunctionality.java:92) - Logging out.
   
   Time: 0.205
   
   OK (1 test)
   ```

## Step 3: Provide credentials to the JCE provider
<a name="java-library-credentials"></a>

HSMs need to authenticate your Java application before the application can use them. Each application can use one session. HSMs authenticate a session by using either explicit login or implicit login method.

**Explicit login** – This method lets you provide CloudHSM credentials directly in the application. It uses the `LoginManager.login()` method, where you pass the CU user name, password, and the HSM partition ID. For more information about using the explicit login method, see the [Login to an HSM](https://github.com/aws-samples/aws-cloudhsm-jce-examples/blob/master/src/main/java/com/amazonaws/cloudhsm/examples/LoginRunner.java) code example. 

**Implicit login** – This method lets you set CloudHSM credentials either in a new property file, system properties, or as environment variables.
+ **New property file** – Create a new file named `HsmCredentials.properties` and add it to your application's `CLASSPATH`. The file should contain the following:

  ```
  HSM_PARTITION = PARTITION_1
  HSM_USER = <HSM user name>
  HSM_PASSWORD = <password>
  ```
+ **System properties** – Set credentials through system properties when running your application. The following examples show two different ways that you can do this:

  ```
  $ java -DHSM_PARTITION=PARTITION_1 -DHSM_USER=<HSM user name> -DHSM_PASSWORD=<password>
  ```

  ```
  System.setProperty("HSM_PARTITION","PARTITION_1");
  System.setProperty("HSM_USER","<HSM user name>");
  System.setProperty("HSM_PASSWORD","<password>");
  ```
+ **Environment variables** – Set credentials as environment variables.

  ```
  $ export HSM_PARTITION=PARTITION_1
  $ export HSM_USER=<HSM user name>
  $ export HSM_PASSWORD=<password>
  ```

Credentials might not be available if the application does not provide them or if you attempt an operation before the HSM authenticates session. In those cases, the CloudHSM software library for Java searches for the credentials in the following order:

1. `HsmCredentials.properties`

1. System properties

1. Environment variables

**Error handling**  
The error handling is easier with the explicit login than the implicit login method. When you use the `LoginManager` class, you have more control over how your application deals with failures. The implicit login method makes error handling difficult to understand when the credentials are invalid or the HSMs are having problems in authenticating session.

# Key management basics in the JCE provider for AWS CloudHSM Client SDK 3
<a name="java-library-key-basics"></a>

The basics on key management in the JCE provider involve importing keys, exporting keys, loading keys by handle, or deleting keys. For more information on managing keys, see the [Manage keys](https://github.com/aws-samples/aws-cloudhsm-jce-examples/blob/master/src/main/java/com/amazonaws/cloudhsm/examples/KeyUtilitiesRunner.java) code example.

You can also find more JCE provider code examples at [Code samples](java-samples_3.md).

# Supported mechanisms for Client SDK 3 for AWS CloudHSM Client SDK 3
<a name="java-lib-supported"></a>

This topic provides information about supported mechanisms for JCE provider with AWS CloudHSM Client SDK 3. For information about the Java Cryptography Architecture (JCA) interfaces and engine classes supported by AWS CloudHSM, see the following topics. 

**Topics**
+ [Supported keys](#java-keys)
+ [Supported ciphers](#java-ciphers)
+ [Supported digests](#java-digests)
+ [Supported hash-based message authentication code (HMAC) algorithms](#java-mac)
+ [Supported sign/verify mechanisms](#java-sign-verify)
+ [Mechanism annotations](#w2aac25c23c25c11c17)

## Supported keys
<a name="java-keys"></a>

The AWS CloudHSM software library for Java enables you to generate the following key types.
+ AES – 128, 192, and 256-bit AES keys.
+ DESede – 92 bit 3DES key. See note [1](#java-keys-note-1) below for an upcoming change.
+ ECC key pairs for NIST curves secp256r1 (P-256), secp384r1 (P-384), and secp256k1 (Blockchain).
+ RSA – 2048-bit to 4096-bit RSA keys, in increments of 256 bits.

In addition to standard parameters, we support the following parameters for each key that is generated.
+ **Label**: A key label that you can use to search for keys.
+ **isExtractable**: Indicates whether the key can be exported from the HSM.
+ **isPersistent**: Indicates whether the key remains on the HSM when the current session ends.

**Note**  
 Java library version 3.1 provides the ability to specify parameters in greater detail. For more information, see [Supported Java Attributes](java-lib-attributes.md).

## Supported ciphers
<a name="java-ciphers"></a>

The AWS CloudHSM software library for Java supports the following algorithm, mode, and padding combinations.


| Algorithm | Mode | Padding | Notes | 
| --- | --- | --- | --- | 
| AES | CBC |  `AES/CBC/NoPadding` `AES/CBC/PKCS5Padding`  | Implements `Cipher.ENCRYPT_MODE` and `Cipher.DECRYPT_MODE`.  | 
| AES | ECB |  `AES/ECB/NoPadding` `AES/ECB/PKCS5Padding`  | Implements Cipher.ENCRYPT\$1MODE and Cipher.DECRYPT\$1MODE. Use Transformation AES. | 
| AES | CTR |  `AES/CTR/NoPadding`  |  Implements `Cipher.ENCRYPT_MODE` and `Cipher.DECRYPT_MODE`.  | 
| AES | GCM | AES/GCM/NoPadding | Implements `Cipher.ENCRYPT_MODE` and `Cipher.DECRYPT_MODE`, `Cipher.WRAP_MODE`, and `Cipher.UNWRAP_MODE`.When performing AES-GCM encryption, the HSM ignores the initialization vector (IV) in the request and uses an IV that it generates. When the operation completes, you must call `Cipher.getIV()` to get the IV. | 
| AESWrap | ECB |  `AESWrap/ECB/ZeroPadding` `AESWrap/ECB/NoPadding` `AESWrap/ECB/PKCS5Padding`  |  Implements `Cipher.WRAP_MODE`, and `Cipher.UNWRAP_MODE`. Use Transformation AES.  | 
| DESede (Triple DES) | CBC |  `DESede/CBC/NoPadding` `DESede/CBC/PKCS5Padding`  |  Implements `Cipher.ENCRYPT_MODE` and `Cipher.DECRYPT_MODE`. The key generation routines accept a size of 168 or 192 bits. However, internally, all DESede keys are 192 bits. See note [1](#java-keys-note-1) below for an upcoming change.  | 
| DESede (Triple DES) | ECB | `DESede/ECB/NoPadding``DESede/ECB/PKCS5Padding` | Implements `Cipher.ENCRYPT_MODE` and `Cipher.DECRYPT_MODE`. The key generation routines accept a size of 168 or 192 bits. However, internally, all DESede keys are 192 bits. See note [1](#java-keys-note-1) below for an upcoming change.  | 
| RSA | ECB | `RSA/ECB/NoPadding``RSA/ECB/PKCS1Padding` | Implements `Cipher.ENCRYPT_MODE` and `Cipher.DECRYPT_MODE`. See note [1](#java-keys-note-1) below for an upcoming change. | 
| RSA | ECB | `RSA/ECB/OAEPPadding` `RSA/ECB/OAEPWithSHA-1ANDMGF1Padding` `RSA/ECB/OAEPWithSHA-224ANDMGF1Padding` `RSA/ECB/OAEPWithSHA-256ANDMGF1Padding` `RSA/ECB/OAEPWithSHA-384ANDMGF1Padding` `RSA/ECB/OAEPWithSHA-512ANDMGF1Padding`  |  Implements `Cipher.ENCRYPT_MODE`, `Cipher.DECRYPT_MODE`, `Cipher.WRAP_MODE`, and `Cipher.UNWRAP_MODE`. `OAEPPadding` is `OAEP` with the `SHA-1` padding type.  | 
| RSAAESWrap | ECB | OAEPPADDING | Implements Cipher.WRAP\$1Mode and Cipher.UNWRAP\$1MODE.  | 

## Supported digests
<a name="java-digests"></a>

The AWS CloudHSM software library for Java supports the following message digests.
+ `SHA-1`
+ `SHA-224`
+ `SHA-256`
+ `SHA-384`
+ `SHA-512`

**Note**  
Data under 16 KB in length are hashed on the HSM, while larger data are hashed locally in software.

## Supported hash-based message authentication code (HMAC) algorithms
<a name="java-mac"></a>

The AWS CloudHSM software library for Java supports the following HMAC algorithms.
+ `HmacSHA1`
+ `HmacSHA224`
+ `HmacSHA256`
+ `HmacSHA384`
+ `HmacSHA512`

## Supported sign/verify mechanisms
<a name="java-sign-verify"></a>

The AWS CloudHSM software library for Java supports the following types of signature and verification.

**RSA Signature Types**
+ `NONEwithRSA`
+ `SHA1withRSA`
+ `SHA224withRSA`
+ `SHA256withRSA`
+ `SHA384withRSA`
+ `SHA512withRSA`
+ `SHA1withRSA/PSS`
+ `SHA224withRSA/PSS`
+ `SHA256withRSA/PSS`
+ `SHA384withRSA/PSS`
+ `SHA512withRSA/PSS`

**ECDSA Signature Types**
+ `NONEwithECDSA`
+ `SHA1withECDSA`
+ `SHA224withECDSA`
+ `SHA256withECDSA`
+ `SHA384withECDSA`
+ `SHA512withECDSA`

## Mechanism annotations
<a name="w2aac25c23c25c11c17"></a>

[1] In accordance with NIST guidance, this is disallowed for clusters in FIPS mode after 2023. For clusters in non-FIPS mode, it is still allowed after 2023. See [FIPS 140 Compliance: 2024 Mechanism Deprecation](compliance-dep-notif.md#compliance-dep-notif-1) for details.

# Supported Java key attributes for AWS CloudHSM Client SDK 3
<a name="java-lib-attributes"></a>

This topic describes how to use a proprietary extension for the Java library version 3.1 to set key attributes for AWS CloudHSM Client SDK 3. Use this extension to set supported key attributes and their values during these operations:
+ Key generation
+ Key import
+ Key unwrap

**Note**  
The extension for setting custom key attributes is an optional feature. If you already have code that functions in Java library version 3.0, you do not need to modify that code. Keys you create will continue to contain the same attributes as before. 

**Topics**
+ [Understanding attributes](#java-understanding-attributes)
+ [Supported attributes](#java-attributes)
+ [Setting attributes for a key](#java-setting-attributes)
+ [Putting it all together](#java-attributes-summary)

## Understanding attributes
<a name="java-understanding-attributes"></a>

You use key attributes to specify what actions are permitted on key objects, including public, private or secret keys. You define key attributes and values during key object creation operations. 

However, the Java Cryptography Extension (JCE) does not specify how you should set values on key attributes, so most actions were permitted by default. In contrast, the PKCS\$1 11 standard defines a comprehensive set of attributes with more restrictive defaults. Starting with the Java library version 3.1, CloudHSM provides a proprietary extension that enables you to set more restrictive values for commonly used attributes. 

## Supported attributes
<a name="java-attributes"></a>

You can set values for the attributes listed in the table below. As a best practice, only set values for attributes you wish to make restrictive. If you don’t specify a value, CloudHSM uses the default value specified in the table below. An empty cell in the Default Value columns indicates that there is no specific default value assigned to the attribute.


****  

| Attribute | Default Value | Notes | 
| --- | --- | --- | 
|  | Symmetric Key | Public Key in Key Pair | Private Key in Key Pair |  | 
| CKA\$1TOKEN | FALSE | FALSE | FALSE | A permanent key which is replicated across all HSMs in the cluster and included in backups. CKA\$1TOKEN = FALSE implies a session key, which is only loaded onto one HSM and automatically erased when the connection to the HSM is broken. | 
| CKA\$1LABEL |   |  |  | A user-defined string. It allows you to conveniently identify keys on your HSM.  | 
| CKA\$1EXTRACTABLE | TRUE |  | TRUE | True indicates you can export this key out of the HSM. | 
| CKA\$1ENCRYPT | TRUE | TRUE |  | True indicates you can use the key to encrypt any buffer. | 
| CKA\$1DECRYPT | TRUE |  | TRUE | True indicates you can use the key to decrypt any buffer. You generally set this to FALSE for a key whose CKA\$1WRAP is set to true.  | 
| CKA\$1WRAP | TRUE | TRUE |  | True indicates you can use the key to wrap another key. You will generally set this to FALSE for private keys. | 
| CKA\$1UNWRAP | TRUE |  | TRUE | True indicates you can use the key to unwrap (import) another key. | 
| CKA\$1SIGN | TRUE |  | TRUE | True indicates you can use the key to sign a message digest. This is generally set to FALSE for public keys and for private keys that you have archived. | 
| CKA\$1VERIFY | TRUE | TRUE |  | True indicates you can use the key to verify a signature. This is generally set to FALSE for private keys. | 
| CKA\$1PRIVATE | TRUE | TRUE | TRUE | True indicates that a user may not access the key until the user is authenticated. For clarity, users cannot access any keys on CloudHSM until they are authenticated, even if this attribute is set to FALSE. | 

**Note**  
You get broader support for attributes in the PKCS\$111 library. For more information, see [Supported PKCS \$111 Attributes](pkcs11-attributes.md).

## Setting attributes for a key
<a name="java-setting-attributes"></a>

`CloudHsmKeyAttributesMap` is a [Java Map](https://devdocs.io/openjdk~8/java/util/map)-like object, which you can use to set attribute values for key objects. The methods for `CloudHsmKeyAttributesMap` function similar to the methods used for Java map manipulation. 

To set custom values on attributes, you have two options:
+ Use the methods listed in the following table
+ Use builder patterns demonstrated later in this document

Attribute map objects support the following methods to set attributes:


****  

| Operation | Return Value | `CloudHSMKeyAttributesMap` method | 
| --- | --- | --- | 
| Get the value of a key attribute for an existing key | Object (containing the value) or null |  **get**(keyAttribute)  | 
| Populate the value of one key attribute  | The previous value associated with key attribute, or null if there was no mapping for a key attribute |  **put**(keyAttribute, value)  | 
| Populate values for multiple key attributes | N/A |  **putAll**(keyAttributesMap)  | 
| Remove a key-value pair from the attribute map |  The previous value associated with key attribute, or *null* if there was no mapping for a key attribute  |  **remove**(keyAttribute)  | 

**Note**  
Any attributes you do not explicitly specify are set to the defaults listed in the preceding table in [Supported attributes](#java-attributes). 

### Builder pattern example
<a name="java-setting-attributes-builder-example"></a>

Developers will generally find it more convenient to utilize classes through the Builder pattern. As examples:

```
import com.amazonaws.cloudhsm.CloudHsmKeyAttributes;
import com.amazonaws.cloudhsm.CloudHsmKeyAttributesMap;
import com.amazonaws.cloudhsm.CloudHsmKeyPairAttributesMap;

CloudHsmKeyAttributesMap keyAttributesSessionDecryptionKey = 
   new CloudHsmKeyAttributesMap.Builder()
      .put(CloudHsmKeyAttributes.CKA_LABEL, "ExtractableSessionKeyEncryptDecrypt")
      .put(CloudHsmKeyAttributes.CKA_WRAP, false)
      .put(CloudHsmKeyAttributes.CKA_UNWRAP, false)
      .put(CloudHsmKeyAttributes.CKA_SIGN, false)
      .put(CloudHsmKeyAttributes.CKA_VERIFY, false)
      .build();

CloudHsmKeyAttributesMap keyAttributesTokenWrappingKey = 
   new CloudHsmKeyAttributesMap.Builder()
      .put(CloudHsmKeyAttributes.CKA_LABEL, "TokenWrappingKey")
      .put(CloudHsmKeyAttributes.CKA_TOKEN, true)
      .put(CloudHsmKeyAttributes.CKA_ENCRYPT, false)
      .put(CloudHsmKeyAttributes.CKA_DECRYPT, false)
      .put(CloudHsmKeyAttributes.CKA_SIGN, false)
      .put(CloudHsmKeyAttributes.CKA_VERIFY, false)
      .build();
```

Developers may also utilize pre-defined attribute sets as a convenient way to enforce best practices in key templates. As an example:

```
//best practice template for wrapping keys

CloudHsmKeyAttributesMap commonKeyAttrs = new CloudHsmKeyAttributesMap.Builder()
    .put(CloudHsmKeyAttributes.CKA_EXTRACTABLE, false)
    .put(CloudHsmKeyAttributes.CKA_DECRYPT, false)
    .build();

// initialize a new instance of CloudHsmKeyAttributesMap by copying commonKeyAttrs
// but with an appropriate label

CloudHsmKeyAttributesMap firstKeyAttrs = new CloudHsmKeyAttributesMap(commonKeyAttrs);
firstKeyAttrs.put(CloudHsmKeyAttributes.CKA_LABEL, "key label");

// alternatively, putAll() will overwrite existing values to enforce conformance

CloudHsmKeyAttributesMap secondKeyAttrs = new CloudHsmKeyAttributesMap();
secondKeyAttrs.put(CloudHsmKeyAttributes.CKA_DECRYPT, true);
secondKeyAttrs.put(CloudHsmKeyAttributes.CKA_ENCRYPT, true);
secondKeyAttrs.put(CloudHsmKeyAttributes.CKA_LABEL, “safe wrapping key”);
secondKeyAttrs.putAll(commonKeyAttrs); // will overwrite CKA_DECRYPT to be FALSE
```

### Setting attributes for a key pair
<a name="java-setting-attributes-key-pair"></a>

Use the Java class `CloudHsmKeyPairAttributesMap` to handle key attributes for a key pair. `CloudHsmKeyPairAttributesMap` encapsulates two `CloudHsmKeyAttributesMap` objects; one for a public key and one for a private key.

To set individual attributes for the public key and private key separately, you can use the `put()` method on corresponding `CloudHsmKeyAttributes` map object for that key. Use the `getPublic()` method to retrieve the attribute map for the public key, and use `getPrivate()` to retrieve the attribute map for the private key. Populate the value of multiple key attributes together for both public and private key pairs using the `putAll()` with a key pair attributes map as its argument.

### Builder pattern example
<a name="java-setting-attributes-key-pair-builder-example"></a>

Developers will generally find it more convenient to set key attributes through the Builder pattern. For example:

```
import com.amazonaws.cloudhsm.CloudHsmKeyAttributes;
import com.amazonaws.cloudhsm.CloudHsmKeyAttributesMap;
import com.amazonaws.cloudhsm.CloudHsmKeyPairAttributesMap;

//specify attributes up-front 
CloudHsmKeyAttributesMap keyAttributes = 
    new CloudHsmKeyAttributesMap.Builder()
        .put(CloudHsmKeyAttributes.CKA_SIGN, false)
        .put(CloudHsmKeyAttributes.CKA_LABEL, "PublicCertSerial12345")
        .build();

CloudHsmKeyPairAttributesMap keyPairAttributes =
    new CloudHsmKeyPairAttributesMap.Builder()
        .withPublic(keyAttributes)
        .withPrivate(
            new CloudHsmKeyAttributesMap.Builder() //or specify them inline 
                .put(CloudHsmKeyAttributes.CKA_LABEL, "PrivateCertSerial12345")
                .put (CloudHSMKeyAttributes.CKA_WRAP, FALSE)
                .build()
        )
        .build();
```

**Note**  
For more information about this proprietary extension, see the [Javadoc](https://s3.amazonaws.com/cloudhsmv2-software/CloudHsmClient/Docs/CloudHsm_CustomKeyAttributes_Javadoc.zip) archive and the [sample](https://github.com/aws-samples/aws-cloudhsm-jce-examples/blob/master/src/main/java/com/amazonaws/cloudhsm/examples/CustomKeyAttributesRunner.java) on GitHub. To explore the Javadoc, download and expand the archive.

## Putting it all together
<a name="java-attributes-summary"></a>

To specify key attributes with your key operations, follow these steps:

1. Instantiate `CloudHsmKeyAttributesMap` for symmetric keys or `CloudHsmKeyPairAttributesMap` for key pairs.

1. Define the attributes object from step 1 with the required key attributes and values.

1. Instantiate a `Cavium*ParameterSpec` class, corresponding to your specific key type, and pass into its constructor this configured attributes object.

1. Pass this `Cavium*ParameterSpec` object into a corresponding crypto class or method.

For reference, the following table contains the `Cavium*ParameterSpec` classes and methods which support custom key attributes.


****  

| Key Type | Parameter Spec Class | Example Constructors | 
| --- | --- | --- | 
| Base Class | CaviumKeyGenAlgorithmParameterSpec | CaviumKeyGenAlgorithmParameterSpec(CloudHsmKeyAttributesMap keyAttributesMap) | 
| DES | CaviumDESKeyGenParameterSpec | CaviumDESKeyGenParameterSpec(int keySize, byte[] iv, CloudHsmKeyAttributesMap keyAttributesMap) | 
| RSA | CaviumRSAKeyGenParameterSpec | CaviumRSAKeyGenParameterSpec(int keysize, BigInteger publicExponent, CloudHsmKeyPairAttributesMap keyPairAttributesMap) | 
| Secret | CaviumGenericSecretKeyGenParameterSpec | CaviumGenericSecretKeyGenParameterSpec(int size, CloudHsmKeyAttributesMap keyAttributesMap) | 
| AES | CaviumAESKeyGenParameterSpec | CaviumAESKeyGenParameterSpec(int keySize, byte[] iv, CloudHsmKeyAttributesMap keyAttributesMap) | 
| EC | CaviumECGenParameterSpec | CaviumECGenParameterSpec(String stdName, CloudHsmKeyPairAttributesMap keyPairAttributesMap) | 

### Sample code: Generate and wrap a key
<a name="example-generate-wrap-key"></a>

These brief code samples demonstrate the steps for two different operations: Key Generation and Key Wrapping:

```
// Set up the desired key attributes

KeyGenerator keyGen = KeyGenerator.getInstance("AES", "Cavium");
CaviumAESKeyGenParameterSpec keyAttributes = new CaviumAESKeyGenParameterSpec(
    256,
    new CloudHsmKeyAttributesMap.Builder()
        .put(CloudHsmKeyAttributes.CKA_LABEL, "MyPersistentAESKey")
        .put(CloudHsmKeyAttributes.CKA_EXTRACTABLE, true)
        .put(CloudHsmKeyAttributes.CKA_TOKEN, true)
        .build()
);

// Assume we already have a handle to the myWrappingKey
// Assume we already have the wrappedBytes to unwrap

// Unwrap a key using Custom Key Attributes

CaviumUnwrapParameterSpec unwrapSpec = new CaviumUnwrapParameterSpec(myInitializationVector, keyAttributes);

Cipher unwrapCipher = Cipher.getInstance("AESWrap", "Cavium");
unwrapCipher.init(Cipher.UNWRAP_MODE, myWrappingKey, unwrapSpec);
Key unwrappedKey = unwrapCipher.unwrap(wrappedBytes, "AES", Cipher.SECRET_KEY);
```

# Code samples for the AWS CloudHSM software library for Java for Client SDK 3
<a name="java-samples_3"></a>

This topic provides resources and information on Java code samples for AWS CloudHSM Client SDK 3.

## Prerequisites
<a name="java-samples-prereqs"></a>

 Before running the samples, you must set up your environment:
+ Install and configure the [Java Cryptographic Extension (JCE) provider](java-library-install.md#install-java-library) and the [AWS CloudHSM client package](cmu-install-and-configure-client-linux.md). 
+ Set up a valid [HSM user name and password](manage-hsm-users.md). Cryptographic user (CU) permissions are sufficient for these tasks. Your application uses these credentials to log in to the HSM in each example.
+ Decide how to provide credentials to the [JCE provider](java-library-install.md#java-library-credentials).

## Code samples
<a name="java-samples-code"></a>

The following code samples show you how to use the [AWS CloudHSM JCE provider](java-library.md) to perform basic tasks. More code samples are available on [GitHub](https://github.com/aws-samples/aws-cloudhsm-jce-examples/).
+ [Log in to an HSM](https://github.com/aws-samples/aws-cloudhsm-jce-examples/blob/master/src/main/java/com/amazonaws/cloudhsm/examples/LoginRunner.java)
+ [Manage keys](https://github.com/aws-samples/aws-cloudhsm-jce-examples/blob/master/src/main/java/com/amazonaws/cloudhsm/examples/KeyUtilitiesRunner.java)
+ [Generate an AES key](https://github.com/aws-samples/aws-cloudhsm-jce-examples/blob/master/src/main/java/com/amazonaws/cloudhsm/examples/SymmetricKeys.java)
+ [Encrypt and decrypt with AES-GCM](https://github.com/aws-samples/aws-cloudhsm-jce-examples/blob/master/src/main/java/com/amazonaws/cloudhsm/examples/AESGCMEncryptDecryptRunner.java)
+ [Encrypt and decrypt with AES-CTR]( https://github.com/aws-samples/aws-cloudhsm-jce-examples/blob/master/src/main/java/com/amazonaws/cloudhsm/examples/AESCTREncryptDecryptRunner.java)
+ [Encrypt and decrypt with D3DES-ECB]( https://github.com/aws-samples/aws-cloudhsm-jce-examples/blob/master/src/main/java/com/amazonaws/cloudhsm/examples/DESedeECBEncryptDecryptRunner.java)**see note [1](#java-samples-code-note-1)**
+ [Wrap and unwrap keys with AES-GCM](https://github.com/aws-samples/aws-cloudhsm-jce-examples/blob/master/src/main/java/com/amazonaws/cloudhsm/examples/AESGCMWrappingRunner.java)
+ [Wrap and unwrap keys with AES](https://github.com/aws-samples/aws-cloudhsm-jce-examples/blob/master/src/main/java/com/amazonaws/cloudhsm/examples/AESWrappingRunner.java)
+ [Wrap and unwrap keys with RSA](https://github.com/aws-samples/aws-cloudhsm-jce-examples/blob/master/src/main/java/com/amazonaws/cloudhsm/examples/RSAWrappingRunner.java)
+ [Use supported key attributes](https://github.com/aws-samples/aws-cloudhsm-jce-examples/blob/master/src/main/java/com/amazonaws/cloudhsm/examples/CustomKeyAttributesRunner.java)
+ [Enumerate keys in the key store](https://github.com/aws-samples/aws-cloudhsm-jce-examples/blob/master/src/main/java/com/amazonaws/cloudhsm/examples/KeyStoreExampleRunner.java)
+ [ Use the CloudHSM key store](https://github.com/aws-samples/aws-cloudhsm-jce-examples/blob/master/src/main/java/com/amazonaws/cloudhsm/examples/CloudHSMKeyStoreExampleRunner.java)
+ [Sign messages in a multi-threaded sample](https://github.com/aws-samples/aws-cloudhsm-jce-examples/blob/master/src/main/java/com/amazonaws/cloudhsm/examples/SignThreadedRunner.java)
+ [Sign and Verify with EC Keys](https://github.com/aws-samples/aws-cloudhsm-jce-examples/blob/master/src/main/java/com/amazonaws/cloudhsm/examples/ECOperationsRunner.java)

[1] In accordance with NIST guidance, this is disallowed for clusters in FIPS mode after 2023. For clusters in non-FIPS mode, it is still allowed after 2023. See [FIPS 140 Compliance: 2024 Mechanism Deprecation](compliance-dep-notif.md#compliance-dep-notif-1) for details.

# AWS CloudHSM KeyStore Java class for Client SDK 3
<a name="alternative-keystore"></a>

The AWS CloudHSM `KeyStore` class provides a special-purpose PKCS12 key store that allows access to AWS CloudHSM keys through applications such as **keytool** and **jarsigner**. This key store can store certificates along with your key data and correlate them to key data stored on AWS CloudHSM. 

**Note**  
Because certificates are public information, and to maximize storage capacity for cryptographic keys, AWS CloudHSM does not support storing certificates on HSMs.

The AWS CloudHSM `KeyStore` class implements the `KeyStore` Service Provider Interface (SPI) of the Java Cryptography Extension (JCE). For more information about using `KeyStore`, see [Class KeyStore](https://docs.oracle.com/javase/8/docs/api/java/security/KeyStore.html).

## Choose the appropriate key store for AWS CloudHSM Client SDK 3
<a name="choosing_keystore"></a>

The AWS CloudHSM Java Cryptographic Extension (JCE) provider comes with a default pass-through, read-only key store that passes all transactions to the HSM. This default key store is distinct from the special-purpose AWS CloudHSM KeyStore. In most situations, you will obtain better runtime performance and throughput by using the default. You should only use the AWS CloudHSM KeyStore for applications where you require support for certificates and certificate-based operations in addition to offloading key operations to the HSM.

Although both key stores use the JCE provider for operations, they are independent entities and do not exchange information with each other. 

Load the default key store for your Java application as follows:

```
KeyStore ks = KeyStore.getInstance("Cavium");
```

Load the special-purpose CloudHSM KeyStore as follows:

```
KeyStore ks = KeyStore.getInstance("CloudHSM")
```

## Initialize the AWS CloudHSM KeyStore for Client SDK 3
<a name="initialize_cloudhsm_keystore"></a>

Log into the AWS CloudHSM KeyStore the same way that you log into the JCE provider. You can use either environment variables or the system property file, and you should log in before you start using the CloudHSM KeyStore. For an example of logging into an HSM using the JCE provider, see [Login to an HSM](https://github.com/aws-samples/aws-cloudhsm-jce-examples/blob/master/src/main/java/com/amazonaws/cloudhsm/examples/LoginRunner.java).

If desired, you can specify a password to encrypt the local PKCS12 file which holds key store data. When you create the AWS CloudHSM Keystore, you set the password and provide it when using the load, set and get methods.

Instantiate a new CloudHSM KeyStore object as follows:

```
ks.load(null, null);
```

Write keystore data to a file using the `store` method. From that point on, you can load the existing keystore using the `load` method with the source file and password as follows: 

```
ks.load(inputStream, password);
```

## Use the AWS CloudHSM KeyStore for AWS CloudHSM Client SDK 3
<a name="using_cloudhsm_keystore"></a>

A CloudHSM KeyStore object is generally used through a third-party application such as [jarsigner](https://docs.oracle.com/javase/8/docs/technotes/tools/windows/jarsigner.html) or [keytool](https://docs.oracle.com/javase/8/docs/technotes/tools/unix/keytool.html). You can also access the object directly with code. 

AWS CloudHSM KeyStore complies with the JCE [Class KeyStore](https://docs.oracle.com/javase/8/docs/api/java/security/KeyStore.html) specification and provides the following functions.
+ `load`

  Loads the key store from the given input stream. If a password was set when saving the key store, this same password must be provided for the load to succeed. Set both parameters to null to initialize an new empty key store.

  ```
  KeyStore ks = KeyStore.getInstance("CloudHSM");
  ks.load(inputStream, password);
  ```
+ `aliases`

  Returns an enumeration of the alias names of all entries in the given key store instance. Results include objects stored locally in the PKCS12 file and objects resident on the HSM. 

  **Sample code:**

  ```
  KeyStore ks = KeyStore.getInstance("CloudHSM");
  for(Enumeration<String> entry = ks.aliases(); entry.hasMoreElements();) 
  	{    
  		String label = entry.nextElement();    
  		System.out.println(label);
  	}
  ```
+ `ContainsAlias`

  Returns true if the key store has access to at least one object with the specified alias. The key store checks objects stored locally in the PKCS12 file and objects resident on the HSM.
+ `DeleteEntry`

  Deletes a certificate entry from the local PKCS12 file. Deleting key data stored in an HSM is not supported using the AWS CloudHSM KeyStore. You can delete keys with CloudHSM’s [key\$1mgmt\$1util](https://docs.aws.amazon.com/cloudhsm/latest/userguide/key_mgmt_util.html) tool.
+ `GetCertificate`

  Returns the certificate associated with an alias if available. If the alias does not exist or references an object which is not a certificate, the function returns NULL. 

  ```
  KeyStore ks = KeyStore.getInstance("CloudHSM");
  Certificate cert = ks.getCertificate(alias)
  ```
+ `GetCertificateAlias`

  Returns the name (alias) of the first key store entry whose data matches the given certificate. 

  ```
  KeyStore ks = KeyStore.getInstance("CloudHSM");
  String alias = ks.getCertificateAlias(cert)
  ```
+ `GetCertificateChain`

  Returns the certificate chain associated with the given alias. If the alias does not exist or references an object which is not a certificate, the function returns NULL. 
+ `GetCreationDate`

  Returns the creation date of the entry identified by the given alias. If a creation date is not available, the function returns the date on which the certificate became valid.
+ `GetKey`

  GetKey is passed to the HSM and returns a key object corresponding to the given label. As `getKey` directly queries the HSM, it can be used for any key on the HSM regardless of whether it was generated by the KeyStore. 

  ```
  Key key = ks.getKey(keyLabel, null);
  ```
+ `IsCertificateEntry`

  Checks if the entry with the given alias represents a certificate entry. 
+ `IsKeyEntry`

  Checks if the entry with the given alias represents a key entry. The action searches both the PKCS12 file and the HSM for the alias. 
+ `SetCertificateEntry`

  Assigns the given certificate to the given alias. If the given alias is already being used to identify a key or certificate, a `KeyStoreException` is thrown. You can use JCE code to get the key object and then use the KeyStore `SetKeyEntry` method to associate the certificate to the key.
+ `SetKeyEntry` with `byte[]` key

  **This API is currently unsupported with Client SDK 3.**
+ `SetKeyEntry` with `Key` object

  Assigns the given key to the given alias and stores it inside the HSM. If the `Key` object is not of type `CaviumKey`, the key is imported into the HSM as an extractable session key. 

  If the `Key` object is of type `PrivateKey`, it must be accompanied by a corresponding certificate chain. 

  If the alias already exists, the `SetKeyEntry` call throws a `KeyStoreException` and prevents the key from being overwritten. If the key must be overwritten, use KMU or JCE for that purpose. 
+ `EngineSize`

  Returns the number of entries in the keystore.
+ `Store`

  Stores the key store to the given output stream as a PKCS12 file and secures it with the given password. In addition, it persists all loaded keys (which are set using `setKey` calls).

# Cryptography API: Next Generation (CNG) and key storage providers (KSP) for AWS CloudHSM
<a name="ksp-v3-library"></a>

The AWS CloudHSM client for Windows includes CNG and KSP providers.

*Key storage providers* (KSPs) enable key storage and retrieval. For example, if you add the Microsoft Active Directory Certificate Services (AD CS) role to your Windows server and choose to create a new private key for your certificate authority (CA), you can choose the KSP that will manage key storage. When you configure the AD CS role, you can choose this KSP. For more information, see [Create Windows Server CA](win-ca-overview-sdk5.md#win-ca-setup-sdk5). 

*Cryptography API: Next Generation (CNG)* is a cryptographic API specific to the Microsoft Windows operating system. CNG enables developers to use cryptographic techniques to secure Windows-based applications. At a high level, the AWS CloudHSM implementation of CNG provides the following functionality: 
+ **Cryptographic Primitives** – enable you to perform fundamental cryptographic operations.
+ **Key Import and Export** – enables you to import and export asymmetric keys.
+ **Data Protection API (CNG DPAPI)** – enables you to easily encrypt and decrypt data.
+ **Key Storage and Retrieval** -–enables you to securely store and isolate the private key of an asymmetric key pair.

**Topics**
+ [Verify the KSP and CNG Providers for AWS CloudHSM](ksp-v3-library-install.md)
+ [Prerequisites for using the AWS CloudHSM Windows Client](ksp-library-prereq.md)
+ [Associate an AWS CloudHSM key with a certificate](ksp-library-associate-key-certificate.md)
+ [Code sample for CNG provider for AWS CloudHSM](ksp-library-sample.md)

# Verify the KSP and CNG Providers for AWS CloudHSM
<a name="ksp-v3-library-install"></a>

The KSP and CNG providers are installed when you install the Windows AWS CloudHSM client. You can install the client by following the steps at [Install the client (Windows)](kmu-install-and-configure-client-win.md). 

Use the following sections to verify the installation of the providers.

## Configure and run the Windows AWS CloudHSM client
<a name="ksp-configure-client-windows"></a>

To start the Windows CloudHSM client, you must first satisfy the [Prerequisites](ksp-library-prereq.md). Then, update the configuration files that the providers use and start the client by completing the steps below. You need to do these steps the first time you use the KSP and CNG providers and after you add or remove HSMs in your cluster. This way, AWS CloudHSM is able to synchronize data and maintain consistency across all HSMs in the cluster.

### Step 1: Stop the AWS CloudHSM client
<a name="ksp-stop-cloudhsm-client"></a>

Before you update the configuration files that the providers use, stop the AWS CloudHSM client. If the client is already stopped, running the stop command has no effect. 
+ For Windows client 1.1.2\$1:

  ```
  C:\Program Files\Amazon\CloudHSM>net.exe stop AWSCloudHSMClient
  ```
+ For Windows clients 1.1.1 and older:

  Use **Ctrl**\$1**C** in the command window where you started the AWS CloudHSM client.

### Step 2: Update the AWS CloudHSM configuration files
<a name="ksp-config-a"></a>

This step uses the `-a` parameter of the [Configure tool](configure-tool.md) to add the elastic network interface (ENI) IP address of one of the HSMs in the cluster to the configuration file. 

```
PS C:\> & "C:\Program Files\Amazon\CloudHSM\configure.exe" -a <HSM ENI IP>
```

To get the ENI IP address of an HSM in your cluster, navigate to the AWS CloudHSM console, choose **clusters**, and select the desired cluster. You can also use the [DescribeClusters](https://docs.aws.amazon.com/cloudhsm/latest/APIReference/API_DescribeClusters.html) operation, the [describe-clusters](https://docs.aws.amazon.com/cli/latest/reference/cloudhsmv2/describe-clusters.html) command, or the [Get-HSM2Cluster](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-HSM2Cluster.html) PowerShell cmdlet. Type only one ENI IP address. It does not matter which ENI IP address you use. 

### Step 3: Start the AWS CloudHSM client
<a name="ksp-start-cloudhsm-client"></a>

Next, start or restart the AWS CloudHSM client. When the AWS CloudHSM client starts, it uses the ENI IP address in its configuration file to query the cluster. Then it adds the ENI IP addresses of all HSMs in the cluster to the cluster information file. 
+ For Windows client 1.1.2\$1:

  ```
  C:\Program Files\Amazon\CloudHSM>net.exe start AWSCloudHSMClient
  ```
+ For Windows clients 1.1.1 and older:

  ```
  C:\Program Files\Amazon\CloudHSM>start "cloudhsm_client" cloudhsm_client.exe C:\ProgramData\Amazon\CloudHSM\data\cloudhsm_client.cfg
  ```

## Checking the KSP and CNG providers
<a name="ksp-check-providers"></a>

You can use either of the following commands to determine which providers are installed on your system. The commands list the registered KSP and CNG providers. The AWS CloudHSM client does not need to be running. 

```
PS C:\> & "C:\Program Files\Amazon\CloudHSM\ksp_config.exe" -enum
```

```
PS C:\> & "C:\Program Files\Amazon\CloudHSM\cng_config.exe" -enum
```

To verify that the KSP and CNG providers are installed on your Windows Server EC2 instance, you should see the following entries in the list:

```
Cavium CNG Provider
Cavium Key Storage Provider
```

If the CNG provider is missing, run the following command. 

```
PS C:\> & "C:\Program Files\Amazon\CloudHSM\cng_config.exe" -register
```

If the KSP provider is missing, run the following command.

```
PS C:\> & "C:\Program Files\Amazon\CloudHSM\ksp_config.exe" -register
```

# Prerequisites for using the AWS CloudHSM Windows Client
<a name="ksp-library-prereq"></a>

Before you can start the Windows AWS CloudHSM client and use the KSP and CNG providers, you must set the login credentials for the HSM on your system. You can set credentials through either Windows Credentials Manager or system environment variable. We recommend you use Windows Credential Manager for storing credentials. This option is available with AWS CloudHSM client version 2.0.4 and later. Using environment variable is easier to set up, but less secure than using Windows Credential Manager.

## Windows Credential Manager
<a name="wcm"></a>

You can use either the `set_cloudhsm_credentials` utility or the Windows Credentials Manager interface.
+ **Using the `set_cloudhsm_credentials` utility**:

  The `set_cloudhsm_credentials` utility is included in your Windows installer. You can use this utility to conveniently pass HSM login credentials to Windows Credential Manager. If you want to compile this utility from source, you can use the Python code that is included in the installer.

  1. Go to the `C:\Program Files\Amazon\CloudHSM\tools\` folder.

  1. Run the `set_cloudhsm_credentials.exe` file with the CU username and password parameters.

     ```
     set_cloudhsm_credentials.exe --username <CU USER> --password <CU PASSWORD>
     ```
+ **Using the Credential Manager interface**:

  You can use the Credential Manager interface to manually manage your credentials.

  1. To open Credential Manager, type `credential manager` in the search box on the taskbar and select **Credential Manager**.

  1. Select **Windows Credentials** to manage Windows credentials.

  1. Select **Add a generic credential** and fill out the details as follows:
     + In **Internet or Network Address**, enter the target name as `cloudhsm_client`.
     + In **Username** and **Password** enter the CU credentials.
     + Click **OK**.

## System environment variables
<a name="enviorn-var"></a>

You can set system environment variables that identify an HSM and a [crypto user](understanding-users-cmu.md#crypto-user-cmu) (CU) for your Windows application. You can use the [**setx** command](https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/setx) to set system environment variables, or set permanent system environment variables [programmatically](https://msdn.microsoft.com/en-us/library/system.environment.setenvironmentvariable(v=vs.110).aspx) or in the **Advanced** tab of the Windows **System Properties** Control Panel. 

**Warning**  
When you set credentials through system environment variables, the password is available in plaintext on a user’s system. To overcome this problem, use Windows Credential Manager.

Set the following system environment variables:

**`n3fips_password=<CU USERNAME>:<CU PASSWORD>`**  
Identifies a [crypto user](understanding-users-cmu.md#crypto-user-cmu) (CU) in the HSM and provides all required login information. Your application authenticates and runs as this CU. The application has the permissions of this CU and can view and manage only the keys that the CU owns and shares. To create a new CU, use [createUser](cloudhsm_mgmt_util-createUser.md). To find existing CUs, use [listUsers](cloudhsm_mgmt_util-listUsers.md).  
For example:  

```
setx /m n3fips_password test_user:password123
```

# Associate an AWS CloudHSM key with a certificate
<a name="ksp-library-associate-key-certificate"></a>

Before you can use AWS CloudHSM keys with third-party tools, such as Microsoft's [SignTool](https://docs.microsoft.com/en-us/windows/win32/seccrypto/signtool), you must import the key's metadata into the local certificate store and associate the metadata with a certificate. To import the key's metadata, use the import\$1key.exe utility which is included in CloudHSM version 3.0 and higher. The following steps provide additional information, and sample output.

## Step 1: Import your certificate
<a name="import-cert"></a>

On Windows, you should be able to double-click the certificate to import it to your local certificate store. 

However, if double-clicking doesn't work, use the [Microsoft Certreq tool](https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2012-R2-and-2012/dn296456%28v%3dws.11%29) to import the certificate into the certificate manager. For example: 

```
certreq -accept <certificatename>
```

If this action fails and you receive the error, `Key not found`, continue to Step 2. If the certificate appears in your key store, you've completed the task and no further action is necessary.

## Step 2: Gather certificate-identifying information
<a name="cert-identifier"></a>

If the previous step wasn't successful, you'll need to associate your private key with a certificate. However, before you can create the association, you must first find the certificate's Unique Container Name and Serial Number. Use a utility, such as **certutil**, to display the needed certificate information. The following sample output from **certutil** shows the container name and the serial number.

```
================ Certificate 1 ================ Serial Number:
			72000000047f7f7a9d41851b4e000000000004Issuer: CN=Enterprise-CANotBefore: 10/8/2019 11:50
			AM NotAfter: 11/8/2020 12:00 PMSubject: CN=www.example.com, OU=Certificate Management,
			O=Information Technology, L=Seattle, S=Washington, C=USNon-root CertificateCert
			Hash(sha1): 7f d8 5c 00 27 bf 37 74 3d 71 5b 54 4e c0 94 20 45 75 bc 65No key provider
			information Simple container name: CertReq-39c04db0-6aa9-4310-93db-db0d9669f42c Unique
			container name: CertReq-39c04db0-6aa9-4310-93db-db0d9669f42c
```



## Step 3: Associate the AWS CloudHSM private key with the certificate
<a name="associate-key-certificate"></a>

To associate the key with the certificate, first be sure to [start the AWS CloudHSM client daemon](key_mgmt_util-setup.md#key_mgmt_util-start-cloudhsm-client). Then, use import\$1key.exe (which is included in CloudHSM version 3.0 and higher) to associate the private key with the certificate. When specifying the certificate, use its simple container name. The following example shows the command and the response. This action only copies the key's metadata; the key remains on the HSM.

```
$> import_key.exe –RSA CertReq-39c04db0-6aa9-4310-93db-db0d9669f42c

Successfully opened Microsoft Software Key Storage Provider : 0NCryptOpenKey failed : 80090016
```

## Step 4: Update the certificate store
<a name="update-certificate-store"></a>

Be certain the AWS CloudHSM client daemon is still running. Then, use the **certutil** verb, **-repairstore**, to update the certificate serial number. The following sample shows the command and output. See the Microsoft documentation for information about the [**-repairstore** verb](https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2012-R2-and-2012/cc732443(v=ws.11)?redirectedfrom=MSDN#-repairstore).

```
C:\Program Files\Amazon\CloudHSM>certutil -f -csp "Cavium Key Storage Provider"-repairstore my "72000000047f7f7a9d41851b4e000000000004"
my "Personal"
================ Certificate 1 ================
Serial Number: 72000000047f7f7a9d41851b4e000000000004
Issuer: CN=Enterprise-CA
NotBefore: 10/8/2019 11:50 AM
NotAfter: 11/8/2020 12:00 PM
Subject: CN=www.example.com, OU=Certificate Management, O=Information Technology, L=Seattle, S=Washington, C=US
Non-root CertificateCert Hash(sha1): 7f d8 5c 00 27 bf 37 74 3d 71 5b 54 4e c0 94 20 45 75 bc 65       
SDK Version: 3.0 
Key Container = CertReq-39c04db0-6aa9-4310-93db-db0d9669f42c 
Provider = "Cavium Key Storage Provider"
Private key is NOT exportableEncryption test passedCertUtil: -repairstore command completed successfully.
```

After updating the certificate serial number you can use this certificate and the corresponding AWS CloudHSM private key with any third-party signing tool on Windows.

# Code sample for CNG provider for AWS CloudHSM
<a name="ksp-library-sample"></a>

****  
\$1\$1 Example code only – Not for production use \$1\$1  
This sample code is for illustrative purposes only. Do not run this code in production.

The following sample shows how to enumerate the registered cryptographic providers on your system to find the CNG provider installed with CloudHSM client for Windows. The sample also shows how to create an asymmetric key pair and how to use the key pair to sign data. 

**Important**  
Before you run this example, you must set up the HSM credentials as explained in the prerequisites. For details, see [Prerequisites for using the AWS CloudHSM Windows Client](ksp-library-prereq.md). 

```
// CloudHsmCngExampleConsole.cpp : Console application that demonstrates CNG capabilities.
// This example contains the following functions.
//
//   VerifyProvider()          - Enumerate the registered providers and retrieve Cavium KSP and CNG providers.
//   GenerateKeyPair()         - Create an RSA key pair.
//   SignData()                - Sign and verify data.
//

#include "stdafx.h"
#include <Windows.h>

#ifndef NT_SUCCESS
#define NT_SUCCESS(Status) ((NTSTATUS)(Status) >= 0)
#endif

#define CAVIUM_CNG_PROVIDER L"Cavium CNG Provider"
#define CAVIUM_KEYSTORE_PROVIDER L"Cavium Key Storage Provider"

// Enumerate the registered providers and determine whether the Cavium CNG provider
// and the Cavium KSP provider exist.
//
bool VerifyProvider()
{
  NTSTATUS status;
  ULONG cbBuffer = 0;
  PCRYPT_PROVIDERS pBuffer = NULL;
  bool foundCng = false;
  bool foundKeystore = false;

  // Retrieve information about the registered providers.
  //   cbBuffer - the size, in bytes, of the buffer pointed to by pBuffer.
  //   pBuffer - pointer to a buffer that contains a CRYPT_PROVIDERS structure.
  status = BCryptEnumRegisteredProviders(&cbBuffer, &pBuffer);

  // If registered providers exist, enumerate them and determine whether the
  // Cavium CNG provider and Cavium KSP provider have been registered.
  if (NT_SUCCESS(status))
  {
    if (pBuffer != NULL)
    {
      for (ULONG i = 0; i < pBuffer->cProviders; i++)
      {
        // Determine whether the Cavium CNG provider exists.
        if (wcscmp(CAVIUM_CNG_PROVIDER, pBuffer->rgpszProviders[i]) == 0)
        {
          printf("Found %S\n", CAVIUM_CNG_PROVIDER);
          foundCng = true;
        }

        // Determine whether the Cavium KSP provider exists.
        else if (wcscmp(CAVIUM_KEYSTORE_PROVIDER, pBuffer->rgpszProviders[i]) == 0)
        {
          printf("Found %S\n", CAVIUM_KEYSTORE_PROVIDER);
          foundKeystore = true;
        }
      }
    }
  }
  else
  {
    printf("BCryptEnumRegisteredProviders failed with error code 0x%08x\n", status);
  }

  // Free memory allocated for the CRYPT_PROVIDERS structure.
  if (NULL != pBuffer)
  {
    BCryptFreeBuffer(pBuffer);
  }

  return foundCng == foundKeystore == true;
}

// Generate an asymmetric key pair. As used here, this example generates an RSA key pair 
// and returns a handle. The handle is used in subsequent operations that use the key pair. 
// The key material is not available.
//
// The key pair is used in the SignData function.
//
NTSTATUS GenerateKeyPair(BCRYPT_ALG_HANDLE hAlgorithm, BCRYPT_KEY_HANDLE *hKey)
{
  NTSTATUS status;

  // Generate the key pair.
  status = BCryptGenerateKeyPair(hAlgorithm, hKey, 2048, 0);
  if (!NT_SUCCESS(status))
  {
    printf("BCryptGenerateKeyPair failed with code 0x%08x\n", status);
    return status;
  }

  // Finalize the key pair. The public/private key pair cannot be used until this 
  // function is called.
  status = BCryptFinalizeKeyPair(*hKey, 0);
  if (!NT_SUCCESS(status))
  {
    printf("BCryptFinalizeKeyPair failed with code 0x%08x\n", status);
    return status;
  }

  return status;
}

// Sign and verify data using the RSA key pair. The data in this function is hardcoded
// and is for example purposes only.
//
NTSTATUS SignData(BCRYPT_KEY_HANDLE hKey)
{
  NTSTATUS status;
  PBYTE sig;
  ULONG sigLen;
  ULONG resLen;
  BCRYPT_PKCS1_PADDING_INFO pInfo;

  // Hardcode the data to be signed (for demonstration purposes only).
  PBYTE message = (PBYTE)"d83e7716bed8a20343d8dc6845e57447";
  ULONG messageLen = strlen((char*)message);

  // Retrieve the size of the buffer needed for the signature.
  status = BCryptSignHash(hKey, NULL, message, messageLen, NULL, 0, &sigLen, 0);
  if (!NT_SUCCESS(status))
  {
    printf("BCryptSignHash failed with code 0x%08x\n", status);
    return status;
  }

  // Allocate a buffer for the signature.
  sig = (PBYTE)HeapAlloc(GetProcessHeap(), 0, sigLen);
  if (sig == NULL)
  {
    return -1;
  }

  // Use the SHA256 algorithm to create padding information.
  pInfo.pszAlgId = BCRYPT_SHA256_ALGORITHM;

  // Create a signature.
  status = BCryptSignHash(hKey, &pInfo, message, messageLen, sig, sigLen, &resLen, BCRYPT_PAD_PKCS1);
  if (!NT_SUCCESS(status))
  {
    printf("BCryptSignHash failed with code 0x%08x\n", status);
    return status;
  }

  // Verify the signature.
  status = BCryptVerifySignature(hKey, &pInfo, message, messageLen, sig, sigLen, BCRYPT_PAD_PKCS1);
  if (!NT_SUCCESS(status))
  {
    printf("BCryptVerifySignature failed with code 0x%08x\n", status);
    return status;
  }

  // Free the memory allocated for the signature.
  if (sig != NULL)
  {
    HeapFree(GetProcessHeap(), 0, sig);
    sig = NULL;
  }

  return 0;
}

// Main function.
//
int main()
{
  NTSTATUS status;
  BCRYPT_ALG_HANDLE hRsaAlg;
  BCRYPT_KEY_HANDLE hKey = NULL;

  // Enumerate the registered providers.
  printf("Searching for Cavium providers...\n");
  if (VerifyProvider() == false) {
    printf("Could not find the CNG and Keystore providers\n");
    return 1;
  }

  // Get the RSA algorithm provider from the Cavium CNG provider.
  printf("Opening RSA algorithm\n");
  status = BCryptOpenAlgorithmProvider(&hRsaAlg, BCRYPT_RSA_ALGORITHM, CAVIUM_CNG_PROVIDER, 0);
  if (!NT_SUCCESS(status))
  {
    printf("BCryptOpenAlgorithmProvider RSA failed with code 0x%08x\n", status);
    return status;
  }

  // Generate an asymmetric key pair using the RSA algorithm.
  printf("Generating RSA Keypair\n");
  GenerateKeyPair(hRsaAlg, &hKey);
  if (hKey == NULL)
  {
    printf("Invalid key handle returned\n");
    return 0;
  }
  printf("Done!\n");

  // Sign and verify [hardcoded] data using the RSA key pair.
  printf("Sign/Verify data with key\n");
  SignData(hKey);
  printf("Done!\n");

  // Remove the key handle from memory.
  status = BCryptDestroyKey(hKey);
  if (!NT_SUCCESS(status))
  {
    printf("BCryptDestroyKey failed with code 0x%08x\n", status);
    return status;
  }

  // Close the RSA algorithm provider.
  status = BCryptCloseAlgorithmProvider(hRsaAlg, NULL);
  if (!NT_SUCCESS(status))
  {
    printf("BCryptCloseAlgorithmProvider RSA failed with code 0x%08x\n", status);
    return status;
  }

  return 0;
}
```