public async Task ImportPemCertificateAsync()
        {
            // Environment variable with the Key Vault endpoint.
            string keyVaultUrl = TestEnvironment.KeyVaultUrl;

            CertificateClient client = new CertificateClient(new Uri(keyVaultUrl), new DefaultAzureCredential());

            string name = $"cert-{Guid.NewGuid()}";

            //@@ byte[] pem = File.ReadAllBytes("certificate.cer");
            /*@@*/ byte[]            pem           = Encoding.ASCII.GetBytes(s_pem);
            ImportCertificateOptions importOptions = new ImportCertificateOptions(name, pem)
            {
                Policy = new CertificatePolicy(WellKnownIssuerNames.Self, "CN=contoso.com")
                {
                    // Required when the certificate bytes are a PEM-formatted certificate.
                    ContentType = CertificateContentType.Pem,

                    // Optionally mark the private key exportable.
                    Exportable = true
                }
            };

            await client.ImportCertificateAsync(importOptions);

            DeleteCertificateOperation operation = await client.StartDeleteCertificateAsync(name);

            // To ensure certificates are deleted on server side.
            // You only need to wait for completion if you want to purge or recover the certificate.
            await operation.WaitForCompletionAsync();

            client.PurgeDeletedCertificate(name);
        }
Пример #2
0
        public async Task SaveAsync(X509Certificate2 certificate, CancellationToken cancellationToken)
        {
            var domainName = certificate.GetNameInfo(X509NameType.DnsName, false);

            _logger.LogInformation("Saving certificate for {Domain} in Azure KeyVault.", domainName);

            if (!(await ShouldImportVersionAsync(domainName, certificate, cancellationToken)))
            {
                _logger.LogInformation("Certificate for {Domain} is already up-to-date in Azure KeyVault. Skipping importing.", domainName);
                return;
            }

            var exported = certificate.Export(X509ContentType.Pfx);

            var options = new ImportCertificateOptions(NormalizeHostName(domainName), exported);

            try
            {
                await _client.ImportCertificateAsync(options, cancellationToken);

                _logger.LogInformation("Imported certificate into Azure KeyVault for {Domain}", domainName);
            }
            catch (RequestFailedException ex)
            {
                _logger.LogWarning(ex, "Failed to save {Domain} certificate to Azure KeyVault", domainName);
            }
        }
        public async Task ImportPfxCertificateAsync()
        {
            // Environment variable with the Key Vault endpoint.
            string keyVaultUrl = TestEnvironment.KeyVaultUrl;

            CertificateClient client = new CertificateClient(new Uri(keyVaultUrl), new DefaultAzureCredential());

            string name = $"cert-{Guid.NewGuid()}";

            //@@ byte[] pfx = File.ReadAllBytes("certificate.pfx");
            /*@@*/ byte[]            pfx           = Convert.FromBase64String(s_pfxBase64);
            ImportCertificateOptions importOptions = new ImportCertificateOptions(name, pfx)
            {
                Policy = new CertificatePolicy(WellKnownIssuerNames.Self, "CN=contoso.com")
                {
                    // Required when setting a policy; if no policy required, Pfx is assumed.
                    ContentType = CertificateContentType.Pkcs12,

                    // Optionally mark the private key exportable.
                    Exportable = true
                }
            };

            await client.ImportCertificateAsync(importOptions);

            DeleteCertificateOperation operation = await client.StartDeleteCertificateAsync(name);

            // To ensure certificates are deleted on server side.
            // You only need to wait for completion if you want to purge or recover the certificate.
            await operation.WaitForCompletionAsync();

            client.PurgeDeletedCertificate(name);
        }
Пример #4
0
        public async Task <(string, string)> ImportCertificate(string certificateName, byte[] certificate, string password)
        {
            var result = await certificateClient.ImportCertificateAsync(new ImportCertificateOptions(certificateName, certificate)
            {
                Password = password
            });

            return(result.Value.Properties.Name, result.Value.Properties.Version);
        }
Пример #5
0
        /// <summary>
        /// Deploy current cert to Azure Key Vault
        /// </summary>
        /// <param name="log"></param>
        /// <param name="managedCert"></param>
        /// <param name="settings"></param>
        /// <param name="credentials"></param>
        /// <param name="isPreviewOnly"></param>
        /// <returns></returns>
        public async Task <List <ActionResult> > Execute(DeploymentTaskExecutionParams execParams)
        {
            var definition = GetDefinition(execParams.Definition);

            var results = await Validate(execParams);

            if (results.Any())
            {
                return(results);
            }

            var managedCert = ManagedCertificate.GetManagedCertificate(execParams.Subject);

            if (string.IsNullOrEmpty(managedCert.CertificatePath))
            {
                results.Add(new ActionResult("No certificate to deploy.", false));
                return(results);
            }

            var keyVaultUri = new Uri(execParams.Settings.Parameters.FirstOrDefault(c => c.Key == "vault_uri")?.Value);

            var pfxData = File.ReadAllBytes(managedCert.CertificatePath);

            // from application user details in Azure AD

            var cred = new ClientSecretCredential(execParams.Credentials["tenantid"], execParams.Credentials["clientid"], execParams.Credentials["secret"]);

            var client = new CertificateClient(keyVaultUri, cred);

            var customName = execParams.Settings.Parameters.FirstOrDefault(c => c.Key == "cert_name")?.Value;

            var certName = GetStringAsKeyVaultName(customName ?? managedCert.Name);

            var importOptions = new ImportCertificateOptions(certName, pfxData);

            try
            {
                await client.ImportCertificateAsync(importOptions);

                execParams.Log.Information($"Deployed certificate [{certName}] to Azure Key Vault");

                results.Add(new ActionResult("Certificate Deployed to Azure Key Vault", true));
            }
            catch (AuthenticationFailedException exp)
            {
                execParams.Log.Error($"Azure Authentiation error: {exp.InnerException?.Message ?? exp.Message}");
                results.Add(new ActionResult("Key Vault Deployment Failed", false));
            }
            catch (Exception exp)
            {
                execParams.Log.Error($"Failed to deploy certificate [{certName}] to Azure Key Vault :{exp}");
                results.Add(new ActionResult("Key Vault Deployment Failed", false));
            }

            return(results);
        }
        public async Task UploadCertificateAsync(string name, Uri keyVaultUri, byte[] pfxCertificate, string pfxPassword)
        {
            var client = new CertificateClient(keyVaultUri, azureCredential);

            var importOptions = new ImportCertificateOptions(name, pfxCertificate)
            {
                Password = pfxPassword,
                Enabled  = true
            };

            logger.LogInformation("Upload the certificate to KeyVault: KeyVault={keyVaultUri}, Name={certName}", keyVaultUri, name);

            await client.ImportCertificateAsync(importOptions);
        }
Пример #7
0
        private async Task <KeyVaultCertificateWithPolicy> ImportCertificateAsync(
            byte[] certificate,
            string password,
            CancellationToken cancellationToken)
        {
            var options = new ImportCertificateOptions(_certificateName, certificate)
            {
                Password = password,
                Enabled  = true
            };
            var result = await _certificateClient.ImportCertificateAsync(options, cancellationToken);

            return(result.Value);
        }
Пример #8
0
        public async Task <string> ImportCertificateAsync([ActivityTrigger] AddCertificateRequestRecord record, ILogger log)
        {
            log.LogInformation($"Creating certificate for {record.Hostname}");

            var certificateName = record.Hostname.Replace("*", "wildcard").Replace(".", "-");
            var certificate     = record.Certificate
                                  .Replace("-----BEGIN CERTIFICATE-----", "")
                                  .Replace("-----END CERTIFICATE-----", "");
            var privateKey = record.PrivateKey
                             .Replace("-----BEGIN PRIVATE KEY-----", "")
                             .Replace("-----END PRIVATE KEY-----", "");

            var certificateByteArray = Encoding.ASCII.GetBytes(certificate);
            var x509Certificate      = new X509Certificate2(certificateByteArray);

            using RSA rsa = RSA.Create();
            var privateKeyByteArray = Convert.FromBase64String(privateKey);

            if (record.Password == null)
            {
                rsa.ImportPkcs8PrivateKey(new ReadOnlySpan <byte>(privateKeyByteArray), out _);
            }
            else
            {
                rsa.ImportEncryptedPkcs8PrivateKey(record.Password, new ReadOnlySpan <byte>(privateKeyByteArray), out _);
            }
            var x509CertificateWithPrivateKey = x509Certificate.CopyWithPrivateKey(rsa);

            // Import certificate with the new Certificate Client
            var options = new ImportCertificateOptions(certificateName, x509CertificateWithPrivateKey.Export(X509ContentType.Pfx))
            {
                Password = record.Password
            };

            options.Tags.Add("Hostname", record.Hostname);
            var cert = await _certificateClient.ImportCertificateAsync(options);

            return(cert.Value.SecretId.AbsoluteUri);
        }
Пример #9
0
        private async Task MigrationGuide()
        {
            #region Snippet:Azure_Security_KeyVault_Certificates_Snippets_MigrationGuide_Create
            CertificateClient client = new CertificateClient(
                new Uri("https://myvault.vault.azure.net"),
                new DefaultAzureCredential());
            #endregion Snippet:Azure_Security_KeyVault_Certificates_Snippets_MigrationGuide_Create

            #region Snippet:Azure_Security_KeyVault_Certificates_Snippets_MigrationGuide_CreateWithOptions
            using (HttpClient httpClient = new HttpClient())
            {
                CertificateClientOptions options = new CertificateClientOptions
                {
                    Transport = new HttpClientTransport(httpClient)
                };

                //@@CertificateClient client = new CertificateClient(
                /*@@*/ CertificateClient _ = new CertificateClient(
                    new Uri("https://myvault.vault.azure.net"),
                    new DefaultAzureCredential(),
                    options);
            }
            #endregion Snippet:Azure_Security_KeyVault_Certificates_Snippets_MigrationGuide_CreateWithOptions

            #region Snippet:Azure_Security_KeyVault_Certificates_Snippets_MigrationGuide_CreateCustomPolicy
            CertificatePolicy policy = new CertificatePolicy("issuer-name", "CN=customdomain.com")
            {
                ContentType = CertificateContentType.Pkcs12,
                KeyType     = CertificateKeyType.Rsa,
                ReuseKey    = true,
                KeyUsage    =
                {
                    CertificateKeyUsage.CrlSign,
                    CertificateKeyUsage.DataEncipherment,
                    CertificateKeyUsage.DigitalSignature,
                    CertificateKeyUsage.KeyEncipherment,
                    CertificateKeyUsage.KeyAgreement,
                    CertificateKeyUsage.KeyCertSign
                },
                ValidityInMonths = 12,
                LifetimeActions  =
                {
                    new LifetimeAction(CertificatePolicyAction.AutoRenew)
                    {
                        DaysBeforeExpiry = 90,
                    }
                }
            };
            #endregion Snippet:Azure_Security_KeyVault_Certificates_Snippets_MigrationGuide_CreateSelfSignedPolicy

            #region Snippet:Azure_Security_KeyVault_Certificates_Snippets_MigrationGuide_CreateSelfSignedPolicy
            //@@CertificatePolicy policy = CertificatePolicy.Default;
            /*@@*/ policy = CertificatePolicy.Default;
            #endregion Snippet:Azure_Security_KeyVault_Certificates_Snippets_MigrationGuide_CreateSelfSignedPolicy

            {
                #region Snippet:Azure_Security_KeyVault_Certificates_Snippets_MigrationGuide_CreateCertificate
                // Start certificate creation.
                // Depending on the policy and your business process, this could even take days for manual signing.
                CertificateOperation createOperation = await client.StartCreateCertificateAsync("certificate-name", policy);

                KeyVaultCertificateWithPolicy certificate = await createOperation.WaitForCompletionAsync(TimeSpan.FromSeconds(20), CancellationToken.None);

                // If you need to restart the application you can recreate the operation and continue awaiting.
                createOperation = new CertificateOperation(client, "certificate-name");
                certificate     = await createOperation.WaitForCompletionAsync(TimeSpan.FromSeconds(20), CancellationToken.None);

                #endregion Snippet:Azure_Security_KeyVault_Certificates_Snippets_MigrationGuide_CreateCertificate
            }

            {
                #region Snippet:Azure_Security_KeyVault_Certificates_Snippets_MigrationGuide_ImportCertificate
                byte[] cer = File.ReadAllBytes("certificate.pfx");
                ImportCertificateOptions importCertificateOptions = new ImportCertificateOptions("certificate-name", cer)
                {
                    Policy = policy
                };

                KeyVaultCertificateWithPolicy certificate = await client.ImportCertificateAsync(importCertificateOptions);

                #endregion Snippet:Azure_Security_KeyVault_Certificates_Snippets_MigrationGuide_ImportCertificate
            }

            {
                #region Snippet:Azure_Security_KeyVault_Certificates_Snippets_MigrationGuide_ListCertificates
                // List all certificates asynchronously.
                await foreach (CertificateProperties item in client.GetPropertiesOfCertificatesAsync())
                {
                    KeyVaultCertificateWithPolicy certificate = await client.GetCertificateAsync(item.Name);
                }

                // List all certificates synchronously.
                foreach (CertificateProperties item in client.GetPropertiesOfCertificates())
                {
                    KeyVaultCertificateWithPolicy certificate = client.GetCertificate(item.Name);
                }
                #endregion Snippet:Azure_Security_KeyVault_Certificates_Snippets_MigrationGuide_ListCertificates
            }

            {
                #region Snippet:Azure_Security_KeyVault_Certificates_Snippets_MigrationGuide_DeleteCertificate
                // Delete the certificate.
                DeleteCertificateOperation deleteOperation = await client.StartDeleteCertificateAsync("certificate-name");

                // Purge or recover the deleted certificate if soft delete is enabled.
                if (deleteOperation.Value.RecoveryId != null)
                {
                    // Deleting a certificate does not happen immediately. Wait for the certificate to be deleted.
                    DeletedCertificate deletedCertificate = await deleteOperation.WaitForCompletionAsync();

                    // Purge the deleted certificate.
                    await client.PurgeDeletedCertificateAsync(deletedCertificate.Name);

                    // You can also recover the deleted certificate using StartRecoverDeletedCertificateAsync,
                    // which returns RecoverDeletedCertificateOperation you can await like DeleteCertificateOperation above.
                }
                #endregion Snippet:Azure_Security_KeyVault_Certificates_Snippets_MigrationGuide_DeleteCertificate
            }
        }
        public async Task StorePfxCertificateAsync(string identifier, byte[] pfx)
        {
            var import = new ImportCertificateOptions(identifier, pfx);

            await certClient.ImportCertificateAsync(import);
        }