/// <summary> /// Lists certificates in a vault /// </summary> private static void ListCertificates() { var vaultAddress = inputValidator.GetVaultAddress(); var numSecretsInVault = 0; var maxResults = 1; Console.Out.WriteLine("List certificate:---------------"); var results = keyVaultClient.GetCertificatesAsync(vaultAddress, maxResults).GetAwaiter().GetResult(); if (results != null) { numSecretsInVault += results.Count(); foreach (var m in results) { Console.Out.WriteLine("\t{0}", m.Identifier.Name); } } while (results != null && !string.IsNullOrWhiteSpace(results.NextPageLink)) { results = keyVaultClient.GetCertificatesNextAsync(results.NextPageLink).GetAwaiter().GetResult(); if (results != null && results != null) { numSecretsInVault += results.Count(); foreach (var m in results) { Console.Out.WriteLine("\t{0}", m.Identifier.Name); } } } Console.Out.WriteLine("\n\tNumber of certificates in the vault: {0}", numSecretsInVault); }
private static async Task <List <string> > GetCertificatesAsync() { // Gets the list of certificates. var secrets = await _kv.GetCertificatesAsync(_baseUri).ConfigureAwait(false); // Returns the list of certificate names. return(secrets.Select(p => p.Identifier.Name).ToList()); }
public async Task <List <CertificateModel> > GetCertificatesInVaultAsync(string vaultUri) { var totalItems = new List <CertificateItem>(); var certs = await kvClient.GetCertificatesAsync(vaultUri).ConfigureAwait(false); totalItems.AddRange(certs); var nextLink = certs.NextPageLink; // Get the rest if there's more while (!string.IsNullOrWhiteSpace(nextLink)) { certs = await kvClient.GetCertificatesNextAsync(nextLink).ConfigureAwait(false); totalItems.AddRange(certs); nextLink = certs.NextPageLink; } // Get keys since they may be there for pending certs var totalKeys = new List <KeyItem>(); var keys = await kvClient.GetKeysAsync(vaultUri).ConfigureAwait(false); totalKeys.AddRange(keys); nextLink = keys.NextPageLink; // Get the rest if there's more while (!string.IsNullOrWhiteSpace(nextLink)) { keys = await kvClient.GetKeysNextAsync(nextLink).ConfigureAwait(false); totalKeys.AddRange(keys); nextLink = keys.NextPageLink; } // only get the ones where we don't have a cert var keyDict = totalKeys.ToDictionary(ki => ki.Kid.Substring(ki.Kid.LastIndexOf("/") + 1)); var models = totalItems .Select(ci => new CertificateModel { Name = ci.Id.Substring(ci.Id.LastIndexOf("/") + 1), CertificateIdentifier = ci.Identifier.Identifier, Thumbprint = BitConverter.ToString(ci.X509Thumbprint).Replace("-", ""), Attributes = ci.Attributes }).ToList(); foreach (var model in models) { keyDict.Remove(model.Name); } models.AddRange(keyDict.Select(kvp => new CertificateModel { Name = kvp.Key })); return(models.OrderBy(cm => cm.Name).ToList()); }
public async Task <IList <CertificateBundle> > GetCertificates([ActivityTrigger] DateTime currentDateTime) { var certificates = await _keyVaultClient.GetCertificatesAsync(Settings.Default.VaultBaseUrl); var list = certificates.Where(x => x.Tags != null && x.Tags.TryGetValue("Issuer", out var issuer) && issuer == "letsencrypt.org") .Where(x => (x.Attributes.Expires.Value - currentDateTime).TotalDays < 30) .ToArray(); var bundles = new List <CertificateBundle>(); foreach (var item in list) { bundles.Add(await _keyVaultClient.GetCertificateAsync(item.Id)); } return(bundles); }
private async Task CertificatesMigrationGuide() { #region Snippet:Microsoft_Azure_KeyVault_Certificates_Snippets_MigrationGuide_Create AzureServiceTokenProvider provider = new AzureServiceTokenProvider(); KeyVaultClient client = new KeyVaultClient( new KeyVaultClient.AuthenticationCallback(provider.KeyVaultTokenCallback)); #endregion Snippet:Microsoft_Azure_KeyVault_Certificates_Snippets_MigrationGuide_Create #region Snippet:Microsoft_Azure_KeyVault_Certificates_Snippets_MigrationGuide_CreateWithOptions using (HttpClient httpClient = new HttpClient()) { //@@AzureServiceTokenProvider provider = new AzureServiceTokenProvider(); /*@@*/ provider = new AzureServiceTokenProvider(); //@@KeyVaultClient client = new KeyVaultClient( /*@@*/ client = new KeyVaultClient( new KeyVaultClient.AuthenticationCallback(provider.KeyVaultTokenCallback), httpClient); } #endregion Snippet:Microsoft_Azure_KeyVault_Certificates_Snippets_MigrationGuide_CreateWithOptions #region Snippet:Microsoft_Azure_KeyVault_Certificates_Snippets_MigrationGuide_CreateCustomPolicy CertificatePolicy policy = new CertificatePolicy { IssuerParameters = new IssuerParameters("issuer-name"), SecretProperties = new SecretProperties("application/x-pkcs12"), KeyProperties = new KeyProperties { KeyType = "RSA", KeySize = 2048, ReuseKey = true }, X509CertificateProperties = new X509CertificateProperties("CN=customdomain.com") { KeyUsage = new[] { KeyUsageType.CRLSign, KeyUsageType.DataEncipherment, KeyUsageType.DigitalSignature, KeyUsageType.KeyEncipherment, KeyUsageType.KeyAgreement, KeyUsageType.KeyCertSign }, ValidityInMonths = 12 }, LifetimeActions = new[] { new LifetimeAction( new Trigger { DaysBeforeExpiry = 90 }, new Models.Action(ActionType.AutoRenew)) } }; #endregion Snippet:Microsoft_Azure_KeyVault_Certificates_Snippets_MigrationGuide_CreateCustomPolicy { #region Snippet:Microsoft_Azure_KeyVault_Certificates_Snippets_MigrationGuide_CreateCertificate CertificateBundle certificate = null; // Start certificate creation. // Depending on the policy and your business process, this could even take days for manual signing. CertificateOperation createOperation = await client.CreateCertificateAsync("https://myvault.vault.azure.net", "certificate-name", policy); while (true) { if ("InProgress".Equals(createOperation.Status, StringComparison.OrdinalIgnoreCase)) { await Task.Delay(TimeSpan.FromSeconds(20)); createOperation = await client.GetCertificateOperationAsync("https://myvault.vault.azure.net", "certificate-name"); continue; } if ("Completed".Equals(createOperation.Status, StringComparison.OrdinalIgnoreCase)) { certificate = await client.GetCertificateAsync(createOperation.Id); break; } throw new Exception(string.Format( CultureInfo.InvariantCulture, "Polling on pending certificate returned an unexpected result. Error code = {0}, Error message = {1}", createOperation.Error.Code, createOperation.Error.Message)); } // If you need to restart the application you can recreate the operation and continue awaiting. do { createOperation = await client.GetCertificateOperationAsync("https://myvault.vault.azure.net", "certificate-name"); if ("InProgress".Equals(createOperation.Status, StringComparison.OrdinalIgnoreCase)) { await Task.Delay(TimeSpan.FromSeconds(20)); continue; } if ("Completed".Equals(createOperation.Status, StringComparison.OrdinalIgnoreCase)) { certificate = await client.GetCertificateAsync(createOperation.Id); break; } throw new Exception(string.Format( CultureInfo.InvariantCulture, "Polling on pending certificate returned an unexpected result. Error code = {0}, Error message = {1}", createOperation.Error.Code, createOperation.Error.Message)); } while (true); #endregion Snippet:Azure_Security_KeyVault_Certificates_Snippets_MigrationGuide_CreateCertificate } { #region Snippet:Microsoft_Azure_KeyVault_Certificates_Snippets_MigrationGuide_ImportCertificate byte[] cer = File.ReadAllBytes("certificate.pfx"); string cerBase64 = Convert.ToBase64String(cer); CertificateBundle certificate = await client.ImportCertificateAsync( "https://myvault.vault.azure.net", "certificate-name", cerBase64, certificatePolicy : policy); #endregion Snippet:Microsoft_Azure_KeyVault_Certificates_Snippets_MigrationGuide_ImportCertificate } #region Snippet:Microsoft_Azure_KeyVault_Certificates_Snippets_MigrationGuide_CreateSelfSignedPolicy //@@CertificatePolicy policy = new CertificatePolicy /*@@*/ policy = new CertificatePolicy { IssuerParameters = new IssuerParameters("Self"), X509CertificateProperties = new X509CertificateProperties("CN=DefaultPolicy") }; #endregion Snippet:Microsoft_Azure_KeyVault_Certificates_Snippets_MigrationGuide_CreateSelfSignedPolicy // TODO { #region Snippet:Microsoft_Azure_KeyVault_Certificates_Snippets_MigrationGuide_ListCertificates IPage <CertificateItem> page = await client.GetCertificatesAsync("https://myvault.vault.azure.net"); foreach (CertificateItem item in page) { CertificateIdentifier certificateId = item.Identifier; CertificateBundle certificate = await client.GetCertificateAsync(certificateId.Vault, certificateId.Name); } while (page.NextPageLink != null) { page = await client.GetCertificatesNextAsync(page.NextPageLink); foreach (CertificateItem item in page) { CertificateIdentifier certificateId = item.Identifier; CertificateBundle certificate = await client.GetCertificateAsync(certificateId.Vault, certificateId.Name); } } #endregion Snippet:Microsoft_Azure_KeyVault_Certificates_Snippets_MigrationGuide_ListCertificates } { #region Snippet:Microsoft_Azure_KeyVault_Certificates_Snippets_MigrationGuide_DeleteCertificate // Delete the certificate. DeletedCertificateBundle deletedCertificate = await client.DeleteCertificateAsync("https://myvault.vault.azure.net", "certificate-name"); // Purge or recover the deleted certificate if soft delete is enabled. if (deletedCertificate.RecoveryId != null) { DeletedCertificateIdentifier deletedCertificateId = deletedCertificate.RecoveryIdentifier; // Deleting a certificate does not happen immediately. Wait a while and check if the deleted certificate exists. while (true) { try { await client.GetDeletedCertificateAsync(deletedCertificateId.Vault, deletedCertificateId.Name); // Finally deleted. break; } catch (KeyVaultErrorException ex) when(ex.Response.StatusCode == HttpStatusCode.NotFound) { // Not yet deleted... } } // Purge the deleted certificate. await client.PurgeDeletedCertificateAsync(deletedCertificateId.Vault, deletedCertificateId.Name); // You can also recover the deleted certificate using RecoverDeletedCertificateAsync. } #endregion Snippet:Microsoft_Azure_KeyVault_Certificates_Snippets_MigrationGuide_DeleteCertificate } }