Exemplo n.º 1
0
        public async Task ResolveKeyId()
        {
            string keyName = Recording.GenerateId();

            KeyVaultKey key = await Client.CreateKeyAsync(keyName, KeyType.Rsa);

            RegisterForCleanup(keyName);

            CryptographyClient cryptoClient = await Resolver.ResolveAsync(key.Id);

            cryptoClient = InstrumentClient(cryptoClient);

            Assert.IsNotNull(cryptoClient);

            byte[] toWrap = new byte[32];

            Recording.Random.NextBytes(toWrap);

            WrapResult wrapResult = await cryptoClient.WrapKeyAsync(KeyWrapAlgorithm.RsaOaep, toWrap);

            UnwrapResult unwrapResult = await cryptoClient.UnwrapKeyAsync(KeyWrapAlgorithm.RsaOaep, wrapResult.EncryptedKey);

            CollectionAssert.AreEqual(toWrap, unwrapResult.Key);
        }
Exemplo n.º 2
0
        public async Task ResolveSecretId()
        {
            SecretClient secretClient = GetSecretClient();

            // using Random to create a key so it is consistent for the recording. IRL this would be
            // a major security no no.  We would need to use AES.Create or RNGCryptoServiceProvider
            byte[] key = new byte[32];

            Recording.Random.NextBytes(key);

            KeyVaultSecret secret = new KeyVaultSecret(Recording.GenerateId(), Base64Url.Encode(key))
            {
                Properties =
                {
                    ContentType = "application/octet-stream"
                }
            };

            secret = await secretClient.SetSecretAsync(secret);

            CryptographyClient cryptoClient = await Resolver.ResolveAsync(secret.Id);

            cryptoClient = InstrumentClient(cryptoClient);

            Assert.IsNotNull(cryptoClient);

            byte[] toWrap = new byte[32];

            Recording.Random.NextBytes(toWrap);

            WrapResult wrapResult = await cryptoClient.WrapKeyAsync(KeyWrapAlgorithm.A256KW, toWrap);

            UnwrapResult unwrapResult = await cryptoClient.UnwrapKeyAsync(KeyWrapAlgorithm.A256KW, wrapResult.EncryptedKey);

            CollectionAssert.AreEqual(toWrap, unwrapResult.Key);
        }
        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
            }
        }
        public async Task ShouldNotRequireGetPermissionForKey()
        {
            // Test for https://github.com/Azure/azure-sdk-for-net/issues/11574
            MockTransport transport = new MockTransport(request => new MockResponse((int)HttpStatusCode.Forbidden, nameof(HttpStatusCode.Forbidden)));

            KeyResolver        resolver = GetResolver(transport);
            CryptographyClient client   = await resolver.ResolveAsync(new Uri("https://mock.vault.azure.net/keys/mock-key"));

            RequestFailedException ex = Assert.ThrowsAsync <RequestFailedException>(() => client.UnwrapKeyAsync(KeyWrapAlgorithm.A256KW, new byte[] { 0, 1, 2, 3 }));

            Assert.AreEqual((int)HttpStatusCode.Forbidden, ex.Status);
        }
        public async Task UnwrapKeyRequiresPrivateKey()
        {
            JsonWebKey         jwk    = CreateKey(KeyType.Rsa, keyOps: new[] { KeyOperation.WrapKey, KeyOperation.UnwrapKey });
            CryptographyClient client = CreateClient <CryptographyClient>(jwk);

            WrapResult wrapped = await client.WrapKeyAsync(KeyWrapAlgorithm.RsaOaep, TestData);

            Assert.ThrowsAsync(new InstanceOfTypeConstraint(typeof(CryptographicException)), async() => await client.UnwrapKeyAsync(KeyWrapAlgorithm.RsaOaep, wrapped.EncryptedKey));
        }