protected async Task <KeyVaultCertificateWithPolicy> WaitForCompletion(CertificateOperation operation)
        {
            using CancellationTokenSource cts = new CancellationTokenSource(TimeSpan.FromMinutes(1));
            TimeSpan pollingInterval = TimeSpan.FromSeconds((Mode == RecordedTestMode.Playback) ? 0 : 1);

            try
            {
                if (IsAsync)
                {
                    await operation.WaitForCompletionAsync(pollingInterval, cts.Token);
                }
                else
                {
                    while (!operation.HasCompleted)
                    {
                        operation.UpdateStatus(cts.Token);

                        await Task.Delay(pollingInterval, cts.Token);
                    }
                }
            }
            catch (TaskCanceledException)
            {
                Assert.Inconclusive("Timed out while waiting for operation {0}", operation.Id);
            }

            return(operation.Value);
        }
        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);
        }
Exemple #3
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);
        }
Exemple #4
0
        public void CreateCertificate()
        {
            #region Snippet:CreateCertificate
            // Create a certificate. This starts a long running operation to create and sign the certificate.
            CertificateOperation operation = client.StartCreateCertificate("MyCertificate", CertificatePolicy.Default);

            // You can await the completion of the create certificate operation.
            // You should run UpdateStatus in another thread or do other work like pumping messages between calls.
            while (!operation.HasCompleted)
            {
                Thread.Sleep(2000);

                operation.UpdateStatus();
            }

            KeyVaultCertificateWithPolicy certificate = operation.Value;
            #endregion
        }
Exemple #5
0
        protected async Task <CertificateWithPolicy> WaitForCompletion(CertificateOperation operation)
        {
            operation.PollingInterval = TimeSpan.FromSeconds((Mode == RecordedTestMode.Playback) ? 0 : 1);

            if (IsAsync)
            {
                await operation.WaitCompletionAsync();
            }
            else
            {
                while (!operation.HasValue)
                {
                    operation.UpdateStatus();

                    await Task.Delay(operation.PollingInterval);
                }
            }

            return(operation.Value);
        }
        private async ValueTask <KeyVaultCertificateWithPolicy> WaitForOperationAsync(CertificateOperation operation)
        {
            var rand = new Random();

            TimeSpan PollingInterval() => TimeSpan.FromMilliseconds(rand.Next(1, 50));

            if (IsAsync)
            {
                return(await operation.WaitForCompletionAsync(PollingInterval(), default));
            }
            else
            {
                while (!operation.HasCompleted)
                {
                    operation.UpdateStatus();
                    await Task.Delay(PollingInterval());
                }

                return(operation.Value);
            }
        }
Exemple #7
0
        public void GetCertificatesSync()
        {
            // 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 two self-signed certificates using the default policy
            string certName1 = $"defaultCert-{Guid.NewGuid()}";

            CertificateOperation certOp1 = client.StartCreateCertificate(certName1);

            string certName2 = $"defaultCert-{Guid.NewGuid()}";

            CertificateOperation certOp2 = client.StartCreateCertificate(certName1);

            // 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 (!certOp1.HasCompleted)
            {
                certOp1.UpdateStatus();

                Thread.Sleep(certOp1.PollingInterval);
            }

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

                Thread.Sleep(certOp2.PollingInterval);
            }

            // Let's list the certificates which exist in the vault along with their thumbprints
            foreach (CertificateBase cert in client.GetCertificates())
            {
                Debug.WriteLine($"Certificate is returned with name {cert.Name} and thumbprint {BitConverter.ToString(cert.X509Thumbprint)}");
            }

            // We need to create a new version of a certificate. Creating a certificate with the same name will create another version of the certificate
            CertificateOperation newCertOp = client.StartCreateCertificate(certName1);

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

                Thread.Sleep(newCertOp.PollingInterval);
            }

            // Let's print all the versions of this certificate
            foreach (CertificateBase cert in client.GetCertificateVersions(certName1))
            {
                Debug.WriteLine($"Certificate {cert.Name} with name {cert.Version}");
            }

            // The certificates are no longer needed.
            // You need to delete them from the Key Vault.
            client.DeleteCertificate(certName1);
            client.DeleteCertificate(certName2);

            // To ensure certificates are deleted on server side.
            Assert.IsTrue(WaitForDeletedCertificate(client, certName1));
            Assert.IsTrue(WaitForDeletedCertificate(client, certName2));

            // You can list all the deleted and non-purged certificates, assuming Key Vault is soft-delete enabled.
            foreach (DeletedCertificate deletedCert in client.GetDeletedCertificates())
            {
                Debug.WriteLine($"Deleted certificate's recovery Id {deletedCert.RecoveryId}");
            }

            // If the keyvault is soft-delete enabled, then for permanent deletion, deleted keys needs to be purged.
            client.PurgeDeletedCertificate(certName1);
            client.PurgeDeletedCertificate(certName2);
        }
Exemple #8
0
        public void DownloadCertificateSync()
        {
            // Environment variable with the Key Vault endpoint.
            string keyVaultUrl = TestEnvironment.KeyVaultUrl;

            #region Snippet:CertificatesSample4CertificateClient
            CertificateClient client = new CertificateClient(new Uri(keyVaultUrl), new DefaultAzureCredential());
            #endregion

            string certificateName         = $"rsa-{Guid.NewGuid()}";
            CertificateOperation operation = client.StartCreateCertificate(certificateName, CertificatePolicy.Default);

            while (!operation.HasCompleted)
            {
                operation.UpdateStatus();
                Thread.Sleep(TimeSpan.FromSeconds(10));
            }

            using SHA256 sha = SHA256.Create();
            byte[] data = Encoding.UTF8.GetBytes("test");
            byte[] hash = sha.ComputeHash(data);

            #region Snippet:CertificatesSample4DownloadCertificate
            X509KeyStorageFlags keyStorageFlags = X509KeyStorageFlags.MachineKeySet;
            if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                keyStorageFlags |= X509KeyStorageFlags.EphemeralKeySet;
            }

            DownloadCertificateOptions options = new DownloadCertificateOptions(certificateName)
            {
                KeyStorageFlags = keyStorageFlags
            };

            using X509Certificate2 certificate = client.DownloadCertificate(options);
            using RSA key = certificate.GetRSAPrivateKey();

            byte[] signature = key.SignHash(hash, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
            Debug.WriteLine($"Signature: {Convert.ToBase64String(signature)}");
            #endregion

            #region Snippet:CertificatesSample4PublicKey
            Response <KeyVaultCertificateWithPolicy> certificateResponse = client.GetCertificate(certificateName);
            using X509Certificate2 publicCertificate = new X509Certificate2(certificateResponse.Value.Cer);
            using RSA publicKey = publicCertificate.GetRSAPublicKey();

            bool verified = publicKey.VerifyHash(hash, signature, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
            Debug.WriteLine($"Signature verified: {verified}");
            #endregion

            Assert.IsTrue(verified);

            DeleteCertificateOperation deleteOperation = client.StartDeleteCertificate(certificateName);
            while (!deleteOperation.HasCompleted)
            {
                deleteOperation.UpdateStatus();
                Thread.Sleep(TimeSpan.FromSeconds(2));
            }

            client.PurgeDeletedCertificate(certificateName);
        }
        public void GetCertificatesSync()
        {
            // Environment variable with the Key Vault endpoint.
            string keyVaultUrl = TestEnvironment.KeyVaultUrl;

            #region Snippet:CertificatesSample2CertificateClient
            CertificateClient client = new CertificateClient(new Uri(keyVaultUrl), new DefaultAzureCredential());
            #endregion

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

            string certName2             = $"defaultCert-{Guid.NewGuid()}";
            CertificateOperation certOp2 = client.StartCreateCertificate(certName2, CertificatePolicy.Default);

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

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

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

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

            #region Snippet:CertificatesSample2ListCertificates
            foreach (CertificateProperties cert in client.GetPropertiesOfCertificates())
            {
                Debug.WriteLine($"Certificate is returned with name {cert.Name} and thumbprint {BitConverter.ToString(cert.X509Thumbprint)}");
            }
            #endregion

            #region Snippet:CertificatesSample2CreateCertificateWithNewVersion
            CertificateOperation newCertOp = client.StartCreateCertificate(certName1, CertificatePolicy.Default);

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

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

            #region Snippet:CertificatesSample2ListCertificateVersions
            foreach (CertificateProperties cert in client.GetPropertiesOfCertificateVersions(certName1))
            {
                Debug.WriteLine($"Certificate {cert.Name} with name {cert.Version}");
            }
            #endregion

            #region Snippet:CertificatesSample2DeleteCertificates
            DeleteCertificateOperation operation1 = client.StartDeleteCertificate(certName1);
            DeleteCertificateOperation operation2 = client.StartDeleteCertificate(certName2);

            // To ensure certificates are deleted on server side.
            // You only need to wait for completion if you want to purge or recover the certificate.
            while (!operation1.HasCompleted || !operation2.HasCompleted)
            {
                Thread.Sleep(2000);

                operation1.UpdateStatus();
                operation2.UpdateStatus();
            }
            #endregion

            #region Snippet:CertificatesSample2ListDeletedCertificates
            foreach (DeletedCertificate deletedCert in client.GetDeletedCertificates())
            {
                Debug.WriteLine($"Deleted certificate's recovery Id {deletedCert.RecoveryId}");
            }
            #endregion

            // If the keyvault is soft-delete enabled, then for permanent deletion, deleted keys needs to be purged.
            client.PurgeDeletedCertificate(certName1);
            client.PurgeDeletedCertificate(certName2);
        }
        public void HelloWorldSync()
        {
            // Environment variable with the Key Vault endpoint.
            string keyVaultUrl = TestEnvironment.KeyVaultUrl;

            #region Snippet:CertificatesSample1CertificateClient
            CertificateClient 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
            Response <KeyVaultCertificateWithPolicy> certificateResponse = client.GetCertificate(certName);
            KeyVaultCertificateWithPolicy            certificate         = certificateResponse.Value;

            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;

            Response <KeyVaultCertificate> updatedCertResponse = client.UpdateCertificateProperties(certificateProperties);
            Debug.WriteLine($"Certificate enabled set to '{updatedCertResponse.Value.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);

            // You only need to wait for completion if you want to purge or recover the certificate.
            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);
        }