Azure.Security.KeyVault.Keys 4.3.0-beta.2

Prefix Reserved
This is a prerelease version of Azure.Security.KeyVault.Keys.
There is a newer version of this package available.
See the version list below for details.
dotnet add package Azure.Security.KeyVault.Keys --version 4.3.0-beta.2                
NuGet\Install-Package Azure.Security.KeyVault.Keys -Version 4.3.0-beta.2                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Azure.Security.KeyVault.Keys" Version="4.3.0-beta.2" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Azure.Security.KeyVault.Keys --version 4.3.0-beta.2                
#r "nuget: Azure.Security.KeyVault.Keys, 4.3.0-beta.2"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install Azure.Security.KeyVault.Keys as a Cake Addin
#addin nuget:?package=Azure.Security.KeyVault.Keys&version=4.3.0-beta.2&prerelease

// Install Azure.Security.KeyVault.Keys as a Cake Tool
#tool nuget:?package=Azure.Security.KeyVault.Keys&version=4.3.0-beta.2&prerelease                

Azure Key Vault key client library for .NET

Azure Key Vault is a cloud service that provides secure storage of keys for encrypting your data. Multiple keys, and multiple versions of the same key, can be kept in the Azure Key Vault. Cryptographic keys in Azure Key Vault are represented as JSON Web Key (JWK) objects.

Azure Key Vault 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-2 Level 3 validated HSMs.

The Azure Key Vault keys library client supports RSA keys and Elliptic Curve (EC) keys, each with corresponding support in hardware security modules (HSM). It offers operations to create, retrieve, update, delete, purge, backup, restore, and list the keys and its versions.

Source code | Package (NuGet) | API reference documentation | Product documentation | Samples | Migration guide

Getting started

Install the package

Install the Azure Key Vault keys client library for .NET with NuGet:

dotnet add package Azure.Security.KeyVault.Keys

Prerequisites

  • An Azure subscription.
  • An existing Azure Key Vault. If you need to create an Azure Key Vault, you can use the Azure Portal or Azure CLI.

See the final two steps in the next section for details on creating the Key Vault with the Azure CLI.

Authenticate the client

In order to interact with the Key Vault service, you'll need to create an instance of the KeyClient class. You need a vault url, which you may see as "DNS Name" in the portal, and client secret credentials (client id, client secret, tenant id) to instantiate a client object.

Client secret credential authentication is being used in this getting started section but you can find more ways to authenticate with Azure identity. To use the DefaultAzureCredential provider shown below, or other credential providers provided with the Azure SDK, you should install the Azure.Identity package:

dotnet add package Azure.Identity
Create/Get credentials

Use the Azure CLI snippet below to create/get client secret credentials.

  • Create a service principal and configure its access to Azure resources:

    az ad sp create-for-rbac -n <your-application-name> --skip-assignment
    

    Output:

    {
        "appId": "generated-app-ID",
        "displayName": "dummy-app-name",
        "name": "http://dummy-app-name",
        "password": "random-password",
        "tenant": "tenant-ID"
    }
    
  • Take note of the service principal objectId

    az ad sp show --id <appId> --query objectId
    

    Output:

    "<your-service-principal-object-id>"
    
  • Use the returned credentials above to set AZURE_CLIENT_ID (appId), AZURE_CLIENT_SECRET (password), and AZURE_TENANT_ID (tenant) environment variables. The following example shows a way to do this in Powershell:

    $Env:AZURE_CLIENT_ID="generated-app-ID"
    $Env:AZURE_CLIENT_SECRET="random-password"
    $Env:AZURE_TENANT_ID="tenant-ID"
    
  • Grant the above mentioned application authorization to perform key operations on the Azure Key Vault:

    # Use --hsm-name instead of --name for Managed HSM
    az keyvault set-policy --name <your-key-vault-name> --spn $Env:AZURE_CLIENT_ID --key-permissions backup delete get list create encrypt decrypt update
    

    --key-permissions: Accepted values: backup, create, decrypt, delete, encrypt, get, import, list, purge, recover, restore, sign, unwrapKey, update, verify, wrapKey

    If you have enabled role-based access control (RBAC) for Key Vault instead, you can find roles like "Key Vault Crypto Officer" in our RBAC guide. If you are managing your keys using Managed HSM, read about its access control that supports different built-in roles isolated from Azure Resource Manager (ARM).

  • Use the above mentioned Azure Key Vault name to retrieve details of your Vault which also contains your Azure Key Vault URL:

    # Use properties.hsmUri instead of properties.vaultUri for Managed HSM
    az keyvault show --name <your-key-vault-name> --query properties.vaultUri --output tsv
    
  • Create the Azure Key Vault or Managed HSM and grant the above mentioned application authorization to perform administrative operations on the Managed HSM (replace <your-resource-group-name> and <your-key-vault-name> with your own unique names and <your-service-principal-object-id> with the value from above):

If you are creating a standard Key Vault resource, use the following CLI command:

az keyvault create --resource-group <your-resource-group-name> --name <your-key-vault-name>

If you are creating a Managed HSM resource, use the following CLI command:

    az keyvault create --hsm-name <your-key-vault-name> --resource-group <your-resource-group-name> --administrators <your-service-principal-object-id> --location <your-azure-location>
Activate your managed HSM

This section only applies if you are creating a Managed HSM. All data plane commands are disabled until the HSM is activated. You will not be able to create keys or assign roles. Only the designated administrators that were assigned during the create command can activate the HSM. To activate the HSM you must download the security domain.

To activate your HSM you need:

  • Minimum 3 RSA key-pairs (maximum 10)
  • Specify minimum number of keys required to decrypt the security domain (quorum)

To activate the HSM you send at least 3 (maximum 10) RSA public keys to the HSM. The HSM encrypts the security domain with these keys and sends it back. Once this security domain is successfully downloaded, your HSM is ready to use. You also need to specify quorum, which is the minimum number of private keys required to decrypt the security domain.

The example below shows how to use openssl to generate 3 self signed certificate.

openssl req -newkey rsa:2048 -nodes -keyout cert_0.key -x509 -days 365 -out cert_0.cer
openssl req -newkey rsa:2048 -nodes -keyout cert_1.key -x509 -days 365 -out cert_1.cer
openssl req -newkey rsa:2048 -nodes -keyout cert_2.key -x509 -days 365 -out cert_2.cer

Use the az keyvault security-domain download command to download the security domain and activate your managed HSM. The example below uses 3 RSA key pairs (only public keys are needed for this command) and sets the quorum to 2.

az keyvault security-domain download --hsm-name <your-key-vault-name> --sd-wrapping-keys ./certs/cert_0.cer ./certs/cert_1.cer ./certs/cert_2.cer --sd-quorum 2 --security-domain-file ContosoMHSM-SD.json
Create KeyClient

Once you've populated the AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, and AZURE_TENANT_ID environment variables, replace vaultUrl with the output of az keyvault show in the example below to create the KeyClient:

// Create a new key client using the default credential from Azure.Identity using environment variables previously set,
// including AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, and AZURE_TENANT_ID.
var client = new KeyClient(vaultUri: new Uri(vaultUrl), credential: new DefaultAzureCredential());

// Create a new key using the key client.
KeyVaultKey key = client.CreateKey("key-name", KeyType.Rsa);

// Retrieve a key using the key client.
key = client.GetKey("key-name");
Create CryptographyClient

Once you've created a KeyVaultKey in the Azure Key Vault, you can also create the CryptographyClient:

// Create a new cryptography client using the same Key Vault or Managed HSM endpoint, service version,
// and options as the KeyClient created earlier.
CryptographyClient cryptoClient = client.GetCryptographyClient(key.Name, key.Properties.Version);

Key concepts

KeyVaultKey

Azure Key Vault supports multiple key types and algorithms, and enables the use of hardware security modules (HSM) for high value keys.

KeyClient

A KeyClient providing both synchronous and asynchronous operations exists in the SDK allowing for selection of a client based on an application's use case. Once you've initialized a KeyClient, you can interact with the primary resource types in Azure Key Vault.

CryptographyClient

A CryptographyClient providing both synchronous and asynchronous operations exists in the SDK allowing for selection of a client based on an application's use case. Once you've initialized a CryptographyClient, you can use it to perform cryptographic operations with keys stored in Azure Key Vault.

Thread safety

We guarantee that all client instance methods are thread-safe and independent of each other (guideline). This ensures that the recommendation of reusing client instances is always safe, even across threads.

Additional concepts

Client options | Accessing the response | Long-running operations | Handling failures | Diagnostics | Mocking | Client lifetime

Examples

The Azure.Security.KeyVault.Keys package supports synchronous and asynchronous APIs.

The following section provides several code snippets using the client created above, covering some of the most common Azure Key Vault key service related tasks:

Sync examples

Async examples

Create a key

Create a key to be stored in the Azure Key Vault. If a key with the same name already exists, then a new version of the key is created.

// Create a key. Note that you can specify the type of key
// i.e. Elliptic curve, Hardware Elliptic Curve, RSA
KeyVaultKey key = client.CreateKey("key-name", KeyType.Rsa);

Console.WriteLine(key.Name);
Console.WriteLine(key.KeyType);

// Create a software RSA key
var rsaCreateKey = new CreateRsaKeyOptions("rsa-key-name", hardwareProtected: false);
KeyVaultKey rsaKey = client.CreateRsaKey(rsaCreateKey);

Console.WriteLine(rsaKey.Name);
Console.WriteLine(rsaKey.KeyType);

// Create a hardware Elliptic Curve key
// Because only premium Azure Key Vault supports HSM backed keys , please ensure your Azure Key Vault
// SKU is premium when you set "hardwareProtected" value to true
var echsmkey = new CreateEcKeyOptions("ec-key-name", hardwareProtected: true);
KeyVaultKey ecKey = client.CreateEcKey(echsmkey);

Console.WriteLine(ecKey.Name);
Console.WriteLine(ecKey.KeyType);

Retrieve a key

GetKey retrieves a key previously stored in the Azure Key Vault.

KeyVaultKey key = client.GetKey("key-name");

Console.WriteLine(key.Name);
Console.WriteLine(key.KeyType);

Update an existing key

UpdateKeyProperties updates a key previously stored in the Azure Key Vault.

KeyVaultKey key = client.CreateKey("key-name", KeyType.Rsa);

// You can specify additional application-specific metadata in the form of tags.
key.Properties.Tags["foo"] = "updated tag";

KeyVaultKey updatedKey = client.UpdateKeyProperties(key.Properties);

Console.WriteLine(updatedKey.Name);
Console.WriteLine(updatedKey.Properties.Version);
Console.WriteLine(updatedKey.Properties.UpdatedOn);

Delete a key

StartDeleteKey starts a long-running operation to delete a key previously stored in the Azure Key Vault. You can retrieve the key immediately without waiting for the operation to complete. When soft-delete is not enabled for the Azure Key Vault, this operation permanently deletes the key.

DeleteKeyOperation operation = client.StartDeleteKey("key-name");

DeletedKey key = operation.Value;
Console.WriteLine(key.Name);
Console.WriteLine(key.DeletedOn);

Delete and purge a key

You will need to wait for the long-running operation to complete before trying to purge or recover the key.

DeleteKeyOperation operation = client.StartDeleteKey("key-name");

// You only need to wait for completion if you want to purge or recover the key.
while (!operation.HasCompleted)
{
    Thread.Sleep(2000);

    operation.UpdateStatus();
}

DeletedKey key = operation.Value;
client.PurgeDeletedKey(key.Name);

List Keys

This example lists all the keys in the specified Azure Key Vault.

Pageable<KeyProperties> allKeys = client.GetPropertiesOfKeys();

foreach (KeyProperties keyProperties in allKeys)
{
    Console.WriteLine(keyProperties.Name);
}

Encrypt and Decrypt

This example creates a CryptographyClient and uses it to encrypt and decrypt with a key in Azure Key Vault.

// Create a new cryptography client using the same Key Vault or Managed HSM endpoint, service version,
// and options as the KeyClient created earlier.
var cryptoClient = client.GetCryptographyClient(key.Name, key.Properties.Version);

byte[] plaintext = Encoding.UTF8.GetBytes("A single block of plaintext");

// encrypt the data using the algorithm RSAOAEP
EncryptResult encryptResult = cryptoClient.Encrypt(EncryptionAlgorithm.RsaOaep, plaintext);

// decrypt the encrypted data.
DecryptResult decryptResult = cryptoClient.Decrypt(EncryptionAlgorithm.RsaOaep, encryptResult.Ciphertext);

Create a key asynchronously

The asynchronous APIs are identical to their synchronous counterparts, but return with the typical "Async" suffix for asynchronous methods and return a Task.

// Create a key of any type
KeyVaultKey key = await client.CreateKeyAsync("key-name", KeyType.Rsa);

Console.WriteLine(key.Name);
Console.WriteLine(key.KeyType);

// Create a software RSA key
var rsaCreateKey = new CreateRsaKeyOptions("rsa-key-name", hardwareProtected: false);
KeyVaultKey rsaKey = await client.CreateRsaKeyAsync(rsaCreateKey);

Console.WriteLine(rsaKey.Name);
Console.WriteLine(rsaKey.KeyType);

// Create a hardware Elliptic Curve key
// Because only premium Azure Key Vault supports HSM backed keys , please ensure your Azure Key Vault
// SKU is premium when you set "hardwareProtected" value to true
var echsmkey = new CreateEcKeyOptions("ec-key-name", hardwareProtected: true);
KeyVaultKey ecKey = await client.CreateEcKeyAsync(echsmkey);

Console.WriteLine(ecKey.Name);
Console.WriteLine(ecKey.KeyType);

List keys asynchronously

Listing keys does not rely on awaiting the GetPropertiesOfKeysAsync method, but returns an AsyncPageable<KeyProperties> that you can use with the await foreach statement:

AsyncPageable<KeyProperties> allKeys = client.GetPropertiesOfKeysAsync();

await foreach (KeyProperties keyProperties in allKeys)
{
    Console.WriteLine(keyProperties.Name);
}

Delete a key asynchronously

When deleting a key asynchronously before you purge it, you can await the WaitForCompletionAsync method on the operation. By default, this loops indefinitely but you can cancel it by passing a CancellationToken.

DeleteKeyOperation operation = await client.StartDeleteKeyAsync("key-name");

// You only need to wait for completion if you want to purge or recover the key.
await operation.WaitForCompletionAsync();

DeletedKey key = operation.Value;
await client.PurgeDeletedKeyAsync(key.Name);

Troubleshooting

General

When you interact with the Azure Key Vault key client library using the .NET SDK, errors returned by the service correspond to the same HTTP status codes returned for REST API requests.

For example, if you try to retrieve a key that doesn't exist in your Azure Key Vault, a 404 error is returned, indicating "Not Found".

try
{
    KeyVaultKey key = client.GetKey("some_key");
}
catch (RequestFailedException ex)
{
    Console.WriteLine(ex.ToString());
}

You will notice that additional information is logged, like the client request ID of the operation.

Message:
    Azure.RequestFailedException : Service request failed.
    Status: 404 (Not Found)
Content:
    {"error":{"code":"KeyNotFound","message":"Key not found: some_key"}}

Headers:
    Cache-Control: no-cache
    Pragma: no-cache
    Server: Microsoft-IIS/10.0
    x-ms-keyvault-region: westus
    x-ms-request-id: 625f870e-10ea-41e5-8380-282e5cf768f2
    x-ms-keyvault-service-version: 1.1.0.866
    x-ms-keyvault-network-info: addr=131.107.174.199;act_addr_fam=InterNetwork;
    X-AspNet-Version: 4.0.30319
    X-Powered-By: ASP.NET
    Strict-Transport-Security: max-age=31536000;includeSubDomains
    X-Content-Type-Options: nosniff
    Date: Tue, 18 Jun 2019 16:02:11 GMT
    Content-Length: 75
    Content-Type: application/json; charset=utf-8
    Expires: -1

Next steps

Several Azure Key Vault keys client library samples are available to you in this GitHub repository. These samples provide example code for additional scenarios commonly encountered while working with Azure Key Vault:

  • Sample1_HelloWorld.md - for working with Azure Key Vault, including:

    • Create a key
    • Get an existing key
    • Update an existing key
    • Delete a key
  • Sample2_BackupAndRestore.md - Contains the code snippets working with Azure Key Vault keys, including:

    • Backup and recover a key
  • Sample3_GetKeys.md - Example code for working with Azure Key Vault keys, including:

    • Create keys
    • List all keys in the Key Vault
    • Update keys in the Key Vault
    • List versions of a specified key
    • Delete keys from the Key Vault
    • List deleted keys in the Key Vault
  • Sample4_EncryptDecrypt.md - Example code for performing cryptographic operations with Azure Key Vault keys, including:

    • Encrypt and Decrypt data with the CryptographyClient
  • Sample5_SignVerify.md - Example code for working with Azure Key Vault keys, including:

    • Sign a precalculated digest and verify the signature with Sign and Verify
    • Sign raw data and verify the signature with SignData and VerifyData
  • Sample6_WrapUnwrap.md - Example code for working with Azure Key Vault keys, including:

    • Wrap and Unwrap a symmetric key

Additional Documentation

Contributing

See the CONTRIBUTING.md for details on building, testing, and contributing to these libraries.

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com.

When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (65)

Showing the top 5 NuGet packages that depend on Azure.Security.KeyVault.Keys:

Package Downloads
Nuke.Common

The AKEless Build System for C#/.NET Signed by signpath.io from repository 'https://github.com/nuke-build/nuke' commit 'a94fbe2ca0c12a4bf2df0a4c92e9dc51ee8f1076' (see contained AppVeyorSettings.json file for build settings).

Azure.Extensions.AspNetCore.DataProtection.Keys

Microsoft Azure Key Vault key encryption support.

AspNetCore.HealthChecks.AzureKeyVault

HealthChecks.AzureKeyVault is the health check package for Azure Key Vault secrets

Microsoft.Data.SqlClient.AlwaysEncrypted.AzureKeyVaultProvider

Always Encrypted Azure Key Vault Provider for Microsoft.Data.SqlClient. This library enables .NET Core and .NET Framework applications to use Microsoft Azure Key Vault with Always Encrypted in Microsoft Azure SQL Database and Microsoft SQL Server. The library includes the column master key store provider that allows client applications to access data when a column master key is stored in Microsoft Azure Key Vault. For more information on Always Encrypted, please refer to: https://aka.ms/AlwaysEncrypted. Use this library only with the Microsoft.Data.SqlClient (https://www.nuget.org/packages/Microsoft.Data.SqlClient) client driver. If you are using the legacy .NET Framework Data Provider for SQL Server within the System.Data.SqlClient namespace in .NET Framework (https://www.nuget.org/packages/System.Data.SqlClient) as a client driver, you need to use Microsoft.SqlServer.Management.AlwaysEncrypted.AzureKeyVaultProvider (http://www.nuget.org/packages/Microsoft.SqlServer.Management.AlwaysEncrypted.AzureKeyVaultProvider) instead of this package. Available Types: Microsoft.Data.SqlClient.AlwaysEncrypted.AzureKeyStoreProvider.SqlColumnEncryptionAzureKeyVaultProvider

Apprio.Enablement.Web.Security

Package Description

GitHub repositories (17)

Showing the top 5 popular GitHub repositories that depend on Azure.Security.KeyVault.Keys:

Repository Stars
Azure/azure-sdk-for-net
This repository is for active development of the Azure SDK for .NET. For consumers of the SDK we recommend visiting our public developer docs at https://learn.microsoft.com/dotnet/azure/ or our versioned developer docs at https://azure.github.io/azure-sdk-for-net.
Azure/azure-powershell
Microsoft Azure PowerShell
Xabaril/AspNetCore.Diagnostics.HealthChecks
Enterprise HealthChecks for ASP.NET Core Diagnostics Package
nuke-build/nuke
🏗 The AKEless Build System for C#/.NET
Nethereum/Nethereum
Ethereum .Net cross platform integration library
Version Downloads Last updated
4.7.0 325,890 10/15/2024
4.6.0 4,352,970 2/15/2024
4.6.0-beta.2 59,676 11/13/2023
4.6.0-beta.1 20,820 11/10/2023
4.5.0 8,772,395 3/14/2023
4.5.0-beta.1 15,538 11/9/2022
4.4.0 2,583,491 9/20/2022
4.3.0 4,802,115 3/26/2022
4.3.0-beta.7 7,639 2/9/2022
4.3.0-beta.6 3,783 1/13/2022
4.3.0-beta.4 31,350 11/16/2021
4.3.0-beta.3 1,985 11/9/2021
4.3.0-beta.2 14,150 10/14/2021
4.3.0-beta.1 5,702 8/11/2021
4.2.0 13,043,570 6/16/2021
4.2.0-beta.6 1,132 5/12/2021
4.2.0-beta.5 7,291 3/9/2021
4.2.0-beta.4 3,975 2/11/2021
4.2.0-beta.3 110,099 11/13/2020
4.2.0-beta.2 95,792 10/7/2020
4.2.0-beta.1 21,329 9/9/2020
4.1.0 2,757,514 8/12/2020
4.1.0-preview.1 41,747 3/10/2020
4.0.4 84,924 7/9/2020
4.0.3 2,541,192 4/4/2020
4.0.2 1,004,066 3/4/2020
4.0.1 1,537,177 1/9/2020
4.0.0 631,866 10/31/2019
4.0.0-preview.5 1,236 10/8/2019
4.0.0-preview.4 486 9/11/2019
4.0.0-preview.2 3,018 8/9/2019
4.0.0-preview.1 439 6/28/2019