public async Task RecoverDeletedEcHsmKey()
        {
            string keyName = Recording.GenerateId();

            CreateEcKeyOptions options  = new CreateEcKeyOptions(keyName, hardwareProtected: true);
            KeyVaultKey        ecHsmKey = await Client.CreateEcKeyAsync(options);

            DeleteKeyOperation deleteOperation = await Client.StartDeleteKeyAsync(keyName);

            DeletedKey deletedKey = await deleteOperation.WaitForCompletionAsync();

            await WaitForDeletedKey(keyName);

            Assert.ThrowsAsync <RequestFailedException>(() => Client.GetKeyAsync(keyName));

            RecoverDeletedKeyOperation recoverOperation = await Client.StartRecoverDeletedKeyAsync(keyName);

            KeyVaultKey recoverKeyResult = await recoverOperation.WaitForCompletionAsync();

            await WaitForKey(keyName);

            KeyVaultKey recoveredKey = await Client.GetKeyAsync(keyName);

            RegisterForCleanup(recoveredKey.Name);

            AssertKeyVaultKeysEqual(ecHsmKey, deletedKey);
            AssertKeyVaultKeysEqual(ecHsmKey, recoverKeyResult);
            AssertKeyVaultKeysEqual(ecHsmKey, recoveredKey);
        }
Ejemplo n.º 2
0
        public void CreateKey()
        {
            #region CreateKey
            // Create a key. Note that you can specify the type of key
            // i.e. Elliptic curve, Hardware Elliptic Curve, RSA
            KeyVaultKey key = client.CreateKey("key-name", KeyType.Rsa);

            Console.WriteLine(key.Name);
            Console.WriteLine(key.KeyType);

            // Create a software RSA key
            var         rsaCreateKey = new CreateRsaKeyOptions("rsa-key-name", hardwareProtected: false);
            KeyVaultKey rsaKey       = client.CreateRsaKey(rsaCreateKey);

            Console.WriteLine(rsaKey.Name);
            Console.WriteLine(rsaKey.KeyType);

            // Create a hardware Elliptic Curve key
            var         echsmkey = new CreateEcKeyOptions("ec-key-name", hardwareProtected: true);
            KeyVaultKey ecKey    = client.CreateEcKey(echsmkey);

            Console.WriteLine(ecKey.Name);
            Console.WriteLine(ecKey.KeyType);
            #endregion
        }
        public async Task UpdateEcHsmKeyOps()
        {
            string keyName = Recording.GenerateId();

            CreateEcKeyOptions options = new CreateEcKeyOptions(keyName, hardwareProtected: true)
            {
                KeyOperations =
                {
                    KeyOperation.Verify,
                },
            };

            KeyVaultKey ecHsmKey = await Client.CreateEcKeyAsync(options);

            RegisterForCleanup(keyName);

            AssertAreEqual(new[] { KeyOperation.Verify }, ecHsmKey.KeyOperations);

            ecHsmKey.Properties.ExpiresOn = DateTimeOffset.Now.AddDays(1);

            ecHsmKey = await Client.UpdateKeyPropertiesAsync(ecHsmKey.Properties);

            AssertAreEqual(new[] { KeyOperation.Verify }, ecHsmKey.KeyOperations);

            ecHsmKey = await Client.UpdateKeyPropertiesAsync(ecHsmKey.Properties, new[] { KeyOperation.Sign, KeyOperation.Verify });

            AssertAreEqual(new[] { KeyOperation.Sign, KeyOperation.Verify }, ecHsmKey.KeyOperations);
        }
Ejemplo n.º 4
0
        public void CreateKey()
        {
            #region Snippet:CreateKey
            // Create a key. Note that you can specify the type of key
            // i.e. Elliptic curve, Hardware Elliptic Curve, RSA
            KeyVaultKey key = client.CreateKey("key-name", KeyType.Rsa);

            Console.WriteLine(key.Name);
            Console.WriteLine(key.KeyType);

            // Create a software RSA key
            var         rsaCreateKey = new CreateRsaKeyOptions("rsa-key-name", hardwareProtected: false);
            KeyVaultKey rsaKey       = client.CreateRsaKey(rsaCreateKey);

            Console.WriteLine(rsaKey.Name);
            Console.WriteLine(rsaKey.KeyType);

            // Create a hardware Elliptic Curve key
            // Because only premium Azure Key Vault supports HSM backed keys , please ensure your Azure Key Vault
            // SKU is premium when you set "hardwareProtected" value to true
            var         echsmkey = new CreateEcKeyOptions("ec-key-name", hardwareProtected: true);
            KeyVaultKey ecKey    = client.CreateEcKey(echsmkey);

            Console.WriteLine(ecKey.Name);
            Console.WriteLine(ecKey.KeyType);
            #endregion
        }
Ejemplo n.º 5
0
        public async Task CreateKeyAsync()
        {
            #region Snippet:CreateKeyAsync
            // Create a key of any type
            KeyVaultKey key = await client.CreateKeyAsync("key-name", KeyType.Rsa);

            Console.WriteLine(key.Name);
            Console.WriteLine(key.KeyType);

            // Create a software RSA key
            var         rsaCreateKey = new CreateRsaKeyOptions("rsa-key-name", hardwareProtected: false);
            KeyVaultKey rsaKey       = await client.CreateRsaKeyAsync(rsaCreateKey);

            Console.WriteLine(rsaKey.Name);
            Console.WriteLine(rsaKey.KeyType);

            // Create a hardware Elliptic Curve key
            // Because only premium Azure Key Vault supports HSM backed keys , please ensure your Azure Key Vault
            // SKU is premium when you set "hardwareProtected" value to true
            var         echsmkey = new CreateEcKeyOptions("ec-key-name", hardwareProtected: true);
            KeyVaultKey ecKey    = await client.CreateEcKeyAsync(echsmkey);

            Console.WriteLine(ecKey.Name);
            Console.WriteLine(ecKey.KeyType);
            #endregion
        }
Ejemplo n.º 6
0
        private PSKeyVaultKey CreateKey(KeyClient client, string keyName, PSKeyVaultKeyAttributes keyAttributes, int?size, string curveName)
        {
            CreateKeyOptions options;
            bool             isHsm = keyAttributes.KeyType == KeyType.RsaHsm || keyAttributes.KeyType == KeyType.EcHsm;

            if (keyAttributes.KeyType == KeyType.Rsa || keyAttributes.KeyType == KeyType.RsaHsm)
            {
                options = new CreateRsaKeyOptions(keyName, isHsm)
                {
                    KeySize = size
                };
            }
            else if (keyAttributes.KeyType == KeyType.Ec || keyAttributes.KeyType == KeyType.EcHsm)
            {
                options = new CreateEcKeyOptions(keyName, isHsm)
                {
                    CurveName = string.IsNullOrEmpty(curveName) ? (KeyCurveName?)null : new KeyCurveName(curveName)
                };
            }
            else
            {
                // oct (AES) is only supported by managed HSM
                throw new NotSupportedException($"{keyAttributes.KeyType} is not supported");
            }
            options.NotBefore     = keyAttributes.NotBefore;
            options.ExpiresOn     = keyAttributes.Expires;
            options.Enabled       = keyAttributes.Enabled;
            options.Exportable    = keyAttributes.Exportable;
            options.ReleasePolicy = keyAttributes.ReleasePolicy?.ToKeyReleasePolicy();;

            if (keyAttributes.KeyOps != null)
            {
                foreach (var keyOp in keyAttributes.KeyOps)
                {
                    options.KeyOperations.Add(new KeyOperation(keyOp));
                }
            }
            if (keyAttributes.Tags != null)
            {
                foreach (DictionaryEntry entry in keyAttributes.Tags)
                {
                    options.Tags.Add(entry.Key.ToString(), entry.Value.ToString());
                }
            }

            if (keyAttributes.KeyType == KeyType.Rsa || keyAttributes.KeyType == KeyType.RsaHsm)
            {
                return(new PSKeyVaultKey(client.CreateRsaKey(options as CreateRsaKeyOptions).Value, _vaultUriHelper, false));
            }
            else if (keyAttributes.KeyType == KeyType.Ec || keyAttributes.KeyType == KeyType.EcHsm)
            {
                return(new PSKeyVaultKey(client.CreateEcKey(options as CreateEcKeyOptions).Value, _vaultUriHelper, false));
            }
            else
            {
                throw new NotSupportedException($"{keyAttributes.KeyType} is not supported");
            }
        }
Ejemplo n.º 7
0
        public async Task CreateEcKey()
        {
            var         eckey    = new CreateEcKeyOptions(Recording.GenerateId(), hardwareProtected: false);
            KeyVaultKey keyNoHsm = await Client.CreateEcKeyAsync(eckey);

            RegisterForCleanup(keyNoHsm.Name);

            KeyVaultKey keyReturned = await Client.GetKeyAsync(keyNoHsm.Name);

            AssertKeyVaultKeysEqual(keyNoHsm, keyReturned);
        }
        public async Task GetEcHsmKey()
        {
            string keyName = Recording.GenerateId();

            CreateEcKeyOptions options  = new CreateEcKeyOptions(keyName, hardwareProtected: true);
            KeyVaultKey        ecHsmKey = await Client.CreateEcKeyAsync(options);

            RegisterForCleanup(keyName);

            KeyVaultKey keyReturned = await Client.GetKeyAsync(keyName);

            AssertKeyVaultKeysEqual(ecHsmKey, keyReturned);
        }
        public async Task UpdateEcHsmKeyTags()
        {
            string keyName = Recording.GenerateId();

            CreateEcKeyOptions options = new CreateEcKeyOptions(keyName, hardwareProtected: true)
            {
                Tags =
                {
                    ["A"] = "1",
                    ["B"] = "2",
                },
            };

            KeyVaultKey ecHsmKey = await Client.CreateEcKeyAsync(options);

            RegisterForCleanup(keyName);

            IDictionary <string, string> expectedTags = new Dictionary <string, string>
            {
                ["A"] = "1",
                ["B"] = "2",
            };

            AssertAreEqual(expectedTags, ecHsmKey.Properties.Tags);

            ecHsmKey.Properties.Tags["B"] = "3";
            ecHsmKey.Properties.Tags["C"] = "4";

            ecHsmKey = await Client.UpdateKeyPropertiesAsync(ecHsmKey.Properties);

            expectedTags = new Dictionary <string, string>
            {
                ["A"] = "1",
                ["B"] = "3",
                ["C"] = "4",
            };

            AssertAreEqual(expectedTags, ecHsmKey.Properties.Tags);

            ecHsmKey.Properties.Tags.Clear();
            ecHsmKey.Properties.Tags["D"] = "5";

            ecHsmKey = await Client.UpdateKeyPropertiesAsync(ecHsmKey.Properties);

            expectedTags = new Dictionary <string, string>
            {
                ["D"] = "5",
            };

            AssertAreEqual(expectedTags, ecHsmKey.Properties.Tags);
        }
        public async Task UpdateEcHsmKey()
        {
            string keyName = Recording.GenerateId();

            CreateEcKeyOptions options  = new CreateEcKeyOptions(keyName, hardwareProtected: true);
            KeyVaultKey        ecHsmKey = await Client.CreateEcKeyAsync(options);

            RegisterForCleanup(keyName);

            ecHsmKey.Properties.ExpiresOn = ecHsmKey.Properties.CreatedOn;
            KeyVaultKey updateResult = await Client.UpdateKeyPropertiesAsync(ecHsmKey.Properties, ecHsmKey.KeyOperations);

            AssertKeyVaultKeysEqual(ecHsmKey, updateResult);
        }
Ejemplo n.º 11
0
        public async Task CreateEcWithCurveKey([EnumValues] KeyCurveName curveName)
        {
            var ecCurveKey = new CreateEcKeyOptions(Recording.GenerateId(), hardwareProtected: false)
            {
                CurveName = curveName,
            };

            KeyVaultKey keyNoHsmCurve = await Client.CreateEcKeyAsync(ecCurveKey);

            RegisterForCleanup(keyNoHsmCurve.Name);

            KeyVaultKey keyReturned = await Client.GetKeyAsync(ecCurveKey.Name);

            AssertKeyVaultKeysEqual(keyNoHsmCurve, keyReturned);
        }
        public async Task DeleteEcHsmKey()
        {
            string keyName = Recording.GenerateId();

            CreateEcKeyOptions options  = new CreateEcKeyOptions(keyName, hardwareProtected: true);
            KeyVaultKey        ecHsmKey = await Client.CreateEcKeyAsync(options);

            RegisterForCleanup(keyName);

            DeleteKeyOperation operation = await Client.StartDeleteKeyAsync(keyName);

            DeletedKey deletedKey = await operation.WaitForCompletionAsync();

            Assert.NotNull(deletedKey.DeletedOn);
            Assert.NotNull(deletedKey.RecoveryId);
            Assert.NotNull(deletedKey.ScheduledPurgeDate);
            AssertKeyVaultKeysEqual(ecHsmKey, deletedKey);

            Assert.ThrowsAsync <RequestFailedException>(() => Client.GetKeyAsync(keyName));
        }
        public async Task CreateEcHsmKey()
        {
            string keyName = Recording.GenerateId();

            CreateEcKeyOptions options  = new CreateEcKeyOptions(keyName, hardwareProtected: true);
            KeyVaultKey        ecHsmkey = await Client.CreateEcKeyAsync(options);

            RegisterForCleanup(keyName);

            KeyVaultKey keyReturned = await Client.GetKeyAsync(keyName);

            AssertKeyVaultKeysEqual(ecHsmkey, keyReturned);

            using MemoryStream ms = new();
            await JsonSerializer.SerializeAsync(ms, keyReturned.Key);

            string json = Encoding.UTF8.GetString(ms.ToArray());

            StringAssert.Contains($@"""kid"":""{keyReturned.Id}""", json);
            StringAssert.Contains(@"""kty"":""EC-HSM""", json);
            StringAssert.Contains(@"""crv"":""P-256""", json);
        }
Ejemplo n.º 14
0
        public async Task CreateKeyAsync()
        {
            #region CreateKeyAsync
            // Create a key of any type
            KeyVaultKey key = await client.CreateKeyAsync("key-name", KeyType.Rsa);

            Console.WriteLine(key.Name);
            Console.WriteLine(key.KeyType);

            // Create a software RSA key
            var         rsaCreateKey = new CreateRsaKeyOptions("rsa-key-name", hardwareProtected: false);
            KeyVaultKey rsaKey       = await client.CreateRsaKeyAsync(rsaCreateKey);

            Console.WriteLine(rsaKey.Name);
            Console.WriteLine(rsaKey.KeyType);

            // Create a hardware Elliptic Curve key
            var         echsmkey = new CreateEcKeyOptions("ec-key-name", hardwareProtected: true);
            KeyVaultKey ecKey    = await client.CreateEcKeyAsync(echsmkey);

            Console.WriteLine(ecKey.Name);
            Console.WriteLine(ecKey.KeyType);
            #endregion
        }
        public async Task GetDeletedEcHsmKey()
        {
            string keyName = Recording.GenerateId();

            CreateEcKeyOptions options  = new CreateEcKeyOptions(keyName, hardwareProtected: true);
            KeyVaultKey        ecHsmKey = await Client.CreateEcKeyAsync(options);

            RegisterForCleanup(keyName);

            DeleteKeyOperation operation = await Client.StartDeleteKeyAsync(keyName);

            DeletedKey deletedKey = await operation.WaitForCompletionAsync();

            await WaitForDeletedKey(keyName);

            DeletedKey polledSecret = await Client.GetDeletedKeyAsync(keyName);

            Assert.NotNull(deletedKey.DeletedOn);
            Assert.NotNull(deletedKey.RecoveryId);
            Assert.NotNull(deletedKey.ScheduledPurgeDate);

            AssertKeyVaultKeysEqual(deletedKey, polledSecret);
            AssertKeyVaultKeysEqual(ecHsmKey, polledSecret);
        }
        public async Task CreateEcWithCurveKey([EnumValues] KeyCurveName curveName)
        {
            var ecCurveKey = new CreateEcKeyOptions(Recording.GenerateId(), hardwareProtected: false)
            {
                CurveName = curveName,
            };

            KeyVaultKey keyNoHsmCurve = null;

            try
            {
                keyNoHsmCurve = await Client.CreateEcKeyAsync(ecCurveKey);
            }
            catch (RequestFailedException ex) when(ex.ErrorCode == "KeyCurveNotSupported")
            {
                Assert.Ignore(ex.Message);
            }

            RegisterForCleanup(keyNoHsmCurve.Name);

            KeyVaultKey keyReturned = await Client.GetKeyAsync(ecCurveKey.Name);

            AssertKeyVaultKeysEqual(keyNoHsmCurve, keyReturned);
        }
Ejemplo n.º 17
0
        public async Task GetKeysAsync()
        {
            // Environment variable with the Key Vault endpoint.
            string keyVaultUrl = Environment.GetEnvironmentVariable("AZURE_KEYVAULT_URL");

            // Instantiate a key 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 KeyClient(new Uri(keyVaultUrl), new DefaultAzureCredential());

            // Let's create EC and RSA keys valid for 1 year. If the key
            // already exists in the Key Vault, then a new version of the key is created.
            string rsaKeyName = $"CloudRsaKey-{Guid.NewGuid()}";
            var    rsaKey     = new CreateRsaKeyOptions(rsaKeyName, hardwareProtected: false)
            {
                KeySize   = 2048,
                ExpiresOn = DateTimeOffset.Now.AddYears(1)
            };

            await client.CreateRsaKeyAsync(rsaKey);

            string ecKeyName = $"CloudECKey-{Guid.NewGuid()}";
            var    ecKey     = new CreateEcKeyOptions(ecKeyName, hardwareProtected: false)
            {
                ExpiresOn = DateTimeOffset.Now.AddYears(1)
            };

            await client.CreateEcKeyAsync(ecKey);

            // You need to check the type of keys that already exist in your Key Vault.
            // Let's list the keys and print their types.
            // List operations don't return the actual key, but only properties of the key.
            // So, for each returned key we call GetKey to get the actual key.
            await foreach (KeyProperties key in client.GetPropertiesOfKeysAsync())
            {
                KeyVaultKey keyWithType = await client.GetKeyAsync(key.Name);

                Debug.WriteLine($"Key is returned with name {keyWithType.Name} and type {keyWithType.KeyType}");
            }

            // We need the Cloud RSA key with bigger key size, so you want to update the key in Key Vault to ensure
            // it has the required size.
            // Calling CreateRsaKey on an existing key creates a new version of the key in the Key Vault
            // with the new specified size.
            var newRsaKey = new CreateRsaKeyOptions(rsaKeyName, hardwareProtected: false)
            {
                KeySize   = 4096,
                ExpiresOn = DateTimeOffset.Now.AddYears(1)
            };

            await client.CreateRsaKeyAsync(newRsaKey);

            // You need to check all the different versions Cloud RSA key had previously.
            // Lets print all the versions of this key.
            await foreach (KeyProperties key in client.GetPropertiesOfKeyVersionsAsync(rsaKeyName))
            {
                Debug.WriteLine($"Key's version {key.Version} with name {key.Name}");
            }

            // The Cloud RSA Key and the Cloud EC Key are no longer needed.
            // You need to delete them from the Key Vault.
            DeleteKeyOperation rsaKeyOperation = await client.StartDeleteKeyAsync(rsaKeyName);

            DeleteKeyOperation ecKeyOperation = await client.StartDeleteKeyAsync(ecKeyName);

            // You only need to wait for completion if you want to purge or recover the key.
            await Task.WhenAll(
                rsaKeyOperation.WaitForCompletionAsync().AsTask(),
                ecKeyOperation.WaitForCompletionAsync().AsTask());

            // You can list all the deleted and non-purged keys, assuming Key Vault is soft-delete enabled.
            await foreach (DeletedKey key in client.GetDeletedKeysAsync())
            {
                Debug.WriteLine($"Deleted key's recovery Id {key.RecoveryId}");
            }

            // If the keyvault is soft-delete enabled, then for permanent deletion, deleted keys needs to be purged.
            await Task.WhenAll(
                client.PurgeDeletedKeyAsync(rsaKeyName),
                client.PurgeDeletedKeyAsync(ecKeyName));
        }
        private async Task MigrationGuide()
        {
            #region Snippet:Azure_Security_KeyVault_Keys_Snippets_MigrationGuide_Create
            KeyClient client = new KeyClient(
                new Uri("https://myvault.vault.azure.net"),
                new DefaultAzureCredential());

            CryptographyClient cryptoClient = new CryptographyClient(
                new Uri("https://myvault.vault.azure.net"),
                new DefaultAzureCredential());
            #endregion Snippet:Azure_Security_KeyVault_Keys_Snippets_MigrationGuide_Create

            #region Snippet:Azure_Security_KeyVault_Keys_Snippets_MigrationGuide_CreateWithOptions
            using (HttpClient httpClient = new HttpClient())
            {
                KeyClientOptions options = new KeyClientOptions
                {
                    Transport = new HttpClientTransport(httpClient)
                };

#if SNIPPET
                KeyClient client = new KeyClient(
#else
                client = new KeyClient(
#endif
                    new Uri("https://myvault.vault.azure.net"),
                    new DefaultAzureCredential(),
                    options);

                CryptographyClientOptions cryptoOptions = new CryptographyClientOptions
                {
                    Transport = new HttpClientTransport(httpClient)
                };

#if SNIPPET
                CryptographyClient cryptoClient = new CryptographyClient(
#else
                cryptoClient = new CryptographyClient(
#endif
                    new Uri("https://myvault.vault.azure.net"),
                    new DefaultAzureCredential(),
                    cryptoOptions);
            }
            #endregion Snippet:Azure_Security_KeyVault_Keys_Snippets_MigrationGuide_CreateWithOptions

            {
                #region Snippet:Azure_Security_KeyVault_Keys_Snippets_MigrationGuide_CreateKeys
                // Create RSA key.
                CreateRsaKeyOptions createRsaOptions = new CreateRsaKeyOptions("rsa-key-name")
                {
                    KeySize = 4096
                };

                KeyVaultKey rsaKey = await client.CreateRsaKeyAsync(createRsaOptions);

                // Create Elliptic-Curve key.
                CreateEcKeyOptions createEcOptions = new CreateEcKeyOptions("ec-key-name")
                {
                    CurveName = KeyCurveName.P256
                };

                KeyVaultKey ecKey = await client.CreateEcKeyAsync(createEcOptions);

                #endregion Snippet:Azure_Security_KeyVault_Keys_Snippets_MigrationGuide_CreateKeys
            }

            {
                #region Snippet:Azure_Security_KeyVault_Keys_Snippets_MigrationGuide_ListKeys
                // List all keys asynchronously.
                await foreach (KeyProperties item in client.GetPropertiesOfKeysAsync())
                {
                    KeyVaultKey key = await client.GetKeyAsync(item.Name);
                }

                // List all keys synchronously.
                foreach (KeyProperties item in client.GetPropertiesOfKeys())
                {
                    KeyVaultKey key = client.GetKey(item.Name);
                }
                #endregion Snippet:Azure_Security_KeyVault_Keys_Snippets_MigrationGuide_ListKeys
            }

            {
                #region Snippet:Azure_Security_KeyVault_Keys_Snippets_MigrationGuide_DeleteKey
                // Delete the key.
                DeleteKeyOperation deleteOperation = await client.StartDeleteKeyAsync("key-name");

                // Purge or recover the deleted key if soft delete is enabled.
                if (deleteOperation.Value.RecoveryId != null)
                {
                    // Deleting a key does not happen immediately. Wait for the key to be deleted.
                    DeletedKey deletedKey = await deleteOperation.WaitForCompletionAsync();

                    // Purge the deleted key.
                    await client.PurgeDeletedKeyAsync(deletedKey.Name);

                    // You can also recover the deleted key using StartRecoverDeletedKeyAsync,
                    // which returns RecoverDeletedKeyOperation you can await like DeleteKeyOperation above.
                }
                #endregion Snippet:Azure_Security_KeyVault_Keys_Snippets_MigrationGuide_DeleteKey
            }

            {
                #region Snippet:Azure_Security_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");
                EncryptResult encrypted = await cryptoClient.EncryptAsync(EncryptionAlgorithm.RsaOaep256, plaintext);

                // Decrypt the message.
                DecryptResult decrypted = await cryptoClient.DecryptAsync(encrypted.Algorithm, encrypted.Ciphertext);

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

            {
                #region Snippet:Azure_Security_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.
                    WrapResult wrapped = await cryptoClient.WrapKeyAsync(KeyWrapAlgorithm.RsaOaep256, aes.Key);

                    // Read the IV and the encrypted key from the payload, then unwrap the key.
                    UnwrapResult unwrapped = await cryptoClient.UnwrapKeyAsync(wrapped.Algorithm, wrapped.EncryptedKey);

                    aes.Key = unwrapped.Key;

                    // Decrypt the payload with the symmetric key.
                }
                       #endregion Snippet:Azure_Security_KeyVault_Keys_Snippets_MigrationGuide_Wrap
            }
        }
Ejemplo n.º 19
0
        private PSKeyVaultKey CreateKey(KeyClient client, string keyName, PSKeyVaultKeyAttributes keyAttributes, int?size, string curveName)
        {
            // todo duplicated code with Track2VaultClient.CreateKey
            CreateKeyOptions options;
            bool             isHsm = keyAttributes.KeyType == KeyType.RsaHsm || keyAttributes.KeyType == KeyType.EcHsm;

            if (keyAttributes.KeyType == KeyType.Rsa || keyAttributes.KeyType == KeyType.RsaHsm)
            {
                options = new CreateRsaKeyOptions(keyName, isHsm)
                {
                    KeySize = size
                };
            }
            else if (keyAttributes.KeyType == KeyType.Ec || keyAttributes.KeyType == KeyType.EcHsm)
            {
                options = new CreateEcKeyOptions(keyName, isHsm);
                if (string.IsNullOrEmpty(curveName))
                {
                    (options as CreateEcKeyOptions).CurveName = null;
                }
                else
                {
                    (options as CreateEcKeyOptions).CurveName = new KeyCurveName(curveName);
                }
            }
            else
            {
                options = new CreateKeyOptions();
            }

            // Common key attributes
            options.NotBefore     = keyAttributes.NotBefore;
            options.ExpiresOn     = keyAttributes.Expires;
            options.Enabled       = keyAttributes.Enabled;
            options.Exportable    = keyAttributes.Exportable;
            options.ReleasePolicy = keyAttributes.ReleasePolicy?.ToKeyReleasePolicy();

            if (keyAttributes.KeyOps != null)
            {
                foreach (var keyOp in keyAttributes.KeyOps)
                {
                    options.KeyOperations.Add(new KeyOperation(keyOp));
                }
            }

            if (keyAttributes.Tags != null)
            {
                foreach (DictionaryEntry entry in keyAttributes.Tags)
                {
                    options.Tags.Add(entry.Key.ToString(), entry.Value.ToString());
                }
            }

            if (keyAttributes.KeyType == KeyType.Rsa || keyAttributes.KeyType == KeyType.RsaHsm)
            {
                return(new PSKeyVaultKey(client.CreateRsaKey(options as CreateRsaKeyOptions).Value, _uriHelper, isHsm: true));
            }
            else if (keyAttributes.KeyType == KeyType.Ec || keyAttributes.KeyType == KeyType.EcHsm)
            {
                return(new PSKeyVaultKey(client.CreateEcKey(options as CreateEcKeyOptions).Value, _uriHelper, isHsm: true));
            }
            else if (keyAttributes.KeyType == KeyType.Oct || keyAttributes.KeyType.ToString() == "oct-HSM")
            {
                return(new PSKeyVaultKey(client.CreateKey(keyName, KeyType.Oct, options).Value, _uriHelper, isHsm: true));
            }
            else
            {
                throw new NotSupportedException($"{keyAttributes.KeyType} is not supported");
            }
        }
Ejemplo n.º 20
0
        public async Task SignVerifyAsync()
        {
            // Environment variable with the Key Vault endpoint.
            string keyVaultUrl = Environment.GetEnvironmentVariable("AZURE_KEYVAULT_URL");

            // Instantiate a key client that will be used to create a key. 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 keyClient = new KeyClient(new Uri(keyVaultUrl), new DefaultAzureCredential());

            // First we'll create both a RSA key and an EC which will be used to sign and verify
            string rsaKeyName = $"CloudRsaKey-{Guid.NewGuid()}";
            var    rsaKey     = new CreateRsaKeyOptions(rsaKeyName, hardwareProtected: false)
            {
                KeySize = 2048,
            };

            string ecKeyName = $"CloudEcKey-{Guid.NewGuid()}";
            var    ecKey     = new CreateEcKeyOptions(ecKeyName, hardwareProtected: false)
            {
                CurveName = KeyCurveName.P256K,
            };

            KeyVaultKey cloudRsaKey = await keyClient.CreateRsaKeyAsync(rsaKey);

            Debug.WriteLine($"Key is returned with name {cloudRsaKey.Name} and type {cloudRsaKey.KeyType}");

            KeyVaultKey cloudEcKey = await keyClient.CreateEcKeyAsync(ecKey);

            Debug.WriteLine($"Key is returned with name {cloudEcKey.Name} and type {cloudEcKey.KeyType}");

            // Let's create the CryptographyClient which can perform cryptographic operations with the keys we just created.
            // Again we are using the default Azure credential as above.
            var rsaCryptoClient = new CryptographyClient(cloudRsaKey.Id, new DefaultAzureCredential());

            var ecCryptoClient = new CryptographyClient(cloudEcKey.Id, new DefaultAzureCredential());

            // Next we'll sign some arbitrary data and verify the signatures using the CryptographyClient with both the EC and RSA keys we created.
            byte[] data   = Encoding.UTF8.GetBytes("This is some sample data which we will use to demonstrate sign and verify");
            byte[] digest = null;

            //
            // Signing with the SignAsync and VerifyAsync methods
            //

            // The SignAsync and VerifyAsync methods expect a precalculated digest, and the digest needs to be calculated using the hash algorithm which matches the
            // singature algorithm being used. SHA256 is the hash algorithm used for both RS256 and ES256K which are the algorithms we'll be using in this sample
            using (HashAlgorithm hashAlgo = SHA256.Create())
            {
                digest = hashAlgo.ComputeHash(data);
            }

            // Get the signature for the computed digest with both keys. Note that the signature algorithm specified must be a valid algorithm for the key type,
            // and for EC keys the algorithm must also match the curve of the key
            SignResult rsaSignResult = await rsaCryptoClient.SignAsync(SignatureAlgorithm.RS256, digest);

            Debug.WriteLine($"Signed digest using the algorithm {rsaSignResult.Algorithm}, with key {rsaSignResult.KeyId}. The resulting signature is {Convert.ToBase64String(rsaSignResult.Signature)}");

            SignResult ecSignResult = await ecCryptoClient.SignAsync(SignatureAlgorithm.ES256K, digest);

            Debug.WriteLine($"Signed digest using the algorithm {ecSignResult.Algorithm}, with key {ecSignResult.KeyId}. The resulting signature is {Convert.ToBase64String(ecSignResult.Signature)}");

            // Verify the signatures
            VerifyResult rsaVerifyResult = await rsaCryptoClient.VerifyAsync(SignatureAlgorithm.RS256, digest, rsaSignResult.Signature);

            Debug.WriteLine($"Verified the signature using the algorithm {rsaVerifyResult.Algorithm}, with key {rsaVerifyResult.KeyId}. Signature is valid: {rsaVerifyResult.IsValid}");

            VerifyResult ecVerifyResult = await ecCryptoClient.VerifyAsync(SignatureAlgorithm.ES256K, digest, ecSignResult.Signature);

            Debug.WriteLine($"Verified the signature using the algorithm {ecVerifyResult.Algorithm}, with key {ecVerifyResult.KeyId}. Signature is valid: {ecVerifyResult.IsValid}");

            //
            // Signing with the SignDataAsync and VerifyDataAsync methods
            //

            // The SignDataAsync and VerifyDataAsync methods take the raw data which is to be signed.  The calculate the digest for the user so there is no need to compute the digest

            // Get the signature for the data with both keys. Note that the signature algorithm specified must be a valid algorithm for the key type,
            // and for EC keys the algorithm must also match the curve of the key
            SignResult rsaSignDataResult = await rsaCryptoClient.SignDataAsync(SignatureAlgorithm.RS256, data);

            Debug.WriteLine($"Signed data using the algorithm {rsaSignDataResult.Algorithm}, with key {rsaSignDataResult.KeyId}. The resulting signature is {Convert.ToBase64String(rsaSignDataResult.Signature)}");

            SignResult ecSignDataResult = await ecCryptoClient.SignDataAsync(SignatureAlgorithm.ES256K, data);

            Debug.WriteLine($"Signed data using the algorithm {ecSignDataResult.Algorithm}, with key {ecSignDataResult.KeyId}. The resulting signature is {Convert.ToBase64String(ecSignDataResult.Signature)}");

            // Verify the signatures
            VerifyResult rsaVerifyDataResult = await rsaCryptoClient.VerifyDataAsync(SignatureAlgorithm.RS256, data, rsaSignDataResult.Signature);

            Debug.WriteLine($"Verified the signature using the algorithm {rsaVerifyDataResult.Algorithm}, with key {rsaVerifyDataResult.KeyId}. Signature is valid: {rsaVerifyDataResult.IsValid}");

            VerifyResult ecVerifyDataResult = await ecCryptoClient.VerifyDataAsync(SignatureAlgorithm.ES256K, data, ecSignDataResult.Signature);

            Debug.WriteLine($"Verified the signature using the algorithm {ecVerifyDataResult.Algorithm}, with key {ecVerifyDataResult.KeyId}. Signature is valid: {ecVerifyDataResult.IsValid}");

            // The Cloud Keys are no longer needed, need to delete them from the Key Vault.
            DeleteKeyOperation rsaKeyOperation = await keyClient.StartDeleteKeyAsync(rsaKeyName);

            DeleteKeyOperation ecKeyOperation = await keyClient.StartDeleteKeyAsync(ecKeyName);

            // To ensure the key is deleted on server before we try to purge it.
            Task.WaitAll(
                rsaKeyOperation.WaitForCompletionAsync().AsTask(),
                ecKeyOperation.WaitForCompletionAsync().AsTask());

            // If the keyvault is soft-delete enabled, then for permanent deletion, deleted keys needs to be purged.
            Task.WaitAll(
                keyClient.PurgeDeletedKeyAsync(rsaKeyName),
                keyClient.PurgeDeletedKeyAsync(ecKeyName));
        }
Ejemplo n.º 21
0
        public void SignVerifySync()
        {
#if NET461
            Assert.Ignore("Using CryptographyClient with EC keys is not supported on .NET Framework 4.6.1.");
#endif

            // Environment variable with the Key Vault endpoint.
            string keyVaultUrl = TestEnvironment.KeyVaultUrl;

            #region Snippet:KeysSample5KeyClient
            var keyClient = new KeyClient(new Uri(keyVaultUrl), new DefaultAzureCredential());
            #endregion

            #region Snippet:KeysSample5CreateKey
            string rsaKeyName    = $"CloudRsaKey-{Guid.NewGuid()}";
            var    rsaKeyOptions = new CreateRsaKeyOptions(rsaKeyName, hardwareProtected: false)
            {
                KeySize = 2048,
            };

            string ecKeyName    = $"CloudEcKey-{Guid.NewGuid()}";
            var    ecKeyOptions = new CreateEcKeyOptions(ecKeyName, hardwareProtected: false)
            {
                CurveName = KeyCurveName.P256K,
            };

            KeyVaultKey rsaKey = keyClient.CreateRsaKey(rsaKeyOptions);
            Debug.WriteLine($"Key is returned with name {rsaKey.Name} and type {rsaKey.KeyType}");

            KeyVaultKey ecKey = keyClient.CreateEcKey(ecKeyOptions);
            Debug.WriteLine($"Key is returned with name {ecKey.Name} and type {ecKey.KeyType}");
            #endregion

            #region Snippet:KeysSample5CryptographyClient
            var rsaCryptoClient = new CryptographyClient(rsaKey.Id, new DefaultAzureCredential());

            var ecCryptoClient = new CryptographyClient(ecKey.Id, new DefaultAzureCredential());
            #endregion

            #region Snippet:KeysSample5SignKey
            byte[] data   = Encoding.UTF8.GetBytes("This is some sample data which we will use to demonstrate sign and verify");
            byte[] digest = null;

            using (HashAlgorithm hashAlgo = SHA256.Create())
            {
                digest = hashAlgo.ComputeHash(data);
            }

            SignResult rsaSignResult = rsaCryptoClient.Sign(SignatureAlgorithm.RS256, digest);
            Debug.WriteLine($"Signed digest using the algorithm {rsaSignResult.Algorithm}, with key {rsaSignResult.KeyId}. The resulting signature is {Convert.ToBase64String(rsaSignResult.Signature)}");

            SignResult ecSignResult = ecCryptoClient.Sign(SignatureAlgorithm.ES256K, digest);
            Debug.WriteLine($"Signed digest using the algorithm {ecSignResult.Algorithm}, with key {ecSignResult.KeyId}. The resulting signature is {Convert.ToBase64String(ecSignResult.Signature)}");
            #endregion

            #region Snippet:KeysSample5VerifySign
            VerifyResult rsaVerifyResult = rsaCryptoClient.Verify(SignatureAlgorithm.RS256, digest, rsaSignResult.Signature);
            Debug.WriteLine($"Verified the signature using the algorithm {rsaVerifyResult.Algorithm}, with key {rsaVerifyResult.KeyId}. Signature is valid: {rsaVerifyResult.IsValid}");

            VerifyResult ecVerifyResult = ecCryptoClient.Verify(SignatureAlgorithm.ES256K, digest, ecSignResult.Signature);
            Debug.WriteLine($"Verified the signature using the algorithm {ecVerifyResult.Algorithm}, with key {ecVerifyResult.KeyId}. Signature is valid: {ecVerifyResult.IsValid}");
            #endregion

            #region Snippet:KeysSample5SignKeyWithSignData
            SignResult rsaSignDataResult = rsaCryptoClient.SignData(SignatureAlgorithm.RS256, data);
            Debug.WriteLine($"Signed data using the algorithm {rsaSignDataResult.Algorithm}, with key {rsaSignDataResult.KeyId}. The resulting signature is {Convert.ToBase64String(rsaSignDataResult.Signature)}");

            SignResult ecSignDataResult = ecCryptoClient.SignData(SignatureAlgorithm.ES256K, data);
            Debug.WriteLine($"Signed data using the algorithm {ecSignDataResult.Algorithm}, with key {ecSignDataResult.KeyId}. The resulting signature is {Convert.ToBase64String(ecSignDataResult.Signature)}");
            #endregion

            #region Snippet:KeysSample5VerifyKeyWithData
            VerifyResult rsaVerifyDataResult = rsaCryptoClient.VerifyData(SignatureAlgorithm.RS256, data, rsaSignDataResult.Signature);
            Debug.WriteLine($"Verified the signature using the algorithm {rsaVerifyDataResult.Algorithm}, with key {rsaVerifyDataResult.KeyId}. Signature is valid: {rsaVerifyDataResult.IsValid}");

            VerifyResult ecVerifyDataResult = ecCryptoClient.VerifyData(SignatureAlgorithm.ES256K, data, ecSignDataResult.Signature);
            Debug.WriteLine($"Verified the signature using the algorithm {ecVerifyDataResult.Algorithm}, with key {ecVerifyDataResult.KeyId}. Signature is valid: {ecVerifyDataResult.IsValid}");
            #endregion

            #region Snippet:KeysSample5DeleteKeys
            DeleteKeyOperation rsaKeyOperation = keyClient.StartDeleteKey(rsaKeyName);
            DeleteKeyOperation ecKeyOperation  = keyClient.StartDeleteKey(ecKeyName);

            // You only need to wait for completion if you want to purge or recover the key.
            while (!rsaKeyOperation.HasCompleted || !ecKeyOperation.HasCompleted)
            {
                Thread.Sleep(2000);

                rsaKeyOperation.UpdateStatus();
                ecKeyOperation.UpdateStatus();
            }
            #endregion

            // If the keyvault is soft-delete enabled, then for permanent deletion, deleted keys needs to be purged.
            keyClient.PurgeDeletedKey(rsaKeyName);
            keyClient.PurgeDeletedKey(ecKeyName);
        }
Ejemplo n.º 22
0
        public void GetKeysSync()
        {
            // Environment variable with the Key Vault endpoint.
            string keyVaultUrl = TestEnvironment.KeyVaultUrl;

            #region Snippet:KeysSample3KeyClient
            var client = new KeyClient(new Uri(keyVaultUrl), new DefaultAzureCredential());
            #endregion

            #region Snippet:KeysSample3CreateKey
            string rsaKeyName = $"CloudRsaKey-{Guid.NewGuid()}";
            var    rsaKey     = new CreateRsaKeyOptions(rsaKeyName, hardwareProtected: false)
            {
                KeySize   = 2048,
                ExpiresOn = DateTimeOffset.Now.AddYears(1)
            };

            client.CreateRsaKey(rsaKey);

            string ecKeyName = $"CloudECKey-{Guid.NewGuid()}";
            var    ecKey     = new CreateEcKeyOptions(ecKeyName, hardwareProtected: false)
            {
                ExpiresOn = DateTimeOffset.Now.AddYears(1)
            };

            client.CreateEcKey(ecKey);
            #endregion

            #region Snippet:KeysSample3ListKeys
            IEnumerable <KeyProperties> keys = client.GetPropertiesOfKeys();
            foreach (KeyProperties key in keys)
            {
#if !SNIPPET
                if (key.Managed)
                {
                    continue;
                }
#endif
                KeyVaultKey keyWithType = client.GetKey(key.Name);
                Debug.WriteLine($"Key is returned with name {keyWithType.Name} and type {keyWithType.KeyType}");
            }
            #endregion

            #region Snippet:KeysSample3UpdateKey
            var newRsaKey = new CreateRsaKeyOptions(rsaKeyName, hardwareProtected: false)
            {
                KeySize   = 4096,
                ExpiresOn = DateTimeOffset.Now.AddYears(1)
            };

            client.CreateRsaKey(newRsaKey);
            #endregion

            #region Snippet:KeysSample3ListKeyVersions
            IEnumerable <KeyProperties> keysVersions = client.GetPropertiesOfKeyVersions(rsaKeyName);
            foreach (KeyProperties key in keysVersions)
            {
                Debug.WriteLine($"Key's version {key.Version} with name {key.Name}");
            }
            #endregion

            #region Snippet:KeysSample3DeletedKeys
            DeleteKeyOperation rsaKeyOperation = client.StartDeleteKey(rsaKeyName);
            DeleteKeyOperation ecKeyOperation  = client.StartDeleteKey(ecKeyName);

            // You only need to wait for completion if you want to purge or recover the key.
            while (!rsaKeyOperation.HasCompleted || !ecKeyOperation.HasCompleted)
            {
                Thread.Sleep(2000);

                rsaKeyOperation.UpdateStatus();
                ecKeyOperation.UpdateStatus();
            }
            #endregion

            #region Snippet:KeysSample3ListDeletedKeys
            IEnumerable <DeletedKey> keysDeleted = client.GetDeletedKeys();
            foreach (DeletedKey key in keysDeleted)
            {
                Debug.WriteLine($"Deleted key's recovery Id {key.RecoveryId}");
            }
            #endregion

            // You only need to wait for completion if you want to purge or recover the key.
            // If the keyvault is soft-delete enabled, then for permanent deletion, deleted keys needs to be purged.
            client.PurgeDeletedKey(rsaKeyName);
            client.PurgeDeletedKey(ecKeyName);
        }