Quickstart: Azure Key Vault Managed HSM client library for .NET

Get started with the Azure Key Vault Managed HSM client library for .NET. 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 .NET client library.

Managed HSM client library resources:

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

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 or 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 new .NET console app

  1. In a command shell, run the following command to create a project named mhsm-console-app:

    dotnet new console --name mhsm-console-app
    
  2. Change to the newly created mhsm-console-app directory:

    cd mhsm-console-app
    

Install the packages

Install the Azure Identity and Key Vault Keys client libraries:

dotnet add package Azure.Identity
dotnet add package Azure.Security.KeyVault.Keys

Create the sample code

Replace the contents of Program.cs with the following code. Replace <hsm-name> with your Managed HSM name, and <key-name> with an existing key name.

using Azure.Identity;
using Azure.Security.KeyVault.Keys;
using Azure.Security.KeyVault.Keys.Cryptography;

// Use DefaultAzureCredential for automatic credential selection
// Works with managed identities in Azure, and developer credentials locally
var credential = new DefaultAzureCredential();

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

// Get a key reference
string keyName = "<key-name>";
Console.WriteLine($"Retrieving key '{keyName}' from Managed HSM...");
KeyVaultKey key = await keyClient.GetKeyAsync(keyName);
Console.WriteLine($"Key retrieved. Key type: {key.KeyType}");

// Perform cryptographic operations
var cryptoClient = new CryptographyClient(key.Id, credential);

// Encrypt data
byte[] plaintext = System.Text.Encoding.UTF8.GetBytes("Hello, Managed HSM!");
Console.WriteLine($"\nOriginal text: {System.Text.Encoding.UTF8.GetString(plaintext)}");

EncryptResult encryptResult = await cryptoClient.EncryptAsync(EncryptionAlgorithm.RsaOaep256, plaintext);
Console.WriteLine($"Encrypted (base64): {Convert.ToBase64String(encryptResult.Ciphertext)}");

// Decrypt data
DecryptResult decryptResult = await cryptoClient.DecryptAsync(EncryptionAlgorithm.RsaOaep256, encryptResult.Ciphertext);
Console.WriteLine($"Decrypted text: {System.Text.Encoding.UTF8.GetString(decryptResult.Plaintext)}");

Console.WriteLine("\nDone!");

Run the application

Run the application with the dotnet run command:

dotnet run

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): <encrypted-data>
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:

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

# Assign the Crypto User role for key operations
az keyvault role assignment create \
    --hsm-name ContosoMHSM \
    --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