Ejemplo n.º 1
0
        public void RetrieveCertificate()
        {
            #region Snippet:RetrieveCertificate
            KeyVaultCertificateWithPolicy certificateWithPolicy = client.GetCertificate("MyCertificate");
            #endregion

            #region Snippet:GetCertificate
            KeyVaultCertificate certificate = client.GetCertificateVersion(certificateWithPolicy.Name, certificateWithPolicy.Properties.Version);
            #endregion
        }
        /// <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}");
        }
Ejemplo n.º 3
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);
        }
        public byte[] GetCertificateData(string keyVaultUrl, string certificateIdentifier)
        {
            var certificateClient = new CertificateClient(new Uri(keyVaultUrl), defaultAzureCredential);
            KeyVaultCertificateWithPolicy cert = certificateClient.GetCertificate(certificateIdentifier);

            return(cert.Cer);
        }
Ejemplo n.º 5
0
        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));
        }
Ejemplo n.º 6
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);
        }
        public void Add_AddsCertificate()
        {
            _adder.Add(CertificateName);

            var certificate = _client.GetCertificate(CertificateName).Value;

            certificate.Should().NotBeNull();
            certificate.Name.Should().Be(CertificateName);
        }
Ejemplo n.º 8
0
        //
        // execute GetCertificate
        //

        public string Execute(string certificateIdentifierUrl, string filePath = null, string identity = null)
        {
            (Uri keyVaultUri, string certificateName, string certificateVersion) = ValidateAndParseCertificateURL(certificateIdentifierUrl);

            var MIcredential      = new ManagedIdentityCredential(identity);
            var certificateClient = new CertificateClient(keyVaultUri, MIcredential);

            // Retrieve a certificate (certificate = certificate and private key bundle in Azure terminology)
            // PEM (Privacy Enhanced Mail) or PFX (Personal Information Exchange; PKCS#12 archive file format) formats
            // depends on what content type you set in Azure Key Vault at respective certificate.
            // Both formats usually contain a certificate (possibly with its assorted set of CA certificates) and the corresponding private key

            // Download CER format (X.509 certificate)
            // single certificate, alone and without any wrapping (no private key, no password protection, just the certificate)
            // not supported
            try
            {
                // certificate (and key) is stored as a secret at the end in Azure
                string secretIdentifierUrl;
                if (String.IsNullOrEmpty(certificateVersion))
                {
                    // certificate has no specific version:
                    // https://my-key-vault.vault.azure.net/certificates/readThisCertificate
                    KeyVaultCertificateWithPolicy certificateWithPolicy = certificateClient.GetCertificate(certificateName);
                    secretIdentifierUrl = certificateWithPolicy.SecretId.ToString();
                }
                else
                {
                    // certificate has specific version:
                    // https://my-key-vault.vault.azure.net/certificates/readThisCertificate/103a7355c6094bc78307b2db7b85b3c2
                    KeyVaultCertificate certificate = certificateClient.GetCertificateVersion(certificateName, certificateVersion);
                    secretIdentifierUrl = certificate.SecretId.ToString();
                }

                // filePath: null means get secret into variable only
                // otherwise secret may be unintentionally saved to file by GetSecret() method
                string secret = new GetSecret().Execute(secretIdentifierUrl, filePath: null, identity);

                if (String.IsNullOrEmpty(filePath))
                {   // print to stdout
                    return(secret);
                }
                else
                {   // creates or overwrites file and saves secret into it
                    File.WriteAllText(filePath, secret);
                    return("Saved");
                }
            }
            catch (Exception ex)
            {
                throw AzmiException.IDCheck(identity, ex);
            }
        }
        /// <summary>
        /// Load a certificate from Key Vault, including the private key.
        /// </summary>
        /// <param name="keyVaultUrl">URL of Key Vault.</param>
        /// <param name="certificateName">Name of the certificate.</param>
        /// <param name="x509KeyStorageFlags">Defines where and how to import the private key of an X.509 certificate.</param>
        /// <returns>An <see cref="X509Certificate2"/> certificate.</returns>
        /// <remarks>This code is inspired by Heath Stewart's code in:
        /// https://github.com/heaths/azsdk-sample-getcert/blob/master/Program.cs#L46-L82.
        /// </remarks>
        private static X509Certificate2 LoadFromKeyVault(
            string keyVaultUrl,
            string certificateName,
            X509KeyStorageFlags x509KeyStorageFlags)
        {
            Uri keyVaultUri = new Uri(keyVaultUrl);
            DefaultAzureCredentialOptions options = new DefaultAzureCredentialOptions();

            options.ManagedIdentityClientId = UserAssignedManagedIdentityClientId;
            DefaultAzureCredential credential        = new DefaultAzureCredential(options);
            CertificateClient      certificateClient = new CertificateClient(keyVaultUri, credential);
            SecretClient           secretClient      = new SecretClient(keyVaultUri, credential);

            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,
                           (string?)null,
                           x509KeyStorageFlags));
            }

            // Parse the secret ID and version to retrieve the private key.
            string[] segments = certificate.SecretId.AbsolutePath.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            if (segments.Length != 3)
            {
                throw new InvalidOperationException(string.Format(
                                                        CultureInfo.InvariantCulture,
                                                        IDWebErrorMessage.IncorrectNumberOfUriSegments,
                                                        segments.Length,
                                                        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 (Constants.MediaTypePksc12.Equals(secret.Properties.ContentType, StringComparison.InvariantCultureIgnoreCase))
            {
                return(LoadFromBase64Encoded(secret.Value, x509KeyStorageFlags));
            }

            throw new NotSupportedException(
                      string.Format(
                          CultureInfo.InvariantCulture,
                          IDWebErrorMessage.OnlyPkcs12IsSupported,
                          secret.Properties.ContentType));
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Reads the signing certificate from a location.
        /// Supported locations: Blob storage, File, Local, KeyVault.
        /// </summary>
        /// <param name="certificate"></param>
        /// <param name="location"></param>
        /// <param name="log"></param>
        /// <returns>x509 certificate without private key</returns>
        private static X509Certificate ReadCertificate(string certificate, Location location, ILogger log)
        {
            log.LogInformation($"Reading certificate from {location}...");

            X509Certificate x509 = null;

            try
            {
                if (location == Location.File)
                {
                    x509 = DotNetUtilities.FromX509Certificate(
                        System.Security.Cryptography.X509Certificates.X509Certificate.CreateFromCertFile(certificate));
                }

                if (location == Location.Local)
                {
                    using (TextReader reader = new StringReader(certificate))
                    {
                        Org.BouncyCastle.OpenSsl.PemReader pemReader = new Org.BouncyCastle.OpenSsl.PemReader(reader);
                        x509 = (X509Certificate)pemReader.ReadObject();
                    };
                }

                if (location == Location.Blob)
                {
                    blobClient = new BlobClient(blobConnectionString, blobContainerName, certificate);
                    BlobDownloadInfo download = blobClient.Download();
                    using (TextReader reader = new StreamReader(download.Content))
                    {
                        Org.BouncyCastle.OpenSsl.PemReader pemReader = new Org.BouncyCastle.OpenSsl.PemReader(reader);
                        x509 = (X509Certificate)pemReader.ReadObject();
                    };
                }

                if (location == Location.KeyVault)
                {
                    var client = new CertificateClient(new Uri($"https://{keyVaultName}.vault.azure.net"), new DefaultAzureCredential());
                    keyVaultCertificate = client.GetCertificate(certificate);
                    x509 = new Org.BouncyCastle.X509.X509CertificateParser().ReadCertificate(keyVaultCertificate.Cer);
                }
            }
            catch (Exception ex)
            {
                log.LogError(ex.Message);
            }

            log.LogInformation($"Finished reading certificate {x509.SubjectDN} from {location}.");

            return(x509);
        }
Ejemplo n.º 11
0
        //
        //
        //  **** Cmdlet start ****
        //
        //


        protected override void ProcessRecord()
        {
            var cred = new ManagedIdentityCredential(Identity);

            WriteVerbose($"Parsing certificate... '{Certificate}'");
            (Uri keyVault, string certName, string certVersion) = Shared.ParseUrl(Certificate);

            WriteVerbose($"Obtaining certificate client for '{keyVault}' using '{Identity}'...");
            var certificateClient = new CertificateClient(keyVault, cred);

            KeyVaultCertificate certObj;

            WriteVerbose($"Obtaining certificate Id {certName}...");
            if (String.IsNullOrEmpty(certVersion))
            {
                certObj = certificateClient.GetCertificate(certName);
            }
            else
            {
                certObj = certificateClient.GetCertificateVersion(certName, certVersion);
            }
            var secretId = certObj.SecretId.ToString();

            WriteVerbose($"Obtaining certificate from {secretId}...");
            // var gs = new GetSecret() { Secret = secretId, Identity = Identity };
            // var cert = (string)gs.Invoke();
            // currently throws InvalidCastException
            //   Unable to cast object of type '<Invoke>d__40' to type 'System.String'.
            // string cert = System.Text.Encoding.UTF32.GetString(certObj.Cer);
            string cert = Convert.ToBase64String(certObj.Cer);

            // return value
            if (String.IsNullOrEmpty(File))
            {
                WriteObject(cert);
            }
            else
            {
                WriteVerbose($"Saving secret to file {File}...");
                System.IO.File.WriteAllText(File, cert);
                // TODO: Add test for file in current dir
                // TODO: Candidate for async
            }
        }
Ejemplo n.º 12
0
        public void CreateClient()
        {
            // Environment variable with the Key Vault endpoint.
            string keyVaultUrl = Environment.GetEnvironmentVariable("AZURE_KEYVAULT_URL");

            #region Snippet:CreateCertificateClient
            // Create a new certificate client using the default credential from Azure.Identity using environment variables previously set,
            // including AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, and AZURE_TENANT_ID.
            var client = new CertificateClient(vaultUri: new Uri(keyVaultUrl), credential: new DefaultAzureCredential());

            // Create a certificate using the certificate client.
            CertificateOperation operation = client.StartCreateCertificate("MyCertificate", CertificatePolicy.Default);

            // Retrieve a certificate using the certificate client.
            KeyVaultCertificateWithPolicy certificate = client.GetCertificate("MyCertificate");
            #endregion

            this.client = client;
        }
        public Saml2Configuration GetSaml2Configuration()
        {
            var saml2Configuration = new Saml2Configuration
            {
                Issuer                    = config.Issuer,
                SignatureAlgorithm        = config.SignatureAlgorithm,
                CertificateValidationMode = config.CertificateValidationMode,
                RevocationMode            = config.RevocationMode
            };

            var certificateClient     = new CertificateClient(new Uri(AzureKeyVaultBaseUrl), tokenCredential);
            var certificateWithPolicy = certificateClient.GetCertificate(AzureKeyVaultCertificateName);

            var publicCertificate = new X509Certificate2(certificateWithPolicy.Value.Cer);
            var rsa = RSAFactory.Create(tokenCredential, certificateWithPolicy.Value.KeyId, new Azure.Security.KeyVault.Keys.JsonWebKey(publicCertificate.GetRSAPublicKey()));

            saml2Configuration.SigningCertificate = new Saml2X509Certificate(publicCertificate, rsa);

            //saml2Configuration.SignAuthnRequest = true;

            saml2Configuration.AllowedAudienceUris.Add(saml2Configuration.Issuer);

            var entityDescriptor = new EntityDescriptor();

            entityDescriptor.ReadIdPSsoDescriptorFromUrl(new Uri(Saml2IdPMetadata));
            if (entityDescriptor.IdPSsoDescriptor != null)
            {
                saml2Configuration.AllowedIssuer           = entityDescriptor.EntityId;
                saml2Configuration.SingleSignOnDestination = entityDescriptor.IdPSsoDescriptor.SingleSignOnServices.First().Location;
                saml2Configuration.SingleLogoutDestination = entityDescriptor.IdPSsoDescriptor.SingleLogoutServices.First().Location;
                saml2Configuration.SignatureValidationCertificates.AddRange(entityDescriptor.IdPSsoDescriptor.SigningCertificates);
            }
            else
            {
                throw new Exception("IdPSsoDescriptor not loaded from metadata.");
            }

            return(saml2Configuration);
        }
Ejemplo n.º 14
0
        private static X509Certificate2 GetCertificateFromKeyVault(string keyVaultCertName)
        {
            var keyVaultName = Configuration[ConfigKeys.KEY_VAULT_NAME];
            Uri vaultUri     = new Uri($"https://{keyVaultName}.vault.azure.net/");
            var cred         = new DefaultAzureCredential();

            var client = new CertificateClient(vaultUri: vaultUri, credential: cred);

            var certResponse = client.GetCertificate(keyVaultCertName);

            if (certResponse != null && certResponse.Value != null)
            {
                string         secretName   = certResponse.Value.SecretId.Segments[2].TrimEnd('/');
                SecretClient   secretClient = new SecretClient(vaultUri, cred);
                KeyVaultSecret secret       = secretClient.GetSecret(secretName);

                byte[] pfx = Convert.FromBase64String(secret.Value);
                return(new X509Certificate2(pfx));
            }
            else
            {
                return(null);
            }
        }
        public void Delete_Purge_CompletelyRemovedCertificate()
        {
            var deleteLogger = _loggerFactory.CreateLogger <KeyVaultCertificateDeleter>();
            var addLogger    = _loggerFactory.CreateLogger <KeyVaultCertificateAdder>();
            var adder        = new KeyVaultCertificateAdder(_client, addLogger);

            adder.Add(_certificateName);
            var deleter = new KeyVaultCertificateDeleter(_client, deleteLogger);

            deleter.Delete(new KeyVaultCertificateDeleteEvent
            {
                Name  = _certificateName,
                Purge = true
            });

            Action action = () => _client.GetCertificate(_certificateName);

            action.Should().ThrowExactly <RequestFailedException>().Where(e =>
                                                                          e.Message.Contains($"A certificate with (name/id) {_certificateName} was not found in this key vault.",
                                                                                             StringComparison.InvariantCultureIgnoreCase));
            action = () => _client.GetDeletedCertificate(_certificateName);

            action.Should().ThrowExactly <RequestFailedException>();
        }
Ejemplo n.º 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(TimeSpan.FromSeconds(1));
            }

            // Let's get the created certificate along with it's policy from the Key Vault.
            CertificateWithPolicy certificate = client.GetCertificate(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.
            CertificateProperties certificateProperties = certificate.Properties;

            certificateProperties.Enabled = false;

            Certificate updatedCert = client.UpdateCertificateProperties(certificateProperties);

            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(TimeSpan.FromSeconds(1));
            }

            // 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);
        }
Ejemplo n.º 17
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 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);
        }
Ejemplo n.º 19
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
            }
        }