Пример #1
0
        /// <summary>
        /// backup the specified key and then restores the key into a vault
        /// </summary>
        /// <param name="keyName"> the name of the key to get </param>
        /// <returns> restored key bundle </returns>
        private static KeyBundle BackupRestoreKey(string keyName)
        {
            var vaultAddress = inputValidator.GetVaultAddress();

            keyName = inputValidator.GetKeyName();

            // Get a backup of the key and cache its backup value
            var backupKeyResult = keyVaultClient.BackupKeyAsync(vaultAddress, keyName).GetAwaiter().GetResult();

            Console.Out.WriteLine(string.Format(
                                      "The backup key value contains {0} bytes.\nTo restore it into a key vault this value should be provided!", backupKeyResult.Value.Length));

            // Get the vault address from args or use the default one
            var newVaultAddress = inputValidator.GetVaultAddress();

            // Delete any existing key in that vault.
            keyVaultClient.DeleteKeyAsync(vaultAddress, keyName).GetAwaiter().GetResult();

            // Restore the backed up value into the vault
            var restoredKey = keyVaultClient.RestoreKeyAsync(newVaultAddress, backupKeyResult.Value).GetAwaiter().GetResult();

            Console.Out.WriteLine("Restored key:---------------");
            PrintoutKey(restoredKey);

            // Cache the restored key
            return(restoredKey);
        }
Пример #2
0
        public async Task <DeletedKeyBundle> DeleteKey(string keyName)
        {
            var client = new KeyVaultClient(AuthCallback);
            var r      = await client.DeleteKeyAsync(VaultBaseUrl, keyName);

            return(r);
        }
Пример #3
0
        public async Task DeleteKeyAsync(string keyName)
        {
            if (string.IsNullOrEmpty(keyName))
            {
                throw new ArgumentNullException(keyName);
            }

            await KeyVaultClient.DeleteKeyAsync(VaultAddress, keyName);
        }
Пример #4
0
        public override async Task RemoveSecretAsync(string key)
        {
            if (DateTime.Now > expiry)
            {
                client = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(GetAccessToken));
            }

            await client.DeleteKeyAsync(String.Format("https://{0}.vault.azure.net:443/", Authority), key);
        }
 /// <summary>
 /// Removes a specific key
 /// </summary>
 /// <param name="key">The key to search for</param>
 public async Task RemoveKeyAsync(string key)
 {
     try
     {
         var retry = new RetryWithExponentialBackoff();
         await retry.RunAsync(async() =>
         {
             // Deletes a key
             var deletedKey = await keyVaultClient.DeleteKeyAsync(vaultAddress, key);
             // And purges it immediately
             if (deletedKey.RecoveryId != null)
             {
                 await keyVaultClient.PurgeDeletedKeyAsync(deletedKey.RecoveryId);
             }
         });
     }
     catch (KeyVaultErrorException ex)
     {
         if (ex.Body.Error.Code != "KeyNotFound")
         {
             throw ex;
         }
     }
 }
Пример #6
0
 public async Task DeleteKeyAsync(string keyName)
 {
     await KeyVaultClient.DeleteKeyAsync(VaultAddress, keyName);
 }
Пример #7
0
        private async Task KeysMigrationGuide()
        {
            #region Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_Create
            AzureServiceTokenProvider provider = new AzureServiceTokenProvider();
            KeyVaultClient            client   = new KeyVaultClient(
                new KeyVaultClient.AuthenticationCallback(provider.KeyVaultTokenCallback));
            #endregion Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_Create

            #region Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_CreateWithOptions
            using (HttpClient httpClient = new HttpClient())
            {
                //@@AzureServiceTokenProvider provider = new AzureServiceTokenProvider();
                /*@@*/ provider = new AzureServiceTokenProvider();
                //@@KeyVaultClient client = new KeyVaultClient(
                /*@@*/ client = new KeyVaultClient(
                    new KeyVaultClient.AuthenticationCallback(provider.KeyVaultTokenCallback),
                    httpClient);
            }
            #endregion Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_CreateWithOptions

            {
                #region Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_CreateKey
                // Create RSA key.
                NewKeyParameters createRsaParameters = new NewKeyParameters
                {
                    Kty     = JsonWebKeyType.Rsa,
                    KeySize = 4096
                };

                KeyBundle rsaKey = await client.CreateKeyAsync("https://myvault.vault.azure.net", "rsa-key-name", createRsaParameters);

                // Create Elliptic-Curve key.
                NewKeyParameters createEcParameters = new NewKeyParameters
                {
                    Kty       = JsonWebKeyType.EllipticCurve,
                    CurveName = "P-256"
                };

                KeyBundle ecKey = await client.CreateKeyAsync("https://myvault.vault.azure.net", "ec-key-name", createEcParameters);

                #endregion Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_CreateKey
            }

            {
                #region Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_ListKeys
                IPage <KeyItem> page = await client.GetKeysAsync("https://myvault.vault.azure.net");

                foreach (KeyItem item in page)
                {
                    KeyIdentifier keyId = item.Identifier;
                    KeyBundle     key   = await client.GetKeyAsync(keyId.Vault, keyId.Name);
                }

                while (page.NextPageLink != null)
                {
                    page = await client.GetKeysNextAsync(page.NextPageLink);

                    foreach (KeyItem item in page)
                    {
                        KeyIdentifier keyId = item.Identifier;
                        KeyBundle     key   = await client.GetKeyAsync(keyId.Vault, keyId.Name);
                    }
                }
                #endregion Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_ListKeys
            }

            {
                #region Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_DeleteKey
                // Delete the key.
                DeletedKeyBundle deletedKey = await client.DeleteKeyAsync("https://myvault.vault.azure.net", "key-name");

                // Purge or recover the deleted key if soft delete is enabled.
                if (deletedKey.RecoveryId != null)
                {
                    DeletedKeyIdentifier deletedKeyId = deletedKey.RecoveryIdentifier;

                    // Deleting a key does not happen immediately. Wait a while and check if the deleted key exists.
                    while (true)
                    {
                        try
                        {
                            await client.GetDeletedKeyAsync(deletedKeyId.Vault, deletedKeyId.Name);

                            // Finally deleted.
                            break;
                        }
                        catch (KeyVaultErrorException ex) when(ex.Response.StatusCode == HttpStatusCode.NotFound)
                        {
                            // Not yet deleted...
                        }
                    }

                    // Purge the deleted key.
                    await client.PurgeDeletedKeyAsync(deletedKeyId.Vault, deletedKeyId.Name);

                    // You can also recover the deleted key using RecoverDeletedKeyAsync.
                }
                #endregion Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_DeleteKey
            }

            {
                #region Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_Encrypt
                // Encrypt a message. The plaintext must be small enough for the chosen algorithm.
                byte[]             plaintext = Encoding.UTF8.GetBytes("Small message to encrypt");
                KeyOperationResult encrypted = await client.EncryptAsync("rsa-key-name", JsonWebKeyEncryptionAlgorithm.RSAOAEP256, plaintext);

                // Decrypt the message.
                KeyOperationResult decrypted = await client.DecryptAsync("rsa-key-name", JsonWebKeyEncryptionAlgorithm.RSAOAEP256, encrypted.Result);

                string message = Encoding.UTF8.GetString(decrypted.Result);
                #endregion Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_Encrypt
            }

            {
                #region Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_Wrap
                using (Aes aes = Aes.Create())
                {
                    // Use a symmetric key to encrypt large amounts of data, possibly streamed...

                    // Now wrap the key and store the encrypted key and plaintext IV to later decrypt the key to decrypt the data.
                    KeyOperationResult wrapped = await client.WrapKeyAsync(
                        "https://myvault.vault.azure.net",
                        "rsa-key-name",
                        null,
                        JsonWebKeyEncryptionAlgorithm.RSAOAEP256,
                        aes.Key);

                    // Read the IV and the encrypted key from the payload, then unwrap the key.
                    KeyOperationResult unwrapped = await client.UnwrapKeyAsync(
                        "https://myvault.vault.azure.net",
                        "rsa-key-name",
                        null,
                        JsonWebKeyEncryptionAlgorithm.RSAOAEP256,
                        wrapped.Result);

                    aes.Key = unwrapped.Result;

                    // Decrypt the payload with the symmetric key.
                }
                #endregion Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_Wrap
            }
        }
Пример #8
0
        public ActionResult Index()
        {
            string keyVaultName = "<YOUR_VAULT's_NAME>";
            string vaultBaseURL = $"https://{keyVaultName}.vault.azure.net";


            //Get a token for accessing the Key Vault.
            var azureServiceTokenProvider = new AzureServiceTokenProvider();

            //Create a Key Vault client for accessing the items in the vault;
            var keyVault = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));

            // Manage secrets in the Key Vault.
            // Create a new secret
            string secretName = "secret-az204";

            Task.Run(async() => await keyVault.SetSecretAsync(vaultBaseURL,
                                                              secretName,
                                                              "This is a secret testing value")).Wait();
            var secret = Task.Run(async() => await keyVault.GetSecretAsync
                                      ($"{vaultBaseURL}/secrets/{secretName}")).GetAwaiter().GetResult();

            // Update an existing secret
            Task.Run(async() => await keyVault.SetSecretAsync(vaultBaseURL,
                                                              secretName,
                                                              "Updated the secret testing value")).Wait();
            secret = Task.Run(async() => await keyVault.GetSecretAsync
                                  ($"{vaultBaseURL}/secrets/{secretName}")).GetAwaiter().GetResult();
            // Delete the secret
            Task.Run(async() => await keyVault.DeleteSecretAsync(vaultBaseURL,
                                                                 secretName)).Wait();

            // Manage certificates in the Key Vault
            string certName = "cert-az204";
            // Create a new self-signed certificate
            var policy = new CertificatePolicy
            {
                IssuerParameters = new IssuerParameters
                {
                    Name = "Self",
                },
                KeyProperties = new KeyProperties
                {
                    Exportable = true,
                    KeySize    = 2048,
                    KeyType    = "RSA"
                },
                SecretProperties = new SecretProperties
                {
                    ContentType = "application/x-pkcs12"
                },
                X509CertificateProperties = new X509CertificateProperties
                {
                    Subject = "CN=AZ204KEYVAULTDEMO"
                }
            };

            Task.Run(async() => await keyVault.CreateCertificateAsync(vaultBaseURL,
                                                                      certName, policy, new CertificateAttributes {
                Enabled = true
            })).Wait();
            // When you create a new certificate in the Key Vault it takes some time
            // before it's ready.
            // We added some wait time here for the sake of simplicity.
            Thread.Sleep(10000);
            var certificate = Task.Run(async() => await keyVault.GetCertificateAsync
                                           (vaultBaseURL, certName)).GetAwaiter().GetResult();
            // Update properties associated with the certificate.
            CertificatePolicy updatePolicy = new CertificatePolicy
            {
                X509CertificateProperties = new X509CertificateProperties
                {
                    SubjectAlternativeNames = new SubjectAlternativeNames
                    {
                        DnsNames = new[] { "az204.examref.testing" }
                    }
                }
            };


            Task.Run(async() => await keyVault.UpdateCertificatePolicyAsync(
                         vaultBaseURL, certName, updatePolicy)).Wait();
            Task.Run(async() => await keyVault.CreateCertificateAsync(vaultBaseURL,
                                                                      certName)).Wait();
            Thread.Sleep(10000);


            certificate = Task.Run(async() => await keyVault.GetCertificateAsync(
                                       vaultBaseURL, certName)).
                          GetAwaiter().GetResult();

            Task.Run(async() => await keyVault.UpdateCertificateAsync(certificate.
                                                                      CertificateIdentifier.Identifier, null,
                                                                      new CertificateAttributes
            {
                Enabled =
                    false
            })).Wait();
            Thread.Sleep(10000);

            // Delete the self-signed certificate.
            Task.Run(async() => await keyVault.DeleteCertificateAsync(vaultBaseURL,
                                                                      certName)).Wait();

            // Manage keys in the Key Vault
            string           keyName       = "key-az204";
            NewKeyParameters keyParameters = new NewKeyParameters
            {
                Kty       = "EC",
                CurveName = "SECP256K1",
                KeyOps    = new[] { "sign", "verify" }
            };

            Task.Run(async() => await keyVault.CreateKeyAsync(vaultBaseURL, keyName,
                                                              keyParameters)).Wait();
            var key = Task.Run(async() => await keyVault.GetKeyAsync(vaultBaseURL,
                                                                     keyName)).GetAwaiter().GetResult();

            // Update keys in the Key Vault
            Task.Run(async() => await keyVault.UpdateKeyAsync(vaultBaseURL, keyName,
                                                              null, new KeyAttributes
            {
                Expires = DateTime.UtcNow.
                          AddYears(1)
            })).Wait();
            key = Task.Run(async() => await keyVault.GetKeyAsync(vaultBaseURL,
                                                                 keyName)).GetAwaiter().GetResult();

            // Delete keys from the Key Vault
            Task.Run(async() => await keyVault.DeleteKeyAsync(vaultBaseURL, keyName)).
            Wait();


            return(View());
        }
Пример #9
0
 public async void DeleteKey(string keyName)
 {
     var keyBundle = await keyVaultClient.DeleteKeyAsync(keyVaultUri, keyName);
 }