Example #1
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);
            }
        }
        public async Task VerifyCertificateGetWithPolicyInProgress()
        {
            string certName = Recording.GenerateId();

            CertificatePolicy certificatePolicy = DefaultPolicy;

            certificatePolicy.IssuerName = WellKnownIssuerNames.Unknown;

            await Client.StartCreateCertificateAsync(certName, certificatePolicy);

            RegisterForCleanup(certName);

            KeyVaultCertificateWithPolicy certificateWithPolicy = await Client.GetCertificateAsync(certName);

            Assert.NotNull(certificateWithPolicy);

            Assert.AreEqual(certificateWithPolicy.Name, certName);

            Assert.NotNull(certificateWithPolicy.Properties.Version);

            KeyVaultCertificate certificate = await Client.GetCertificateVersionAsync(certName, certificateWithPolicy.Properties.Version);

            Assert.NotNull(certificate);

            Assert.AreEqual(certificate.Name, certName);
        }
        protected override void ProcessRecord()
        {
            CertificateBundle certBundle;

            switch (ParameterSetName)
            {
            case ByCertificateNameParameterSet:
                certBundle = this.DataServiceClient.GetCertificate(VaultName, Name, Version ?? string.Empty);
                var certificate = KeyVaultCertificate.FromCertificateBundle(certBundle);
                this.WriteObject(certificate);
                break;

            case ByCertificateVersionsParameterSet:
                certBundle = this.DataServiceClient.GetCertificate(VaultName, Name, string.Empty);
                if (certBundle != null)
                {
                    WriteObject(new CertificateIdentityItem(certBundle));
                    GetAndWriteCertificatesVersions(VaultName, Name, certBundle.CertificateIdentifier.Version);
                }
                break;

            case ByVaultNameParameterSet:
                GetAndWriteCertificates(VaultName);
                break;

            default:
                throw new ArgumentException(KeyVaultProperties.Resources.BadParameterSetName);
            }
        }
        public async Task VerifyUpdateCertificate()
        {
            string certName = Recording.GenerateId();

            CertificateOperation operation = await Client.StartCreateCertificateAsync(certName, DefaultPolicy);

            RegisterForCleanup(certName);

            KeyVaultCertificateWithPolicy original = await operation.WaitForCompletionAsync(DefaultCertificateOperationPollingInterval, default);

            CertificateProperties originalProperties = original.Properties;

            Assert.IsTrue(originalProperties.Enabled);
            Assert.IsEmpty(originalProperties.Tags);

            IDictionary <string, string> expTags = new Dictionary <string, string>()
            {
                { "key1", "value1" }
            };

            originalProperties.Tags.Add("key1", "value1");

            KeyVaultCertificate updated = await Client.UpdateCertificatePropertiesAsync(originalProperties);

            Assert.IsTrue(updated.Properties.Enabled);
            CollectionAssert.AreEqual(expTags, updated.Properties.Tags);

            originalProperties.Enabled = false;
            originalProperties.Tags.Clear();
            updated = await Client.UpdateCertificatePropertiesAsync(originalProperties);

            Assert.IsFalse(updated.Properties.Enabled);
            CollectionAssert.AreEqual(expTags, updated.Properties.Tags);
        }
        public async Task DownloadVersionedCertificate(string contentType)
        {
            string            name   = Recording.GenerateId();
            CertificatePolicy policy = new CertificatePolicy
            {
                IssuerName = WellKnownIssuerNames.Self,
                Subject    = "CN=default",
                KeyType    = CertificateKeyType.Rsa,
                Exportable = true,
                ReuseKey   = false,
                KeyUsage   =
                {
                    CertificateKeyUsage.DataEncipherment,
                },
                CertificateTransparency = false,
                ContentType             = contentType,
            };

            CertificateOperation operation = await Client.StartCreateCertificateAsync(name, policy);

            RegisterForCleanup(name);

            await operation.WaitForCompletionAsync(DefaultCertificateOperationPollingInterval, default);

            KeyVaultCertificate certificate = await Client.GetCertificateAsync(name);

            string version = certificate.Properties.Version;

            using X509Certificate2 pub = new X509Certificate2(certificate.Cer);
#if NET6_0_OR_GREATER
            using RSA pubkey = (RSA)pub.PublicKey.GetRSAPublicKey();
#else
            using RSA pubkey = (RSA)pub.PublicKey.Key;
#endif

            byte[] plaintext  = Encoding.UTF8.GetBytes("Hello, world!");
            byte[] ciphertext = pubkey.Encrypt(plaintext, RSAEncryptionPadding.Pkcs1);

            // Create a new certificate version that is not exportable just to further prove we are not downloading it.
            policy.Exportable = false;
            operation         = await Client.StartCreateCertificateAsync(name, policy);

            await operation.WaitForCompletionAsync(DefaultCertificateOperationPollingInterval, default);

            certificate = await Client.GetCertificateAsync(name);

            Assert.AreNotEqual(version, certificate.Properties.Version);

            // Now download the certificate and test decryption.
            using X509Certificate2 x509certificate = await Client.DownloadCertificateAsync(name, version);

            Assert.IsTrue(x509certificate.HasPrivateKey);

            using RSA rsa = (RSA)x509certificate.GetRSAPrivateKey();
            byte[] decrypted = rsa.Decrypt(ciphertext, RSAEncryptionPadding.Pkcs1);

            CollectionAssert.AreEqual(plaintext, decrypted);
        }
Example #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);
        }
Example #7
0
        protected override void ProcessRecord()
        {
            if (ShouldProcess(Name, Properties.Resources.ImportCertificate))
            {
                List <CertificateBundle> certBundleList = new List <CertificateBundle>();
                CertificateBundle        certBundle     = null;

                switch (ParameterSetName)
                {
                case ImportCertificateFromFileParameterSet:

                    certBundle = this.DataServiceClient.MergeCertificate(
                        VaultName,
                        Name,
                        LoadCertificateFromFile(),
                        Tag == null ? null : Tag.ConvertToDictionary());

                    break;

                case ImportWithPrivateKeyFromFileParameterSet:

                    X509Certificate2Collection userProvidedCertColl = InitializeCertificateCollection();
                    X509Certificate2Collection certColl             = new X509Certificate2Collection();

                    byte[] base64Bytes;

                    if (Password == null)
                    {
                        base64Bytes = userProvidedCertColl.Export(X509ContentType.Pfx);
                    }
                    else
                    {
                        base64Bytes = userProvidedCertColl.Export(X509ContentType.Pfx, Password.ConvertToString());
                    }

                    string base64CertCollection = Convert.ToBase64String(base64Bytes);
                    certBundle = this.DataServiceClient.ImportCertificate(VaultName, Name, base64CertCollection, Password, Tag == null ? null : Tag.ConvertToDictionary());

                    break;

                case ImportWithPrivateKeyFromCollectionParameterSet:
                    certBundle = this.DataServiceClient.ImportCertificate(VaultName, Name, CertificateCollection, Tag == null ? null : Tag.ConvertToDictionary());

                    break;

                case ImportWithPrivateKeyFromStringParameterSet:
                    certBundle = this.DataServiceClient.ImportCertificate(VaultName, Name, CertificateString, Password, Tag == null ? null : Tag.ConvertToDictionary());

                    break;

                default:
                    throw new ArgumentException(KeyVaultProperties.Resources.BadParameterSetName);
                }

                var certificate = KeyVaultCertificate.FromCertificateBundle(certBundle);
                this.WriteObject(certificate);
            }
        }
Example #8
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
        }
Example #9
0
        public void UpdateCertificate()
        {
            KeyVaultCertificateWithPolicy certificate = client.GetCertificate("MyCertificate");

            #region Snippet:UpdateCertificate
            CertificateProperties certificateProperties = new CertificateProperties(certificate.Id);
            certificateProperties.Tags["key1"] = "value1";

            KeyVaultCertificate updated = client.UpdateCertificateProperties(certificateProperties);
            #endregion
        }
Example #10
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>
        /// Initializes a new instance of the type
        /// </summary>
        /// <param name="certificate">The key vault certificate</param>
        /// <param name="httpStatus">The http status code returned</param>
        /// <param name="elapsedMilliseconds">The number of milliseconds that elapsed executing the query</param>
        internal KeyVaultCertificateResponse(KeyVaultCertificate certificate, int httpStatus, long elapsedMilliseconds) : base(httpStatus, elapsedMilliseconds)
        {
            Id      = certificate.Id;
            Name    = certificate.Name;
            Version = certificate.Properties.Version;

            Properties = certificate.Properties;
            Value      = certificate.Cer;
            SecretId   = certificate.SecretId;
            KeyId      = certificate.KeyId;
            Policy     = null;
        }
Example #12
0
        public async Task RetrieveCertificateAsync()
        {
            #region Snippet:RetrieveCertificate
            KeyVaultCertificateWithPolicy certificateWithPolicy = await client.GetCertificateAsync("MyCertificate");

            #endregion

            #region Snippet:GetCertificate
            KeyVaultCertificate certificate = await client.GetCertificateVersionAsync(certificateWithPolicy.Name, certificateWithPolicy.Properties.Version);

            #endregion
        }
        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.
            var 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.
            KeyVaultCertificateWithPolicy certificate = await certOp.WaitForCompletionAsync();

            // 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;

            KeyVaultCertificate updatedCert = await client.UpdateCertificatePropertiesAsync(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 = 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);
        }
Example #14
0
        internal async Task <SecurityKeyInfo> GetSecurityKeyFromCertificateAsync(KeyVaultCertificate certificateItem)
        {
            var certificateVersionBundle = await this._CertificateClient.GetCertificateAsync(certificateItem.Name);

            var certificatePrivateKeySecretBundle = await this._SecretClient.GetSecretAsync(certificateVersionBundle.Value.Name);

            var privateKeyBytes           = Convert.FromBase64String(certificatePrivateKeySecretBundle.Value.Value);
            var certificateWithPrivateKey = new X509Certificate2(privateKeyBytes, (string)null, X509KeyStorageFlags.MachineKeySet);

            return(new SecurityKeyInfo()
            {
                Key = new X509SecurityKey(certificateWithPrivateKey),
                SigningAlgorithm = SecurityAlgorithms.RsaSha512
            });
        }
Example #15
0
        public async Task UpdateCertificateAsync()
        {
            KeyVaultCertificateWithPolicy certificate = await client.GetCertificateAsync("MyCertificate");

            #region Snippet:UpdateCertificate
            CertificateProperties certificateProperties = new CertificateProperties(certificate.Id)
            {
                Tags =
                {
                    ["key1"] = "value1"
                }
            };

            KeyVaultCertificate updated = await client.UpdateCertificatePropertiesAsync(certificateProperties);

            #endregion
        }
Example #16
0
        public async Task DownloadLatestCertificate()
        {
            string            name   = Recording.GenerateId();
            CertificatePolicy policy = new CertificatePolicy
            {
                IssuerName = WellKnownIssuerNames.Self,
                Subject    = "CN=default",
                KeyType    = CertificateKeyType.Rsa,
                Exportable = true,
                ReuseKey   = false,
                KeyUsage   =
                {
                    CertificateKeyUsage.DataEncipherment,
                    CertificateKeyUsage.DigitalSignature,
                },
                CertificateTransparency = false,
                ContentType             = CertificateContentType.Pkcs12,
            };

            CertificateOperation operation = await Client.StartCreateCertificateAsync(name, policy);

            RegisterForCleanup(name);

            await operation.WaitForCompletionAsync();

            KeyVaultCertificate certificate = await Client.GetCertificateAsync(name);

            using X509Certificate2 pub = new X509Certificate2(certificate.Cer);
            using RSA pubkey           = (RSA)pub.PublicKey.Key;

            byte[] plaintext  = Encoding.UTF8.GetBytes("Hello, world!");
            byte[] ciphertext = pubkey.Encrypt(plaintext, RSAEncryptionPadding.Pkcs1);

            using X509Certificate2 x509certificate = await Client.DownloadCertificateAsync(name);

            Assert.IsTrue(x509certificate.HasPrivateKey);

            using RSA rsa = (RSA)x509certificate.PrivateKey;
            byte[] decrypted = rsa.Decrypt(ciphertext, RSAEncryptionPadding.Pkcs1);

            CollectionAssert.AreEqual(plaintext, decrypted);
        }
        public override void ExecuteCmdlet()
        {
            if (ShouldProcess(Name, Properties.Resources.SetCertificateAttributes))
            {
                var certificateBundle = DataServiceClient.UpdateCertificate(
                    VaultName,
                    Name,
                    Version ?? string.Empty,
                    new CertificateAttributes
                {
                    Enabled = Enable,
                },
                    Tag == null ? null : Tag.ConvertToDictionary());

                if (PassThru)
                {
                    var certificate = KeyVaultCertificate.FromCertificateBundle(certificateBundle);
                    this.WriteObject(certificate);
                }
            }
        }
        protected override void ProcessRecord()
        {
            CertificateBundle certBundle = null;

            ConfirmAction(
                Force.IsPresent,
                string.Format(
                    CultureInfo.InvariantCulture,
                    KeyVaultProperties.Resources.RemoveCertWarning,
                    Name),
                string.Format(
                    CultureInfo.InvariantCulture,
                    KeyVaultProperties.Resources.RemoveCertWhatIfMessage,
                    Name),
                Name,
                () => { certBundle = this.DataServiceClient.DeleteCertificate(VaultName, Name); });

            if (PassThru.IsPresent)
            {
                var certificate = KeyVaultCertificate.FromCertificateBundle(certBundle);
                this.WriteObject(certificate);
            }
        }
        public async Task VerifyGetCertificateCompleted()
        {
            string certName = Recording.GenerateId();

            CertificateOperation operation = await Client.StartCreateCertificateAsync(certName, DefaultPolicy);

            RegisterForCleanup(certName);

            await operation.WaitForCompletionAsync(DefaultCertificateOperationPollingInterval, default);

            KeyVaultCertificateWithPolicy certificateWithPolicy = await Client.GetCertificateAsync(certName);

            Assert.NotNull(certificateWithPolicy);

            Assert.AreEqual(certificateWithPolicy.Name, certName);

            Assert.NotNull(certificateWithPolicy.Properties.Version);

            KeyVaultCertificate certificate = await Client.GetCertificateVersionAsync(certName, certificateWithPolicy.Properties.Version);

            Assert.NotNull(certificate);

            Assert.AreEqual(certificate.Name, certName);
        }
        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, 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.
            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.
            KeyVaultCertificateWithPolicy certificate = client.GetCertificate(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;

            KeyVaultCertificate 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);
        }
Example #21
0
        internal async Task <SigningCredentials> GetSigningCredentialsFromCertificateAsync(KeyVaultCertificate certificateItem)
        {
            var certificateVersionSecurityKey = await GetSecurityKeyFromCertificateAsync(certificateItem);

            return(new SigningCredentials(certificateVersionSecurityKey.Key, SecurityAlgorithms.RsaSha512));
        }
        public async Task <ActionResult> Secrets()
        {
            // Via App Service reference
            // See https://docs.microsoft.com/bs-cyrl-ba/azure/app-service/app-service-key-vault-references
            // For example:
            //     @Microsoft.KeyVault(SecretUri=https://myvault.vault.azure.net/secrets/mysecret/ec96f02080254f109c51a1f14cdb1931)
            //     or
            //     @Microsoft.KeyVault(SecretUri=https://myvault.vault.azure.net/secrets/mysecret/)
            //     if you only care about the latest version of that secret
            ViewBag.ViaRef = ConfigurationManager.AppSettings["secret1"];

            // Via Key Vault SDK
            string keyVaultInstance = "https://alice.vault.azure.net";
            // Retry policy
            // https://docs.microsoft.com/en-us/azure/key-vault/general/overview-throttling
            SecretClientOptions options = new SecretClientOptions()
            {
                Retry =
                {
                    Delay      = TimeSpan.FromSeconds(2),
                    MaxDelay   = TimeSpan.FromSeconds(16),
                    MaxRetries =                        5,
                    Mode       = RetryMode.Exponential
                }
            };
            // Instantiate client with retry policy (options)
            SecretClient   secretClient = new SecretClient(new Uri(keyVaultInstance), new DefaultAzureCredential(), options);
            KeyVaultSecret secret       = await secretClient.GetSecretAsync("secret1");

            ViewBag.ViaSDK = secret.Value;

            // Via configBuilder (see web.config)
            ViewBag.ViaBuilder = ConfigurationManager.AppSettings["secret1"];

            // Manual REST API calls
            AzureServiceTokenProvider tokenProvider = new AzureServiceTokenProvider();
            // Resource URI for Key Vault is always https://vault.azure.net,
            // irrespective of the name of your Key Vault
            string accessToken = await tokenProvider.GetAccessTokenAsync("https://vault.azure.net");

            HttpClient httpClient = new HttpClient();

            httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {accessToken}");
            // Response is a JSON object, the secret value is returned as response["value"] and looks like this -
            //  {
            //      "value": "TH3 VALU3 0F THE S3CRE7",
            //      "contentType": "this_property_is/completely_arbitrary",
            //      "id": "https://<YOUR-VAULT-NAME>.vault.azure.net/secrets/<NAME-OF-YOUR-SECRET>/d96492d7b6d744a085a37c812badb3e4",
            //      "attributes": {
            //          "enabled": true,
            //          "created": 1526314127,
            //          "updated": 1526314127,
            //          "recoveryLevel": "Purgeable"
            //      }
            //  }
            string secretOverRest = await httpClient.GetStringAsync("https://alice.vault.azure.net/secrets/secret1?api-version=7.0");

            ViewBag.ViaRest = secretOverRest;


            // Get certificate from Key Vault
            CertificateClient   certClient = new CertificateClient(new Uri(keyVaultInstance), new DefaultAzureCredential());
            KeyVaultCertificate cert       = await certClient.GetCertificateAsync("Joes-Crab-Shack-RSA");

            X509Certificate2 x509cert = new X509Certificate2(cert.Cer);

            ViewBag.CertSubject = x509cert.Subject;
            ViewBag.CertId      = cert.Id;
            ViewBag.CertName    = cert.Name;

            return(View());
        }