public async Task WrapUnwrapRoundTrip([Fields] KeyWrapAlgorithm algorithm)
        {
            Key key = await CreateTestKey(algorithm);

            RegisterForCleanup(key.Name);

            CryptographyClient cryptoClient = GetCryptoClient(key.Id, forceRemote: true);

            byte[] data = new byte[32];
            Recording.Random.NextBytes(data);

            WrapResult encResult = await cryptoClient.WrapKeyAsync(algorithm, data);

            Assert.AreEqual(algorithm, encResult.Algorithm);
            Assert.AreEqual(key.Id, encResult.KeyId);
            Assert.IsNotNull(encResult.EncryptedKey);

            UnwrapResult decResult = await cryptoClient.UnwrapKeyAsync(algorithm, encResult.EncryptedKey);

            Assert.AreEqual(algorithm, decResult.Algorithm);
            Assert.AreEqual(key.Id, decResult.KeyId);
            Assert.IsNotNull(decResult.Key);

            CollectionAssert.AreEqual(data, decResult.Key);
        }
Ejemplo n.º 2
0
        public async Task AesKwWrapUnwrapRoundTrip([EnumValues(
                                                        nameof(KeyWrapAlgorithm.A128KW),
                                                        nameof(KeyWrapAlgorithm.A192KW),
                                                        nameof(KeyWrapAlgorithm.A256KW))] KeyWrapAlgorithm algorithm)
        {
            KeyVaultKey key = await CreateTestKey(algorithm);

            RegisterForCleanup(key.Name);

            CryptographyClient remoteClient = GetCryptoClient(key.Id, forceRemote: true);

            byte[] plaintext = new byte[32];
            Recording.Random.NextBytes(plaintext);

            WrapResult encrypted = await remoteClient.WrapKeyAsync(algorithm, plaintext);

            Assert.AreEqual(algorithm, encrypted.Algorithm);
            Assert.AreEqual(key.Id, encrypted.KeyId);
            Assert.IsNotNull(encrypted.EncryptedKey);

            UnwrapResult decrypted = await remoteClient.UnwrapKeyAsync(algorithm, encrypted.EncryptedKey);

            Assert.AreEqual(algorithm, decrypted.Algorithm);
            Assert.AreEqual(key.Id, decrypted.KeyId);
            Assert.IsNotNull(decrypted.Key);

            CollectionAssert.AreEqual(plaintext, decrypted.Key);
        }
Ejemplo n.º 3
0
        public override async Task RunAsync(CancellationToken cancellationToken)
        {
            UnwrapResult result = await CryptographyClient.UnwrapKeyAsync(s_algorithm, _encryptedKey);

            byte[] key = result.Key;

#if DEBUG
            Assert.AreEqual(_aes.Key, key);
#endif
        }
Ejemplo n.º 4
0
        public override void Run(CancellationToken cancellationToken)
        {
            UnwrapResult result = CryptographyClient.UnwrapKey(KeyWrapAlgorithm.RsaOaep256, _encryptedKey);

            byte[] key = result.Key;

#if DEBUG
            Assert.AreEqual(_aes.Key, key);
#endif
        }
        public async Task WrapKeyUnwrapKeyRoundtrip([EnumValues(Exclude = new[] { nameof(KeyWrapAlgorithm.RsaOaep256) })] KeyWrapAlgorithm algorithm)
        {
            JsonWebKey jwk = KeyUtilities.CreateKey(algorithm, includePrivateParameters: true);
            LocalCryptographyClient client = CreateClient <LocalCryptographyClient>(jwk);

            WrapResult wrapped = await client.WrapKeyAsync(algorithm, TestKey);

            UnwrapResult unwrapped = await client.UnwrapKeyAsync(algorithm, wrapped.EncryptedKey);

            CollectionAssert.AreEqual(TestKey, unwrapped.Key);
        }
Ejemplo n.º 6
0
        public async Task <IActionResult> Unwrap(EncryptDto toDecrypt)
        {
            KeyVaultKey key = await _keyClient.GetKeyAsync("test");

            CryptographyClient crypto     = new CryptographyClient(key.Id, new DefaultAzureCredential());
            KeyVaultSecret     wrappedKey = await _secretClient.GetSecretAsync(toDecrypt.Name);

            UnwrapResult result = await crypto.UnwrapKeyAsync(KeyWrapAlgorithm.RsaOaep256, Convert.FromBase64String(wrappedKey.Value));

            return(Ok(Encoding.UTF8.GetString(result.Key)));
        }
Ejemplo n.º 7
0
        public void WrapUnwrapSync()
        {
            // Environment variable with the Key Vault endpoint.
            string keyVaultUrl = Environment.GetEnvironmentVariable("AZURE_KEYVAULT_URL");

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

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

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

            #region Snippet:KeysSample6CryptographyClient
            var cryptoClient = new CryptographyClient(cloudRsaKey.Id, new DefaultAzureCredential());
            #endregion

            #region Snippet:KeysSample6GenerateKey
            byte[] keyData = AesManaged.Create().Key;
            Debug.WriteLine($"Generated Key: {Convert.ToBase64String(keyData)}");
            #endregion

            #region Snippet:KeysSample6WrapKey
            WrapResult wrapResult = cryptoClient.WrapKey(KeyWrapAlgorithm.RsaOaep, keyData);
            Debug.WriteLine($"Encrypted data using the algorithm {wrapResult.Algorithm}, with key {wrapResult.KeyId}. The resulting encrypted data is {Convert.ToBase64String(wrapResult.EncryptedKey)}");
            #endregion

            #region Snippet:KeysSample6UnwrapKey
            UnwrapResult unwrapResult = cryptoClient.UnwrapKey(KeyWrapAlgorithm.RsaOaep, wrapResult.EncryptedKey);
            Debug.WriteLine($"Decrypted data using the algorithm {unwrapResult.Algorithm}, with key {unwrapResult.KeyId}. The resulting decrypted data is {Encoding.UTF8.GetString(unwrapResult.Key)}");
            #endregion

            #region Snippet:KeysSample6DeleteKey
            DeleteKeyOperation operation = keyClient.StartDeleteKey(rsaKeyName);

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

                operation.UpdateStatus();
            }
            #endregion

            // If the keyvault is soft-delete enabled, then for permanent deletion, deleted key needs to be purged.
            keyClient.PurgeDeletedKey(rsaKeyName);
        }
        public void WrapUnwrapSync()
        {
            // 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 create a RSA key which will be used to wrap and unwrap another key
            string rsaKeyName = $"CloudRsaKey-{Guid.NewGuid()}";
            var    rsaKey     = new CreateRsaKeyOptions(rsaKeyName, hardwareProtected: false)
            {
                KeySize = 2048,
            };

            KeyVaultKey cloudRsaKey = keyClient.CreateRsaKey(rsaKey);

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

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

            // Next we'll generate a symmetric key which we will wrap
            byte[] keyData = AesManaged.Create().Key;
            Debug.WriteLine($"Generated Key: {Convert.ToBase64String(keyData)}");

            // Wrap the key using RSAOAEP with the created key.
            WrapResult wrapResult = cryptoClient.WrapKey(KeyWrapAlgorithm.RsaOaep, keyData);

            Debug.WriteLine($"Encrypted data using the algorithm {wrapResult.Algorithm}, with key {wrapResult.KeyId}. The resulting encrypted data is {Convert.ToBase64String(wrapResult.EncryptedKey)}");

            // Now unwrap the encrypted key. Note that the same algorithm must always be used for both wrap and unwrap
            UnwrapResult unwrapResult = cryptoClient.UnwrapKey(KeyWrapAlgorithm.RsaOaep, wrapResult.EncryptedKey);

            Debug.WriteLine($"Decrypted data using the algorithm {unwrapResult.Algorithm}, with key {unwrapResult.KeyId}. The resulting decrypted data is {Encoding.UTF8.GetString(unwrapResult.Key)}");

            // The Cloud RSA Key is no longer needed, need to delete it from the Key Vault.
            DeleteKeyOperation operation = keyClient.StartDeleteKey(rsaKeyName);

            // To ensure the key is deleted on server before we try to purge it.
            while (!operation.HasCompleted)
            {
                Thread.Sleep(2000);

                operation.UpdateStatus();
            }

            // If the keyvault is soft-delete enabled, then for permanent deletion, deleted key needs to be purged.
            keyClient.PurgeDeletedKey(rsaKeyName);
        }
Ejemplo n.º 9
0
        public async Task WrapUnwrapAsync()
        {
            // 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 create a RSA key which will be used to wrap and unwrap another key
            string rsaKeyName = $"CloudRsaKey-{Guid.NewGuid()}";
            var    rsaKey     = new RsaKeyCreateOptions(rsaKeyName, hsm: false, keySize: 2048);

            Key cloudRsaKey = await keyClient.CreateRsaKeyAsync(rsaKey);

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

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

            // Next we'll generate a symmetric key which we will wrap
            byte[] keyData = AesManaged.Create().Key;
            Debug.WriteLine($"Generated Key: {Convert.ToBase64String(keyData)}");

            // Wrap the key using RSAOAEP with the created key.
            WrapResult wrapResult = await cryptoClient.WrapKeyAsync(KeyWrapAlgorithm.RSAOAEP, keyData);

            Debug.WriteLine($"Encrypted data using the algorithm {wrapResult.Algorithm}, with key {wrapResult.KeyId}. The resulting encrypted data is {Convert.ToBase64String(wrapResult.EncryptedKey)}");

            // Now unwrap the encrypted key. Note that the same algorithm must always be used for both wrap and unwrap
            UnwrapResult unwrapResult = await cryptoClient.UnwrapKeyAsync(KeyWrapAlgorithm.RSAOAEP, wrapResult.EncryptedKey);

            Debug.WriteLine($"Decrypted data using the algorithm {unwrapResult.Algorithm}, with key {unwrapResult.KeyId}. The resulting decrypted data is {Encoding.UTF8.GetString(unwrapResult.Key)}");

            // The Cloud RSA Key is no longer needed, need to delete it from the Key Vault.
            await keyClient.DeleteKeyAsync(rsaKeyName);

            // To ensure key is deleted on server side.
            Assert.IsTrue(await WaitForDeletedKeyAsync(keyClient, rsaKeyName));

            // If the keyvault is soft-delete enabled, then for permanent deletion, deleted key needs to be purged.
            await keyClient.PurgeDeletedKeyAsync(rsaKeyName);
        }
            /// <summary>
            /// Simulates UnwrapKeyAsync of KeyVault SDK.
            /// </summary>
            /// <param name="algorithm"> Encryption Algorithm </param>
            /// <param name="encryptedKey"> Key to be unwrapped </param>
            /// <param name="cancellationToken"> cancellation token </param>
            /// <returns></returns>
            public override Task <UnwrapResult> UnwrapKeyAsync(KeyWrapAlgorithm algorithm, byte[] encryptedKey, CancellationToken cancellationToken = default)
            {
                if (encryptedKey.IsNullOrEmpty())
                {
                    throw new ArgumentNullException("Key is Null.");
                }

                byte[] unwrappedKey = this.Decrypt(encryptedKey, this.secretkey, this.iv);

                // simulate a null unwrapped key.
                if (this.keyId.ToString().Contains(KeyVaultTestConstants.ValidateNullUnwrappedKey))
                {
                    unwrappedKey = null;
                }

                string       keyid            = "12345678910";
                UnwrapResult mockUnwrapResult = CryptographyModelFactory.UnwrapResult(keyId: keyid, key: unwrappedKey, algorithm: KeyVaultConstants.RsaOaep256);

                return(Task.FromResult(mockUnwrapResult));
            }
        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);

            Secret secret = new Secret(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);
        }
        public async Task ResolveKeyId()
        {
            string keyName = Recording.GenerateId();

            Key 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);
        }
        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.º 14
0
 static UnwrapResult()
 {
     instance = new UnwrapResult();
 }
Ejemplo n.º 15
0
 public PSKeyOperationResult(UnwrapResult unwrapResult)
 {
     this.KeyId     = unwrapResult.KeyId;
     this.Result    = System.Text.Encoding.Default.GetString(unwrapResult.Key);
     this.Algorithm = unwrapResult.Algorithm.ToString();
 }
Ejemplo n.º 16
0
 static UnwrapResult()
 {
     instance = new UnwrapResult();
 }