Skip to content

Instantly share code, notes, and snippets.

@mahoekst
Last active February 19, 2022 05:16
Show Gist options
  • Save mahoekst/16773cc1bebdf7db3b5fcaf079e8c059 to your computer and use it in GitHub Desktop.
Save mahoekst/16773cc1bebdf7db3b5fcaf079e8c059 to your computer and use it in GitHub Desktop.
Using Keyvault with client credentials
// create app registration in AAD and secret
// Go to Keyvault and add app in access policies
// give sign permissions!
//
using Azure.Identity;
using Azure.Security.KeyVault.Keys;
using Azure.Security.KeyVault.Keys.Cryptography;
using Azure.Security.KeyVault.Secrets;
using System;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace KeyVaultDIDTest
{
internal class Program
{
static async Task Main(string[] args)
{
const string keyVaultClientId = "APPID";
const string keyVaultClientSecret = "SECRET";
const string TenantId = "TENANTID";
const string kvURI = "https://YOURKEYVAULT.vault.azure.net/";
Console.WriteLine("Hello World!");
var cc = new ClientSecretCredential(TenantId, keyVaultClientId, keyVaultClientSecret);
var secretClient = new SecretClient(new Uri(kvURI), cc);
var keyClient = new KeyClient(new Uri(kvURI), cc);
var kvKey = await keyClient.GetKeyAsync("YOURKEYNAME");
var cryptoClient = new CryptographyClient(keyId: kvKey.Value.Id, cc);
byte[] data = Encoding.UTF8.GetBytes("This is some sample data which we will use to demonstrate sign and verify");
byte[] digest = null;
using (HashAlgorithm hashAlgo = SHA256.Create())
{
digest = hashAlgo.ComputeHash(data);
}
SignResult ecSignResult = cryptoClient.Sign(SignatureAlgorithm.ES256K, digest);
Console.WriteLine($"Signed digest using the algorithm {ecSignResult.Algorithm}, with key {ecSignResult.KeyId}. The resulting signature is {Convert.ToBase64String(ecSignResult.Signature)}");
VerifyResult ecVerifyResult = cryptoClient.Verify(SignatureAlgorithm.ES256K, digest, ecSignResult.Signature);
Console.WriteLine($"Verified the signature using the algorithm {ecVerifyResult.Algorithm}, with key {ecVerifyResult.KeyId}. Signature is valid: {ecVerifyResult.IsValid}");
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment