What is Key Vault

Key Vault is a managed service for managing keys and secrets. It can be used for:

  • store and retrieve secrets (like passwords, connection strings)
  • generate and retrieve keys for encrypting and decrypting by yourself
  • encrypting and decrypting inside Key Vault (this is the recommended way, because it is not necessary that the key leaves Key Vault)
  • to store and retrieve certificates

We will focus on getting secrets and crypt and decrypt in this article.

Configure Key Vault and Solution

  1. Setup MSI (Managed Service Identity) for the service you plan to use:
    • I use App Services can simple activate MSI
    • MSI will create an AD application for you, that you can grant access to Key Vault
    • this is a much better way instead of using ClientID and ClientSecret, because you must store them in the Application Settings
    • if you develop local, check if your user has access to Key Vault and run az login, your app will authenticate with your credentials to Key Vault and you can test everything locally
  2. Adding NuGet Packages:
    • „Microsoft.Azure.Services.AppAuthentication“ for MSI
    • „Microsoft.Azure.KeyVault“ for using Key Vault
  3. Configure the „Access Policy“ in Key Vault for your application, to access keys or to process encryption/decryption (like you need)

Using Key Vault

The soure code of this example is hosted at GutHub: https://github.com/ArvatoSystems/UsingAzureKeyVault

You need a KeyVaultClient instance to work with Key Vault. You can genrate the client like this: https://github.com/ArvatoSystems/UsingAzureKeyVault/blob/master/KeyVaultUsing/Services/KeyVaultService.cs#L59-L69


If you want to retrieve a secret, using the secret identifier

and use the GetSecretAsync-method:

public string GetSecret(string secretIdentifier)
    var kv = GetKeyVaultClient(GetKeyVaultCallback());
    var sec = kv.GetSecretAsync(secretIdentifier);
    return sec.Result.Value;


For encrypting/decrypting using the keyidentifier:

and use the EncryptAsync and DecryptAsync methods:

public byte[] Encrypt(string keyIdentifier, string text2encrypt)
    var kv = GetKeyVaultClient(GetKeyVaultCallback());
    byte[] text_as_byte = Encoding.UTF8.GetBytes(text2encrypt);
    var enc = kv.EncryptAsync(keyIdentifier, JsonWebKeyEncryptionAlgorithm.RSA15, text_as_byte).GetAwaiter().GetResult();
    return enc.Result;

public string Decrypt(string keyIdentifier, byte[] text2decrypt)
    var kv = GetKeyVaultClient(GetKeyVaultCallback());
    var dec = kv.DecryptAsync(keyIdentifier, JsonWebKeyEncryptionAlgorithm.RSA15, text2decrypt).GetAwaiter().GetResult();
    return Encoding.UTF8.GetString(dec.Result);