Skip to content

Instantly share code, notes, and snippets.

@ulve
Last active December 12, 2018 17:42
Show Gist options
  • Save ulve/82bb08f147f1c2d2c900a67574c2dd9e to your computer and use it in GitHub Desktop.
Save ulve/82bb08f147f1c2d2c900a67574c2dd9e to your computer and use it in GitHub Desktop.
How to create a self signed certificate in azure key vault
// This creates the certificate
AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
KeyVaultClient keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
var vaultBaseUrl = "https://youvault.vault.azure.net/";
var policy = new CertificatePolicy
{
IssuerParameters = new IssuerParameters
{
Name = "self"
},
X509CertificateProperties = new X509CertificateProperties
{
Subject = "CN=" + certificateName
}
};
await keyVaultClient.CreateCertificateAsync(vaultBaseUrl, certificateName, policy);
// This will take a while and is not finished just because it is created. Needs to be signed too
// This is how to get the thumbprints while waiting
AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
KeyVaultClient keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
var certificateIdentifier = "https://yourkeyvault.vault.azure.net/certificates/" + certificateName;
var retries = 10;
CertificateBundle cert = null;
while ((cert == null || cert.X509Thumbprint == null) && retries > 0)
{
retries--;
cert = await keyVaultClient.GetCertificateAsync(certificateIdentifier);
}
return string.Concat(cert.X509Thumbprint.Select(i => i.ToString("X2")))
// And this is how you export a certificate as a pfx
AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
KeyVaultClient keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
var certificateIdentifierSecretPart = "https://yourkeyvault.vault.azure.net/secrets/" + certificateName;
SecretBundle certificatePrivateKeySecretBundle = await keyVaultClient.GetSecretAsync(certificateIdentifierSecretPart);
byte[] privateKeyBytes = Convert.FromBase64String(certificatePrivateKeySecretBundle.Value);
X509Certificate2 certificateWithPrivateKey = new X509Certificate2(privateKeyBytes, (string)null, X509KeyStorageFlags.Exportable);
return Convert.ToBase64String(certificateWithPrivateKey.Export(X509ContentType.Pfx));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment