Skip to content

Keyvault extensions

Jean-Marc Prieur edited this page Jan 5, 2024 · 4 revisions

Microsoft.IdentityModel.KeyVaultExtensions

Microsoft.IdentityModel.KeyVaultExtensions contains classes to delegate to KeyVault crypto operations. Instead of loading a certificate and using its keys, you let KeyVault do it.

KeyVaultSecurityKey

KeyVaultSecurityKey is a class that represents a cryptographic key stored in Azure Key Vault1.

To use KeyVaultSecurityKey, you need to create an instance of it with a key identifier and an optional authentication callback. For example:

// Create a KeyVaultSecurityKey from a key identifier
var key = new KeyVaultSecurityKey(keyIdentifier);

// Optionally, provide an authentication callback delegate that retrieves an access token for the KeyVault
key.Callback = async (authority, resource, scope) =>
{
    // Use your preferred authentication method to get an access token
    var credential = new DefaultAzureCredential();
    var token = await credential.GetTokenAsync(new TokenRequestContext(new[] { resource + "/.default" }));
    return token.Token;
};

You can use the KeyVaultSecurityKey as a SecurityKey for signing and verifying operations using the KeyVaultSignatureProvider class decribed below.

KeyVaultSignatureProvider

KeyVaultSignatureProvider is a class that provides signing and verifying operations using Azure Key Vault

To use KeyVaultSignatureProvider, you need to create an instance of it with a SecurityKey, a signature algorithm, and a boolean indicating whether it will create signatures or not. For example:

// Create a KeyVaultSecurityKey from a key identifier
var key = new KeyVaultSecurityKey(keyIdentifier);

// Create a KeyVaultSignatureProvider with the key, the algorithm, and the flag
var provider = new KeyVaultSignatureProvider(key, SecurityAlgorithms.RsaSha256, true);

// Sign some data using the provider
var data = Encoding.UTF8.GetBytes("Hello, world!");
var signature = provider.Sign(data);

// Verify the signature using the provider
var result = provider.Verify(data, signature);

You can also use the Sign and Verify methods of the KeyVaultSignatureProvider class to produce and verify signatures over byte arrays using Azure Key Vault.

Clone this wiki locally