Edit

Share via


Quickstart: Azure Key Vault Managed HSM client library for JavaScript

Get started with the Azure Key Vault Managed HSM client library for JavaScript. Managed HSM is a fully managed, highly available, single-tenant, standards-compliant cloud service that enables you to safeguard cryptographic keys for your cloud applications, using FIPS 140-3 Level 3 validated HSMs. For more information on Managed HSM, review the Overview.

In this quickstart, you learn how to access and perform cryptographic operations on keys in a Managed HSM using the JavaScript client library.

Managed HSM client library resources:

API reference documentation | Library source code | Package (npm)

Prerequisites

Set up your local environment

This quickstart uses the Azure Identity library with Azure CLI to authenticate to Azure services. Developers can also use Visual Studio Code to authenticate their calls. For more information, see Authenticate the client with Azure Identity client library.

Sign in to Azure

Run the az login command to sign in:

az login

Create a project folder and initialize

  1. Create a project folder and navigate to it:

    mkdir mhsm-js-app && cd mhsm-js-app
    
  2. Initialize the project:

    npm init -y
    

Install the packages

Install the Azure Identity and Key Vault Keys client libraries:

npm install @azure/identity @azure/keyvault-keys

Create the sample code

Create a file named index.js with the following code. Replace <hsm-name> with your Managed HSM name, and <key-name> with an existing key name.

const { DefaultAzureCredential } = require("@azure/identity");
const { KeyClient, CryptographyClient } = require("@azure/keyvault-keys");

async function main() {
    // Use DefaultAzureCredential for automatic credential selection
    const credential = new DefaultAzureCredential();

    // Connect to Managed HSM - replace with your HSM URI
    const hsmUri = "https://<hsm-name>.managedhsm.azure.net";
    const keyClient = new KeyClient(hsmUri, credential);

    // Get a key reference
    const keyName = "<key-name>";
    console.log(`Retrieving key '${keyName}' from Managed HSM...`);
    const key = await keyClient.getKey(keyName);
    console.log(`Key retrieved. Key type: ${key.keyType}`);

    // Perform cryptographic operations
    const cryptoClient = new CryptographyClient(key, credential);

    // Encrypt data
    const plaintext = Buffer.from("Hello, Managed HSM!");
    console.log(`\nOriginal text: ${plaintext.toString()}`);

    const encryptResult = await cryptoClient.encrypt("RSA-OAEP-256", plaintext);
    console.log(`Encrypted (base64): ${encryptResult.result.toString("base64").substring(0, 64)}...`);

    // Decrypt data
    const decryptResult = await cryptoClient.decrypt("RSA-OAEP-256", encryptResult.result);
    console.log(`Decrypted text: ${decryptResult.result.toString()}`);

    console.log("\nDone!");
}

main().catch((error) => {
    console.error("An error occurred:", error);
    process.exit(1);
});

Run the application

Run the application:

node index.js

You should see output similar to:

Retrieving key 'myrsakey' from Managed HSM...
Key retrieved. Key type: RSA-HSM

Original text: Hello, Managed HSM!
Encrypted (base64): NWE4ZjNiMmMxZDRlNWY2YTdiOGM5ZDBlMWYyYTNiNGM...
Decrypted text: Hello, Managed HSM!

Done!

Understanding the code

Authentication with DefaultAzureCredential

DefaultAzureCredential automatically selects the appropriate credential based on your environment:

Environment Credential used
Azure VMs, App Service, Functions System-assigned or user-assigned managed identity
Azure Kubernetes Service Workload identity
Local development Azure CLI, Visual Studio, or VS Code credentials
CI/CD pipelines Workload identity federation or service principal

The credential checks these sources in order:

  1. Environment variables
  2. Workload identity
  3. Managed identity
  4. Azure CLI
  5. Azure PowerShell
  6. Visual Studio / VS Code credentials

For production workloads in Azure, managed identities are strongly recommended because they eliminate credential management entirely.

Key operations

The KeyClient class provides methods to:

  • Create, get, update, and delete keys
  • List keys and key versions
  • Backup and restore keys

The CryptographyClient class provides cryptographic operations:

  • Encrypt and decrypt data
  • Sign and verify signatures
  • Wrap and unwrap keys

Assign Managed HSM roles

For your application to access keys, assign the appropriate Managed HSM local RBAC role to your managed identity. Replace <vm-name>, <resource-group>, and <hsm-name> with your actual values.

# Get the principal ID of your managed identity
principalId=$(az vm identity show --name <vm-name> --resource-group <resource-group> --query principalId -o tsv)

# Assign the Crypto User role for key operations
az keyvault role assignment create \
    --hsm-name <hsm-name> \
    --role "Managed HSM Crypto User" \
    --assignee $principalId \
    --scope /keys

For more information on roles and permissions, see Managed HSM local RBAC built-in roles.

Clean up resources

When no longer needed, delete the resource group and all related resources:

az group delete --name <resource-group>

Warning

Deleting the resource group puts the Managed HSM into a soft-deleted state. The Managed HSM continues to be billed until it's purged. See Managed HSM soft-delete and purge protection

Next steps