private async Task GetCertificateFromKeyVault()
        {
            try
            {
                string keyVaultUri    = KeyVaultOptions.Value.KeyVaultUri;
                string tenantId       = KeyVaultOptions.Value.TenantId;
                string clientId       = KeyVaultOptions.Value.ClientId;
                string clientSecret   = KeyVaultOptions.Value.ClientSecret;
                string certificateUrl = KeyVaultOptions.Value.CertificateUrl;

                var          credential   = new ClientSecretCredential(tenantId, clientId, clientSecret);
                SecretClient secretClient = new SecretClient(new Uri(keyVaultUri), credential);

                KeyVaultSecret keyVaultCertificatePfx = await secretClient.GetSecretAsync(certificateUrl);

                CertificateClient             certificateClient      = new CertificateClient(new Uri(keyVaultUri), credential);
                KeyVaultCertificateWithPolicy keyVaultCertificateCer = await certificateClient.GetCertificateAsync(certificateUrl.Replace("/secrets/", "/certificates/", StringComparison.OrdinalIgnoreCase));

                DecryptionCertificate        = keyVaultCertificatePfx.Value;
                this.EncryptionCertificate   = Convert.ToBase64String(keyVaultCertificateCer.Cer);
                this.EncryptionCertificateId = keyVaultCertificatePfx.Properties.Version;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
コード例 #2
0
        public async Task <CertificateOperation> GetCertificateOperation(Uri vaultUrl, string certificateName)
        {
            var client = new CertificateClient(vaultUrl, appTokenCredential);
            var op     = await client.GetCertificateOperationAsync(certificateName).ConfigureAwait(false);

            return(op);
        }
コード例 #3
0
        public AzureKeyVaultStore(ManagerConfig config)
        {
            var cred = new DefaultAzureCredential();

            this.certClient   = new CertificateClient(new Uri(config.KeyVaultUrl), cred);
            this.secretClient = new SecretClient(new Uri(config.KeyVaultUrl), cred);
        }
コード例 #4
0
ファイル: Startup.cs プロジェクト: veracity/MDSConnector
        private HttpClient InitiateHttpClientWithCertificate(string keyvaultName, string certificateName)
        {
            var certificateClient             = new CertificateClient(new Uri(keyvaultName), new DefaultAzureCredential());
            var secretClient                  = new SecretClient(new Uri(keyvaultName), new DefaultAzureCredential());
            var keyvaultCertificateWithPolicy = certificateClient.GetCertificate(certificateName);

            Uri    secretId   = keyvaultCertificateWithPolicy.Value.SecretId;
            var    segments   = secretId.Segments;
            string secretName = segments[2].Trim('/');
            string version    = segments[3].TrimEnd('/');

            KeyVaultSecret secret = secretClient.GetSecret(secretName, version);

            byte[] privateKeyBytes = Convert.FromBase64String(secret.Value);
            var    certificate     = new X509Certificate2(privateKeyBytes, "");

            var clientHandler = new HttpClientHandler();

            clientHandler.ServerCertificateCustomValidationCallback =
                (httpRequestMessage, cert, cetChain, policyErrors) =>
            {
                return(true);
            };
            clientHandler.ClientCertificateOptions = ClientCertificateOption.Manual;
            clientHandler.ClientCertificates.Add(certificate);

            return(new HttpClient(clientHandler));
        }
コード例 #5
0
        public AzureCertificateLocator(IOptions <Config> config)
        {
            TokenCredential azureCredentials = new DefaultAzureCredential();

            _certClient   = new CertificateClient(vaultUri: new Uri(config.Value.VaultUri), credential: azureCredentials);
            _secretClient = new SecretClient(vaultUri: new Uri(config.Value.VaultUri), credential: azureCredentials);
        }
コード例 #6
0
 protected CertificatesScenarioBase(T options) : base(options)
 {
     Client = new CertificateClient(
         PerfTestEnvironment.Instance.VaultUri,
         PerfTestEnvironment.Instance.Credential,
         ConfigureClientOptions(new CertificateClientOptions()));
 }
コード例 #7
0
        public void CertificateTest()
        {
            var keyClient = new CertificateClient(new Uri("{{your keyvault uri}}"), new DefaultAzureCredential());
            Response <KeyVaultCertificateWithPolicy> response = keyClient.GetCertificate("SignInCredentialsCert");

            Assert.NotNull(response.Value.Properties.Version);
        }
        /// <summary>
        /// Helper method to get a certificate
        ///
        /// Source https://github.com/heaths/azsdk-sample-getcert/blob/master/Program.cs
        /// </summary>
        /// <param name="certificateClient"></param>
        /// <param name="secretClient"></param>
        /// <param name="certificateName"></param>
        /// <returns></returns>
        private static X509Certificate2 GetCertificateAsync(CertificateClient certificateClient,
                                                            SecretClient secretClient,
                                                            string certificateName)
        {
            KeyVaultCertificateWithPolicy certificate = certificateClient.GetCertificate(certificateName);

            // Return a certificate with only the public key if the private key is not exportable.
            if (certificate.Policy?.Exportable != true)
            {
                return(new X509Certificate2(certificate.Cer));
            }

            // Parse the secret ID and version to retrieve the private key.
            string[] segments = certificate.SecretId.AbsolutePath.Split('/', StringSplitOptions.RemoveEmptyEntries);
            if (segments.Length != 3)
            {
                throw new InvalidOperationException($"Number of segments is incorrect: {segments.Length}, URI: {certificate.SecretId}");
            }

            string secretName    = segments[1];
            string secretVersion = segments[2];

            KeyVaultSecret secret = secretClient.GetSecret(secretName, secretVersion);

            // For PEM, you'll need to extract the base64-encoded message body.
            // .NET 5.0 preview introduces the System.Security.Cryptography.PemEncoding class to make this easier.
            if ("application/x-pkcs12".Equals(secret.Properties.ContentType, StringComparison.InvariantCultureIgnoreCase))
            {
                byte[] pfx = Convert.FromBase64String(secret.Value);
                return(new X509Certificate2(pfx));
            }

            throw new NotSupportedException($"Only PKCS#12 is supported. Found Content-Type: {secret.Properties.ContentType}");
        }
コード例 #9
0
        public async Task <bool> SignAsync(string packagePath,
                                           string outputPath,
                                           string timestampUrl,
                                           HashAlgorithmName signatureHashAlgorithm,
                                           HashAlgorithmName timestampHashAlgorithm,
                                           SignatureType signatureType,
                                           bool overwrite,
                                           Uri v3ServiceIndexUrl,
                                           IReadOnlyList <string> packageOwners,
                                           string keyVaultCertificateName,
                                           Uri keyVaultUrl,
                                           TokenCredential credential,
                                           CancellationToken cancellationToken = default)
        {
            var client = new CertificateClient(keyVaultUrl, credential);
            // We call this here to verify it's a valid cert
            // It also implicitly validates the access token or credentials
            var kvcert = await client.GetCertificateAsync(keyVaultCertificateName, cancellationToken)
                         .ConfigureAwait(false);

            var publicCertificate = new X509Certificate2(kvcert.Value.Cer);


            var rsa = RSAFactory.Create(credential, kvcert.Value.KeyId, publicCertificate);

            return(await SignAsync(packagePath, outputPath, timestampUrl, v3ServiceIndexUrl, packageOwners, signatureType, signatureHashAlgorithm, timestampHashAlgorithm, overwrite, publicCertificate, rsa, cancellationToken));
        }
コード例 #10
0
        private async Task GetCertificateFromKeyVault()
        {
            try
            {
                string clientId     = KeyVaultOptions.Value.ClientId;
                string clientSecret = KeyVaultOptions.Value.ClientSecret;
                string tenantId     = KeyVaultOptions.Value.TenantId;
                Uri    keyVaultUrl  = KeyVaultOptions.Value.KeyVaultUrl;
                string keyName      = KeyVaultOptions.Value.KeyName;

                ClientSecretCredential credential        = new ClientSecretCredential(tenantId, clientId, clientSecret);
                SecretClient           secretClient      = new SecretClient(keyVaultUrl, credential);
                CertificateClient      certificateClient = new CertificateClient(keyVaultUrl, credential);


                KeyVaultSecret keyVaultCertificatePfx = await secretClient.GetSecretAsync(keyName).ConfigureAwait(false);

                KeyVaultCertificate keyVaultCertificateCer = await certificateClient.GetCertificateAsync(keyName).ConfigureAwait(false);

                DecryptionCertificate        = keyVaultCertificatePfx.Value;
                this.EncryptionCertificate   = Convert.ToBase64String(keyVaultCertificateCer.Cer);
                this.EncryptionCertificateId = keyVaultCertificatePfx.Properties.Version;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
コード例 #11
0
        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);
        }
        public byte[] GetCertificateData(string keyVaultUrl, string certificateIdentifier)
        {
            var certificateClient = new CertificateClient(new Uri(keyVaultUrl), defaultAzureCredential);
            KeyVaultCertificateWithPolicy cert = certificateClient.GetCertificate(certificateIdentifier);

            return(cert.Cer);
        }
コード例 #13
0
        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);
        }
コード例 #14
0
        public KeyStore(TokenCredential tokenCredential, string vault)
        {
            var vaultUri = new Uri(vault);

            this._CertificateClient = new CertificateClient(vaultUri, tokenCredential);
            this._SecretClient      = new SecretClient(vaultUri, tokenCredential);
        }
コード例 #15
0
        public static async Task <AzureKeyVaultMaterializedConfiguration> Materialize(AzureKeyVaultSignConfigurationSet configuration, CryptographyClientOptions options = null)
        {
            TokenCredential credential = configuration.ManagedIdentity switch
            {
                true => new DefaultAzureCredential(),
                false => new ClientSecretCredential(configuration.AzureTenantId, configuration.AzureClientId, configuration.AzureClientSecret)
            };

            if (configuration.Mode == KeyVaultMode.Certificate)
            {
                var certificateClient = new CertificateClient(configuration.AzureKeyVaultUrl, credential);
                var cert = await certificateClient.GetCertificateAsync(configuration.AzureKeyVaultKeyName).ConfigureAwait(false);

                var x509Certificate = new X509Certificate2(cert.Value.Cer);
                var keyId           = cert.Value.KeyId;

                return(new AzureKeyVaultMaterializedConfiguration(credential, keyId, publicCertificate: x509Certificate, options: options));
            }
            else if (configuration.Mode == KeyVaultMode.Key)
            {
                var keyClient = new KeyClient(configuration.AzureKeyVaultUrl, credential);
                var key       = await keyClient.GetKeyAsync(configuration.AzureKeyVaultKeyName).ConfigureAwait(false);

                return(new AzureKeyVaultMaterializedConfiguration(credential, key.Value.Id, key.Value.Key, options: options));
            }
            throw new ArgumentOutOfRangeException(nameof(configuration));
        }
    }
コード例 #16
0
        public void HelloWorldSync()
        {
            // Environment variable with the Key Vault endpoint.
            string keyVaultUrl = Environment.GetEnvironmentVariable("AZURE_KEYVAULT_URL");

            // Instantiate a certificate client that will be used to call the service. Notice that the client is using
            // default Azure credentials. To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
            // 'AZURE_CLIENT_KEY' and 'AZURE_TENANT_ID' are set with the service principal credentials.
            var client = new CertificateClient(new Uri(keyVaultUrl), new DefaultAzureCredential());

            // Let's create a self signed certifiate using the default policy. If the certificiate
            // already exists in the Key Vault, then a new version of the key is created.
            string certName = $"defaultCert-{Guid.NewGuid()}";

            CertificateOperation certOp = client.StartCreateCertificate(certName);

            // Next let's wait on the certificate operation to complete. Note that certificate creation can last an indeterministic
            // amount of time, so applications should only wait on the operation to complete in the case the issuance time is well
            // known and within the scope of the application lifetime. In this case we are creating a self-signed certificate which
            // should be issued in a relatively short amount of time.
            while (!certOp.HasCompleted)
            {
                certOp.UpdateStatus();

                Thread.Sleep(certOp.PollingInterval);
            }

            // Let's get the created certificate along with it's policy from the Key Vault.
            CertificateWithPolicy certificate = client.GetCertificateWithPolicy(certName);

            Debug.WriteLine($"Certificate was returned with name {certificate.Name} which expires {certificate.Properties.Expires}");

            // We find that the certificate has been compromised and we want to disable it so applications will no longer be able
            // to access the compromised version of the certificate.
            Certificate updatedCert = client.UpdateCertificate(certName, certificate.Version, enabled: false);

            Debug.WriteLine($"Certificate enabled set to '{updatedCert.Properties.Enabled}'");

            // We need to create a new version of the certificate that applications can use to replace the compromised certificate.
            // Creating a certificate with the same name and policy as the compromised certificate will create another version of the
            // certificate with similar properties to the original certificate
            CertificateOperation newCertOp = client.StartCreateCertificate(certificate.Name, certificate.Policy);

            while (!newCertOp.HasCompleted)
            {
                newCertOp.UpdateStatus();

                Thread.Sleep(newCertOp.PollingInterval);
            }

            // The certificate is no longer needed, need to delete it from the Key Vault.
            client.DeleteCertificate(certName);

            // To ensure certificate is deleted on server side.
            Assert.IsTrue(WaitForDeletedCertificate(client, certName));

            // If the keyvault is soft-delete enabled, then for permanent deletion, deleted certificate needs to be purged.
            client.PurgeDeletedCertificate(certName);
        }
コード例 #17
0
        /// <summary>
        /// Initializes a new instance of the type
        /// </summary>
        /// <param name="keyVault">The key vault URI</param>
        /// <param name="credential">Oauth token credentials</param>
        /// <param name="options">The options used to access the certificates</param>
        public KeyVaultCertificates(Uri keyVault, TokenCredential credential, CertificateClientOptions options)
        {
            Guard.NotNull(nameof(credential), credential);
            Guard.NotNull(nameof(options), options);
            Guard.NotNull(nameof(keyVault), keyVault);

            Client = new CertificateClient(keyVault, credential, options);
        }
コード例 #18
0
        private void InitializeClients(string keyVaultName)
        {
            var keyVaultUri = new Uri(string.Format(keyVaultBaseUri, keyVaultName));

            SecretClient      = new SecretClient(keyVaultUri, keyVaultCredential);
            KeyClient         = new KeyClient(keyVaultUri, keyVaultCredential);
            CertificateClient = new CertificateClient(keyVaultUri, keyVaultCredential);
        }
コード例 #19
0
    private static async Task <int> RunAsync(
        Uri vaultUri,
        string certificateName,
        string message,
        IConsole console)
    {
        CancellationToken cancellationToken = s_cancellationTokenSource.Token;

        // Allow only credentials appropriate for this interactive tool sample.
        DefaultAzureCredential credential = new DefaultAzureCredential(
            new DefaultAzureCredentialOptions
        {
            ExcludeEnvironmentCredential     = true,
            ExcludeManagedIdentityCredential = true,
        });

        // Get the certificate to use for encrypting and decrypting.
        CertificateClient             certificateClient = new CertificateClient(vaultUri, credential);
        KeyVaultCertificateWithPolicy certificate       = await certificateClient.GetCertificateAsync(certificateName, cancellationToken : cancellationToken);

        // Make sure the private key is exportable.
        if (certificate.Policy?.Exportable != true)
        {
            console.Error.WriteLine($@"Error: certificate ""{certificateName}"" is not exportable.");
            return(1);
        }
        else if (certificate.Policy?.KeyType != CertificateKeyType.Rsa)
        {
            console.Error.WriteLine($@"Error: certificate type ""{certificate.Policy?.KeyType}"" cannot be used to locally encrypt and decrypt.");
            return(1);
        }

        // Get the managed secret which contains the public and private key (if exportable).
        string secretName = ParseSecretName(certificate.SecretId);

        SecretClient   secretClient = new SecretClient(vaultUri, credential);
        KeyVaultSecret secret       = await secretClient.GetSecretAsync(secretName, cancellationToken : cancellationToken);

        // Get a certificate pair from the secret value.
        X509Certificate2 pfx = ParseCertificate(secret);

        // Decode and encrypt the message.
        byte[] plaintext = Encoding.UTF8.GetBytes(message);

        using RSA encryptor = (RSA)pfx.PublicKey.Key;
        byte[] ciphertext = encryptor.Encrypt(plaintext, RSAEncryptionPadding.OaepSHA256);

        console.Out.WriteLine($"Encrypted message: {Convert.ToBase64String(ciphertext)}");

        // Decrypt and encode the message.
        using RSA decryptor = (RSA)pfx.PrivateKey;
        plaintext           = decryptor.Decrypt(ciphertext, RSAEncryptionPadding.OaepSHA256);

        message = Encoding.UTF8.GetString(plaintext);
        console.Out.WriteLine($"Decrypted message: {message}");

        return(0);
    }
コード例 #20
0
        public void HelloWorldSync(string keyVaultUrl)
        {
            #region Snippet:CertificatesSample1CertificateClient
            var client = new CertificateClient(new Uri(keyVaultUrl), new DefaultAzureCredential());
            #endregion

            #region Snippet:CertificatesSample1CreateCertificate
            string certName             = $"defaultCert-{Guid.NewGuid()}";
            CertificateOperation certOp = client.StartCreateCertificate(certName, CertificatePolicy.Default);

            while (!certOp.HasCompleted)
            {
                certOp.UpdateStatus();

                Thread.Sleep(TimeSpan.FromSeconds(1));
            }
            #endregion

            #region Snippet:CertificatesSample1GetCertificateWithPolicy
            KeyVaultCertificateWithPolicy certificate = client.GetCertificate(certName);

            Debug.WriteLine($"Certificate was returned with name {certificate.Name} which expires {certificate.Properties.ExpiresOn}");
            #endregion

            #region Snippet:CertificatesSample1UpdateCertificate
            CertificateProperties certificateProperties = certificate.Properties;
            certificateProperties.Enabled = false;

            KeyVaultCertificate updatedCert = client.UpdateCertificateProperties(certificateProperties);
            Debug.WriteLine($"Certificate enabled set to '{updatedCert.Properties.Enabled}'");
            #endregion

            #region Snippet:CertificatesSample1CreateCertificateWithNewVersion
            CertificateOperation newCertOp = client.StartCreateCertificate(certificate.Name, certificate.Policy);

            while (!newCertOp.HasCompleted)
            {
                newCertOp.UpdateStatus();

                Thread.Sleep(TimeSpan.FromSeconds(1));
            }
            #endregion

            #region Snippet:CertificatesSample1DeleteCertificate
            DeleteCertificateOperation operation = client.StartDeleteCertificate(certName);

            // To ensure certificate is deleted on server side.
            while (!operation.HasCompleted)
            {
                Thread.Sleep(2000);

                operation.UpdateStatus();
            }
            #endregion

            // If the keyvault is soft-delete enabled, then for permanent deletion, the deleted certificate needs to be purged.
            client.PurgeDeletedCertificate(certName);
        }
コード例 #21
0
 public AzureKeyVaultCertificateRepository(
     CertificateClient client,
     IOptions <LetsEncryptOptions> encryptOptions,
     ILogger <AzureKeyVaultCertificateRepository> logger)
 {
     _client         = client ?? throw new ArgumentNullException(nameof(client));
     _encryptOptions = encryptOptions ?? throw new ArgumentNullException(nameof(encryptOptions));
     _logger         = logger ?? throw new ArgumentNullException(nameof(logger));
 }
コード例 #22
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SecretsProvider"/> class.
 /// </summary>
 /// <param name="appSettings">App settings.</param>
 /// <param name="certificateClient">Certificate client.</param>
 /// <param name="logger">Logger.</param>
 public SecretsProvider(
     IAppSettings appSettings,
     CertificateClient certificateClient,
     ILogger <SecretsProvider> logger)
 {
     this.appSettings       = appSettings ?? throw new ArgumentNullException(nameof(appSettings));
     this.certificateClient = certificateClient ?? throw new ArgumentNullException(nameof(certificateClient));
     this.logger            = logger ?? throw new ArgumentNullException(nameof(logger));
 }
コード例 #23
0
 /// <summary>
 /// Initializes a new instance.
 /// </summary>
 /// <param name="certificateClient"></param>
 /// <param name="secretClient"></param>
 /// <param name="logger"></param>
 /// <param name="cache"></param>
 public KeyVaultX509Certificate2Provider(CertificateClient certificateClient, SecretClient secretClient, ILogger <KeyVaultX509Certificate2Provider> logger, IMemoryCache cache = null)
 {
     this.certificateClient = certificateClient ?? throw new ArgumentNullException(nameof(certificateClient));
     this.secretClient      = secretClient ?? throw new ArgumentNullException(nameof(secretClient));
     this.logger            = logger ?? throw new ArgumentNullException(nameof(logger));
     this.cache             = cache ?? new MemoryCache(new MemoryCacheOptions()
     {
     });
 }
コード例 #24
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);
        }
コード例 #25
0
        public void RetrieveCertificate(object o)
        {
            CertificateRegistration certReg = (CertificateRegistration)o;

            try
            {
                CertificateClient certificateClient = new CertificateClient();


                Assembly asm = Assembly.GetEntryAssembly();
                certificateClient.ProgramName    = asm.GetName().Name;
                certificateClient.ProgramVersion = AssemblyHelper.GetVersionString(asm);

                certificateClient.CertificateAuthorizationRequired += new EventHandler <EventArgs>(delegate
                {
                    this.LogMessage(Properties.Resources.Certificate_authorization_required, true);
                });

                certificateClient.EmailVerificationRequired += new EventHandler <EventArgs>(delegate
                {
                    this.LogMessage(Properties.Resources.GetNewCertificate_RetrieveCertificate_);
                    this.Dispatcher.Invoke(DispatcherPriority.Normal, (SendOrPostCallback) delegate
                    {
                        this.UsernameField.Text     = "";
                        this.EmailField.Text        = "";
                        this.PasswordField.Password = "";
                        this.ConfirmField.Password  = "";
                    }, null);
                });

                certificateClient.CertificateReceived += CertificateReceived;

                certificateClient.InvalidCertificateRegistration += InvalidCertificateRegistration;

                certificateClient.ServerErrorOccurred += ServerErrorOccured;

                certificateClient.NewProtocolVersion += new EventHandler <EventArgs>(delegate
                {
                    this.LogMessage(Properties.Resources.New_ProtocolVersion__Please_update_CrypTool_2_0, true);
                });

                certificateClient.RegisterCertificate(certReg);
            }
            catch (NetworkException nex)
            {
                this.LogMessage(String.Format(Properties.Resources.There_was_a_communication_problem_with_the_server, nex.Message), true);
            }
            catch (Exception ex)
            {
                this.LogMessage(String.Format(Properties.Resources.An_exception_occured___1, ex.Message), true);
            }
            finally
            {
                Requesting = false;
            }
        }
コード例 #26
0
        public void SetUp()
        {
            var hostname = Environment.GetEnvironmentVariable("keyvaultHostname");

            _client = new CertificateClient(new Uri(hostname ?? throw new ArgumentException()), new DefaultAzureCredential());

            _client.StartCreateCertificate(CertificateName, CertificatePolicy.Default, true);

            _retriever = new KeyVaultCertificateRetriever(_client);
        }
        private CertificateClient CreateCertificateClient()
        {
            if (!_certificateClientsHolder.TryGetValue(_keyVaultUri, out var client))
            {
                client = new CertificateClient(_keyVaultUri, _azureCredential);
                _certificateClientsHolder.TryAdd(_keyVaultUri, client);
            }

            return(client);
        }
コード例 #28
0
        public async Task <DeleteCertificateOperation> CancelCsrAsync(string vaultName, string certificateName)
        {
            var vault = await GetVaultAsync(vaultName).ConfigureAwait(false);

            var client = new CertificateClient(vault.VaultUri, appTokenCredential);

            var op = await client.StartDeleteCertificateAsync(certificateName);

            return(op);
        }
コード例 #29
0
        public async Task HelloWorldAsync()
        {
            // Environment variable with the Key Vault endpoint.
            string keyVaultUrl = TestEnvironment.KeyVaultUrl;

            // Instantiate a certificate client that will be used to call the service. Notice that the client is using
            // default Azure credentials. To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
            // 'AZURE_CLIENT_KEY' and 'AZURE_TENANT_ID' are set with the service principal credentials.
            CertificateClient client = new CertificateClient(new Uri(keyVaultUrl), new DefaultAzureCredential());

            // Let's create a self-signed certificate using the default policy. If the certificate
            // already exists in the Key Vault, then a new version of the key is created.
            string certName = $"defaultCert-{Guid.NewGuid()}";

            CertificateOperation certOp = await client.StartCreateCertificateAsync(certName, CertificatePolicy.Default);

            // Next, let's wait on the certificate operation to complete. Note that certificate creation can last an indeterministic
            // amount of time, so applications should only wait on the operation to complete in the case the issuance time is well
            // known and within the scope of the application lifetime. In this case we are creating a self-signed certificate which
            // should be issued in a relatively short amount of time.
            Response <KeyVaultCertificateWithPolicy> certificateResponse = await certOp.WaitForCompletionAsync();

            KeyVaultCertificateWithPolicy certificate = certificateResponse.Value;

            // At some time later we could get the created certificate along with its policy from the Key Vault.
            certificate = await client.GetCertificateAsync(certName);

            Debug.WriteLine($"Certificate was returned with name {certificate.Name} which expires {certificate.Properties.ExpiresOn}");

            // We find that the certificate has been compromised and we want to disable it so applications will no longer be able
            // to access the compromised version of the certificate.
            CertificateProperties certificateProperties = certificate.Properties;

            certificateProperties.Enabled = false;

            Response <KeyVaultCertificate> updatedCertResponse = await client.UpdateCertificatePropertiesAsync(certificateProperties);

            Debug.WriteLine($"Certificate enabled set to '{updatedCertResponse.Value.Properties.Enabled}'");

            // We need to create a new version of the certificate that applications can use to replace the compromised certificate.
            // Creating a certificate with the same name and policy as the compromised certificate will create another version of the
            // certificate with similar properties to the original certificate
            CertificateOperation newCertOp = await client.StartCreateCertificateAsync(certificate.Name, certificate.Policy);

            KeyVaultCertificateWithPolicy newCert = await newCertOp.WaitForCompletionAsync();

            // The certificate is no longer needed, need to delete it from the Key Vault.
            DeleteCertificateOperation operation = await client.StartDeleteCertificateAsync(certName);

            // You only need to wait for completion if you want to purge or recover the certificate.
            await operation.WaitForCompletionAsync();

            // If the keyvault is soft-delete enabled, then for permanent deletion, the deleted key needs to be purged.
            await client.PurgeDeletedCertificateAsync(certName);
        }
コード例 #30
0
 public SharedFunctions(LookupClient lookupClient, IAcmeProtocolClientFactory acmeProtocolClientFactory,
                        IDnsProvider dnsProvider, CertificateClient certificateClient,
                        WebhookClient webhookClient, IOptions <AcmebotOptions> options)
 {
     _acmeProtocolClientFactory = acmeProtocolClientFactory;
     _dnsProvider       = dnsProvider;
     _lookupClient      = lookupClient;
     _certificateClient = certificateClient;
     _webhookClient     = webhookClient;
     _options           = options.Value;
 }