Пример #1
0
        /// <summary>
        /// Creates a new key, stores it, then returns key parameters and attributes.
        /// </summary>
        /// <param name="keyName"></param>
        /// <param name="keyParameters"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task <KeyBundle> CreateKeyAsync(
            string keyName,
            NewKeyParameters keyParameters,
            CancellationToken cancellationToken = default
            )
        {
            if (string.IsNullOrEmpty(keyName))
            {
                throw new ArgumentNullException(nameof(keyName));
            }

            var keyBundle = await _keyVaultClient
                            .CreateKeyAsync(
                _keyVault.Properties.VaultUri,
                keyName,
                keyParameters,
                cancellationToken
                );

            return(keyBundle);
        }
Пример #2
0
        public static async Task <KeyBundle> CreateKeyAsync(this IKeyVaultClient operations, string vaultBaseUrl, string keyName, NewKeyParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (string.IsNullOrEmpty(vaultBaseUrl))
            {
                throw new ArgumentNullException(nameof(vaultBaseUrl));
            }

            if (string.IsNullOrEmpty(keyName))
            {
                throw new ArgumentNullException(nameof(keyName));
            }

            if (parameters == null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }

            using (var _result = await operations.CreateKeyWithHttpMessagesAsync(
                       vaultBaseUrl,
                       keyName,
                       parameters.Kty,
                       parameters.KeySize,
                       parameters.KeyOps,
                       parameters.Attributes,
                       parameters.Tags,
                       parameters.CurveName,
                       null, // customHeaders
                       cancellationToken
                       ).ConfigureAwait(false))
            {
                return(_result.Body);
            }
        }
Пример #3
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
            }
        }
Пример #4
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());
        }