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

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

            RegisterForCleanup(key.Name);

            key.Properties.Enabled = false;
            KeyVaultKey updateResult = await Client.UpdateKeyPropertiesAsync(key.Properties, key.KeyOperations);

            KeyVaultKey keyReturned = await Client.GetKeyAsync(keyName);

            AssertKeyVaultKeysEqual(keyReturned, updateResult);
        }
Пример #2
0
        public void UpdateKey()
        {
            #region Snippet:UpdateKey
            KeyVaultKey key = client.CreateKey("key-name", KeyType.Rsa);

            // You can specify additional application-specific metadata in the form of tags.
            key.Properties.Tags["foo"] = "updated tag";

            KeyVaultKey updatedKey = client.UpdateKeyProperties(key.Properties);

            Console.WriteLine(updatedKey.Name);
            Console.WriteLine(updatedKey.Properties.Version);
            Console.WriteLine(updatedKey.Properties.UpdatedOn);
            #endregion
        }
        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 CreateRsaWithSizeKey()
        {
            var rsaSizeKey = new CreateRsaKeyOptions(name: Recording.GenerateId(), hardwareProtected: false)
            {
                KeySize = 2048,
            };

            KeyVaultKey key = await Client.CreateRsaKeyAsync(rsaSizeKey);

            RegisterForCleanup(key.Name);

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

            AssertKeyVaultKeysEqual(key, keyReturned);
        }
        private (CryptographyClient, ICryptographyProvider) GetCryptoClient(KeyVaultKey key)
        {
            CryptographyClientOptions options     = InstrumentClientOptions(new CryptographyClientOptions((CryptographyClientOptions.ServiceVersion)_serviceVersion));
            CryptographyClient        client      = new CryptographyClient(key, TestEnvironment.Credential, options);
            CryptographyClient        clientProxy = InstrumentClient(client);

            ICryptographyProvider remoteClientProxy = null;

            if (client.RemoteClient is RemoteCryptographyClient remoteClient)
            {
                remoteClientProxy = InstrumentClient(remoteClient);
            }

            return(clientProxy, remoteClientProxy);
        }
Пример #6
0
        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.
            keyClient.DeleteKey(rsaKeyName);

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

            // If the keyvault is soft-delete enabled, then for permanent deletion, deleted key needs to be purged.
            keyClient.PurgeDeletedKey(rsaKeyName);
        }
        public async Task EncryptDecryptAsync()
        {
            // Environment variable with the Key Vault endpoint.
            string keyVaultUrl = TestEnvironment.KeyVaultUrl;

            // 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 create a RSA key which will be used to encrypt and decrypt
            string rsaKeyName = $"CloudRsaKey-{Guid.NewGuid()}";
            var    rsaKey     = new CreateRsaKeyOptions(rsaKeyName, hardwareProtected: false)
            {
                KeySize = 2048,
            };

            KeyVaultKey cloudRsaKey = await keyClient.CreateRsaKeyAsync(rsaKey);

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

            // Then we create the CryptographyClient which can perform cryptographic operations with the key we just created using the same credential created above.
            var cryptoClient = new CryptographyClient(cloudRsaKey.Id, new DefaultAzureCredential());

            // Next we'll encrypt some arbitrary plain text with the key using the CryptographyClient. Note that RSA encryption
            // algorithms have no chaining so they can only encrypt a single block of plaintext securely. For RSAOAEP this can be
            // calculated as (keysize / 8) - 42, or in our case (2048 / 8) - 42 = 214 bytes.
            byte[] plaintext = Encoding.UTF8.GetBytes("A single block of plaintext");

            // First encrypt the data using RSAOAEP with the created key.
            EncryptResult encryptResult = await cryptoClient.EncryptAsync(EncryptionAlgorithm.RsaOaep, plaintext);

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

            // Now decrypt the encrypted data. Note that the same algorithm must always be used for both encrypt and decrypt
            DecryptResult decryptResult = await cryptoClient.DecryptAsync(EncryptionAlgorithm.RsaOaep, encryptResult.Ciphertext);

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

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

            // You only need to wait for completion if you want to purge or recover the key.
            await operation.WaitForCompletionAsync();

            // If the keyvault is soft-delete enabled, then for permanent deletion, deleted key needs to be purged.
            await keyClient.PurgeDeletedKeyAsync(rsaKeyName);
        }
Пример #8
0
        public async Task BackupAndRestoreSampleAsync()
        {
            var blobStorageUrl    = TestEnvironment.StorageUri;
            var blobContainerName = BlobContainerName;
            var sasToken          = "?" + SasToken;

            // Create a Uri with the storage container.
            UriBuilder builder = new UriBuilder(blobStorageUrl)
            {
                Path = blobContainerName,
            };

            // Make sure we have a key to back up and restore.
            KeyVaultKey key = await KeyClient.CreateKeyAsync(Recording.GenerateId(), KeyType.Oct);

            string keyName = key.Name;

            RegisterKeyForCleanup(keyName);

            // Start the backup.
            KeyVaultBackupOperation backupOperation = await Client.StartBackupAsync(builder.Uri, sasToken);

            // Wait for completion of the BackupOperation.
            Response <KeyVaultBackupResult> backupResult = await backupOperation.WaitForCompletionAsync();

            await WaitForOperationAsync();

            // Get the Uri for the location of you backup blob.
            Uri folderUri = backupResult.Value.FolderUri;

            Assert.That(folderUri, Is.Not.Null);
            Assert.That(backupOperation.HasValue, Is.True);

            #region Snippet:SelectiveRestoreAsync
#if SNIPPET
            string keyName = "<key name to restore>";
#endif

            // Start the restore for a specific key that was previously backed up using the backupBlobUri returned from a previous BackupOperation.
            KeyVaultSelectiveKeyRestoreOperation restoreOperation = await Client.StartSelectiveRestoreAsync(keyName, folderUri, sasToken);

            // Wait for completion of the RestoreOperation.
            KeyVaultSelectiveKeyRestoreResult restoreResult = await restoreOperation.WaitForCompletionAsync();

            #endregion

            Assert.That(restoreOperation.HasValue, Is.True);
            Assert.That(restoreResult.StartTime, Is.Not.EqualTo(default));
Пример #9
0
        private (CryptographyClient, ICryptographyProvider) GetCryptoClient(KeyVaultKey key, TestRecording recording = null)
        {
            recording ??= Recording;

            CryptographyClient client      = new CryptographyClient(key, recording.GetCredential(new DefaultAzureCredential()), recording.InstrumentClientOptions(new CryptographyClientOptions()));
            CryptographyClient clientProxy = InstrumentClient(client);

            ICryptographyProvider remoteClientProxy = null;

            if (client.RemoteClient is RemoteCryptographyClient remoteClient)
            {
                remoteClientProxy = InstrumentClient(remoteClient);
            }

            return(clientProxy, remoteClientProxy);
        }
        public async Task UpdateRsaHsmKeyEnabled()
        {
            string keyName = Recording.GenerateId();

            CreateRsaKeyOptions options   = new CreateRsaKeyOptions(keyName, hardwareProtected: true);
            KeyVaultKey         rsaHsmKey = await Client.CreateRsaKeyAsync(options);

            RegisterForCleanup(keyName);

            rsaHsmKey.Properties.Enabled = false;
            KeyVaultKey updateResult = await Client.UpdateKeyPropertiesAsync(rsaHsmKey.Properties, rsaHsmKey.KeyOperations);

            KeyVaultKey keyReturned = await Client.GetKeyAsync(keyName);

            AssertKeyVaultKeysEqual(keyReturned, updateResult);
        }
Пример #11
0
        protected void DefaultInit()
        {
            string tenantId     = _configuration["Azure:Tenant_ID"];
            string clientId     = _configuration["Azure:Client_ID"];
            string clientSecret = _configuration["Azure:Client_Secret"];

            var clientCredentials = new ClientSecretCredential(tenantId, clientId, clientSecret);

            var keyClient = new KeyClient(new Uri(_keyVaultUri), clientCredentials);

            keyClient.CreateRsaKey(new CreateRsaKeyOptions(_keyVaultKeyName));

            KeyVaultKey key = keyClient.GetKey(_keyVaultKeyName);

            _cryptoClient = new CryptographyClient(key.Id, new DefaultAzureCredential());
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            var    keyclient = new KeyClient(new Uri("https://markappincc.vault.azure.net/"), new DefaultAzureCredential());
            string payload   = req.Query["payload"];

            byte[]      toDecryptInBytes = Convert.FromBase64String(payload);
            KeyVaultKey key = await keyclient.GetKeyAsync("marekmaencrypt");

            CryptographyClient crypto = new CryptographyClient(key.Id, new DefaultAzureCredential());

            DecryptResult result = await crypto.DecryptAsync(EncryptionAlgorithm.RsaOaep256, toDecryptInBytes);

            return(new OkObjectResult(Encoding.UTF8.GetString(result.Plaintext)));
        }
Пример #13
0
        public async Task EncryptDecryptFromKeyClient()
        {
            KeyVaultKey key = await CreateTestKey(EncryptionAlgorithm.RsaOaep);

            RegisterForCleanup(key.Name);

            byte[] plaintext = Encoding.UTF8.GetBytes("A single block of plaintext");

            // Make sure the same (instrumented) pipeline is used from the KeyClient.
            CryptographyClient cryptoClient  = Client.GetCryptographyClient(key.Name, key.Properties.Version);
            EncryptResult      encryptResult = await cryptoClient.EncryptAsync(EncryptionAlgorithm.RsaOaep, plaintext);

            DecryptResult decryptResult = await cryptoClient.DecryptAsync(EncryptionAlgorithm.RsaOaep, encryptResult.Ciphertext);

            Assert.AreEqual(plaintext, decryptResult.Plaintext);
        }
        private void EncryptDecryptSync(string keyVaultUrl)
        {
            #region Snippet:KeysSample4KeyClient
            var keyClient = new KeyClient(new Uri(keyVaultUrl), new DefaultAzureCredential());
            #endregion

            #region Snippet:KeysSample4CreateKey
            // Let's create a RSA key which will be used to encrypt and decrypt
            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:KeysSample4CryptographyClient
            var cryptoClient = new CryptographyClient(cloudRsaKey.Id, new DefaultAzureCredential());
            #endregion

            #region Snippet:KeysSample4EncryptKey
            byte[]        plaintext     = Encoding.UTF8.GetBytes("A single block of plaintext");
            EncryptResult encryptResult = cryptoClient.Encrypt(EncryptionAlgorithm.RsaOaep, plaintext);
            Debug.WriteLine($"Encrypted data using the algorithm {encryptResult.Algorithm}, with key {encryptResult.KeyId}. The resulting encrypted data is {Convert.ToBase64String(encryptResult.Ciphertext)}");
            #endregion

            #region Snippet:KeysSample4DecryptKey
            DecryptResult decryptResult = cryptoClient.Decrypt(EncryptionAlgorithm.RsaOaep, encryptResult.Ciphertext);
            Debug.WriteLine($"Decrypted data using the algorithm {decryptResult.Algorithm}, with key {decryptResult.KeyId}. The resulting decrypted data is {Encoding.UTF8.GetString(decryptResult.Plaintext)}");
            #endregion

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

            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);
        }
Пример #15
0
        public async Task SignVerifyDataStreamRoundTrip([EnumValues] SignatureAlgorithm algorithm)
        {
            KeyVaultKey key = await CreateTestKey(algorithm);

            RegisterForCleanup(key.Name);

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

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

            using MemoryStream dataStream = new MemoryStream(data);

            using HashAlgorithm hashAlgo = algorithm.GetHashAlgorithm();

            byte[] digest = hashAlgo.ComputeHash(dataStream);

            dataStream.Seek(0, SeekOrigin.Begin);

            SignResult signResult = await cryptoClient.SignAsync(algorithm, digest);

            SignResult signDataResult = await cryptoClient.SignDataAsync(algorithm, dataStream);

            Assert.AreEqual(algorithm, signResult.Algorithm);
            Assert.AreEqual(algorithm, signDataResult.Algorithm);

            Assert.AreEqual(key.Id, signResult.KeyId);
            Assert.AreEqual(key.Id, signDataResult.KeyId);

            Assert.NotNull(signResult.Signature);
            Assert.NotNull(signDataResult.Signature);

            dataStream.Seek(0, SeekOrigin.Begin);

            VerifyResult verifyResult = await cryptoClient.VerifyAsync(algorithm, digest, signDataResult.Signature);

            VerifyResult verifyDataResult = await cryptoClient.VerifyDataAsync(algorithm, dataStream, signResult.Signature);

            Assert.AreEqual(algorithm, verifyResult.Algorithm);
            Assert.AreEqual(algorithm, verifyDataResult.Algorithm);

            Assert.AreEqual(key.Id, verifyResult.KeyId);
            Assert.AreEqual(key.Id, verifyDataResult.KeyId);

            Assert.True(verifyResult.IsValid);
            Assert.True(verifyResult.IsValid);
        }
        public async Task CreateRoleAssignmentAsync()
        {
            // Replace client with the Instrumented Client.
            client = Client;

            List <KeyVaultRoleDefinition> definitions = await client.GetRoleDefinitionsAsync(KeyVaultRoleScope.Global).ToEnumerableAsync().ConfigureAwait(false);

            _roleDefinitionId = definitions.FirstOrDefault(d => d.RoleName == RoleName).Id;

            // Replace roleDefinitionId with a role definition Id from the definitions returned from GetRoleDefinitionsAsync.
            string definitionIdToAssign = _roleDefinitionId;

            // Replace objectId with the service principal object id.
            string servicePrincipalObjectId = _objectId;

            #region Snippet:CreateRoleAssignmentKeysScope
            //@@string definitionIdToAssign = "<roleDefinitionId>";
            //@@string servicePrincipalObjectId = "<objectId>";

            KeyVaultRoleAssignmentProperties properties = new KeyVaultRoleAssignmentProperties(definitionIdToAssign, servicePrincipalObjectId);
            //@@RoleAssignment keysScopedAssignment = await client.CreateRoleAssignmentAsync(RoleAssignmentScope.Global, properties);
            /*@@*/ KeyVaultRoleAssignment keysScopedAssignment = await client.CreateRoleAssignmentAsync(KeyVaultRoleScope.Keys, properties, _roleAssignmentId).ConfigureAwait(false);

            #endregion

            RegisterForCleanup(keysScopedAssignment);

            // Make sure we have a key to secure.
            KeyClient   keyClient  = KeyClient;
            KeyVaultKey createdKey = await keyClient.CreateKeyAsync(Recording.GenerateId(), KeyType.Oct);

            string keyName = createdKey.Name;

            RegisterKeyForCleanup(keyName);

            #region Snippet:CreateRoleAssignmentKeyScope
            //@@string keyName = "<your-key-name>";
            KeyVaultKey key = await keyClient.GetKeyAsync(keyName);

            //@@RoleAssignment keyScopedAssignment = await client.CreateRoleAssignmentAsync(new RoleAssignmentScope(key.Id), properties);
            /*@@*/ KeyVaultRoleAssignment keyScopedAssignment = await client.CreateRoleAssignmentAsync(new KeyVaultRoleScope(key.Id), properties, _roleAssignmentId).ConfigureAwait(false);

            #endregion

            RegisterForCleanup(keyScopedAssignment);
        }
Пример #17
0
        public async Task DeleteKey()
        {
            string keyName = Recording.GenerateId();

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

            RegisterForCleanup(key.Name, delete: false);

            DeletedKey deletedKey = await Client.DeleteKeyAsync(keyName);

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

            Assert.ThrowsAsync <RequestFailedException>(() => Client.GetKeyAsync(keyName));
        }
Пример #18
0
        public async Task <IActionResult> Encrypt(EncryptDto toEncrypt)
        {
            byte[] toEncryptInBytes = Encoding.UTF8.GetBytes(toEncrypt.Payload);

            if (toEncryptInBytes.Length > 245)
            {
                return(BadRequest());
            }

            KeyVaultKey key = await _keyClient.GetKeyAsync("test");

            CryptographyClient crypto = new CryptographyClient(key.Id, new DefaultAzureCredential());

            EncryptResult result = await crypto.EncryptAsync(EncryptionAlgorithm.RsaOaep256, toEncryptInBytes);

            return(new OkObjectResult(Convert.ToBase64String(result.Ciphertext)));
        }
        private void BackupAndRestoreSync(string keyVaultUrl)
        {
            #region Snippet:KeysSample2KeyClient
            var client = new KeyClient(new Uri(keyVaultUrl), new DefaultAzureCredential());
            #endregion

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

            KeyVaultKey storedKey = client.CreateRsaKey(rsaKey);
            #endregion

            #region Snippet:KeysSample2BackupKey
            byte[] backupKey = client.BackupKey(rsaKeyName);
            #endregion

            using (var memoryStream = new MemoryStream())
            {
                memoryStream.Write(backupKey, 0, backupKey.Length);

                // The storage account key is no longer in use, so you delete it.
                DeleteKeyOperation operation = client.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.
                client.PurgeDeletedKey(rsaKeyName);

                #region Snippet:KeysSample2RestoreKey
                KeyVaultKey restoredKey = client.RestoreKeyBackup(memoryStream.ToArray());
                #endregion

                AssertKeysEqual(storedKey.Properties, restoredKey.Properties);
            }
        }
        public void BackupAndRestoreSync()
        {
            // 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 a RSA key 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)
            };

            KeyVaultKey storedKey = client.CreateRsaKey(rsaKey);

            // Backups are good to have if in case keys get accidentally deleted by you.
            // For long term storage, it is ideal to write the backup to a file, disk, database, etc.
            // For the purposes of this sample, we are storing the bakup in a temporary memory area.
            byte[] backupKey = client.BackupKey(rsaKeyName);

            using (var memoryStream = new MemoryStream())
            {
                memoryStream.Write(backupKey, 0, backupKey.Length);

                // The storage account key is no longer in use, so you delete it.
                client.DeleteKey(rsaKeyName);

                // To ensure the key is deleted on server side.
                Assert.IsTrue(WaitForDeletedKey(client, rsaKeyName));

                // If the keyvault is soft-delete enabled, then for permanent deletion, deleted key needs to be purged.
                client.PurgeDeletedKey(rsaKeyName);

                // After sometime, the key is required again. We can use the backup value to restore it in the Key Vault.
                KeyVaultKey restoredKey = client.RestoreKeyBackup(memoryStream.ToArray());

                AssertKeysEqual(storedKey.Properties, restoredKey.Properties);
            }
        }
Пример #21
0
        public async Task EncryptWithKeyNameReturnsFullKeyId()
        {
            KeyVaultKey key = await CreateTestKey(EncryptionAlgorithm.RsaOaep);

            RegisterForCleanup(key.Name);

            byte[] plaintext = Encoding.UTF8.GetBytes("A single block of plaintext");

            Uri keyId = new UriBuilder(Client.VaultUri)
            {
                Path = KeyClient.KeysPath + key.Name,
            }.Uri;

            CryptographyClient client    = GetCryptoClient(keyId, forceRemote: true);
            EncryptResult      encrypted = await client.EncryptAsync(EncryptionAlgorithm.RsaOaep, plaintext);

            Assert.AreEqual(key.Id.ToString(), encrypted.KeyId);
        }
        public async Task KeyRotationAsync()
        {
            // Environment variable with the Key Vault endpoint.
            string keyVaultUrl = TestEnvironment.KeyVaultUrl;

            var keyClient = new KeyClient(new Uri(keyVaultUrl), new DefaultAzureCredential());

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

            KeyVaultKey cloudRsaKey = await keyClient.CreateRsaKeyAsync(rsaKey);

            Debug.WriteLine($"{cloudRsaKey.KeyType} key is returned with name {cloudRsaKey.Name} and version {cloudRsaKey.Properties.Version}");

            KeyRotationPolicy policy = new KeyRotationPolicy()
            {
                ExpiresIn       = TimeSpan.FromDays(90),
                LifetimeActions =
                {
                    new KeyRotationLifetimeAction()
                    {
                        Action           = KeyRotationPolicyAction.Rotate,
                        TimeBeforeExpiry = TimeSpan.FromDays(30)
                    }
                }
            };

            await keyClient.UpdateKeyRotationPolicyAsync(rsaKeyName, policy);

            KeyVaultKey newRsaKey = await keyClient.RotateKeyAsync(rsaKeyName);

            Debug.WriteLine($"Rotated key {newRsaKey.Name} with version {newRsaKey.Properties.Version}");

            DeleteKeyOperation operation = await keyClient.StartDeleteKeyAsync(rsaKeyName);

            // You only need to wait for completion if you want to purge or recover the key.
            await operation.WaitForCompletionAsync();

            // If the keyvault is soft-delete enabled, then for permanent deletion, deleted key needs to be purged.
            keyClient.PurgeDeletedKey(rsaKeyName);
        }
Пример #23
0
        public async Task SignLocalVerifyRoundTrip([EnumValues(Exclude = new[] { nameof(SignatureAlgorithm.ES256K) })] SignatureAlgorithm algorithm)
        {
#if NET461
            if (algorithm.GetEcKeyCurveName() != default)
            {
                Assert.Ignore("Creating JsonWebKey with ECDsa is not supported on net461.");
            }
#endif

#if NETFRAMEWORK
            if (algorithm.GetRsaSignaturePadding() == RSASignaturePadding.Pss)
            {
                Assert.Ignore("RSA-PSS signature padding is not supported on .NET Framework.");
            }
#endif

            KeyVaultKey key = await CreateTestKey(algorithm);

            RegisterForCleanup(key.Name);

            CryptographyClient client = GetCryptoClient(key.Id);

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

            using HashAlgorithm hashAlgo = algorithm.GetHashAlgorithm();
            byte[] digest = hashAlgo.ComputeHash(data);

            // Should sign remotely...
            SignResult signResult = await client.SignAsync(algorithm, digest);

            Assert.AreEqual(algorithm, signResult.Algorithm);
            Assert.AreEqual(key.Key.Id, signResult.KeyId);
            Assert.NotNull(signResult.Signature);

            // ...and verify locally.
            VerifyResult verifyResult = await client.VerifyAsync(algorithm, digest, signResult.Signature);

            Assert.AreEqual(algorithm, verifyResult.Algorithm);
            Assert.AreEqual(key.Key.Id, verifyResult.KeyId);
            Assert.IsTrue(verifyResult.IsValid);
        }
        public async Task ExportCreatedKey()
        {
            SaveDebugRecordingsOnFailure = true;

            string jsonPolicy = @"{
  ""anyOf"": [
    {
      ""allOf"": [
        {
          ""claim"": ""MyClaim"",
          ""condition"": ""equals"",
          ""value"": ""abc123""
        }
      ],
      ""authority"": ""my.attestation.com""
    }
  ],
  ""version"": ""0.2""
}";

            byte[] encodedPolicy = Encoding.UTF8.GetBytes(jsonPolicy);

            CreateRsaKeyOptions options = new CreateRsaKeyOptions(Recording.GenerateId())
            {
                Exportable    = true,
                KeyOperations =
                {
                    KeyOperation.UnwrapKey,
                    KeyOperation.WrapKey,
                },
                KeySize       = 2048,
                ReleasePolicy = new KeyReleasePolicy(encodedPolicy),
            };

            // Not currently implemented:
            KeyVaultKey createdKey = await Client.CreateRsaKeyAsync(options);

            // This requires provisioning of an application in the enclave, which is coming soon:
            KeyVaultKey exportedKey = await Client.ExportKeyAsync(createdKey.Name, "test");

            CollectionAssert.AreEqual(createdKey.Key.N, exportedKey.Key.N);
        }
        public void SignAfterValidDate()
        {
            using RSA rsa = RSA.Create();

            KeyVaultKey key = new KeyVaultKey("test")
            {
                Key        = new JsonWebKey(rsa),
                Properties =
                {
                    ExpiresOn = DateTimeOffset.Now.AddDays(-1),
                },
            };

            RsaCryptographyProvider provider = new RsaCryptographyProvider(key.Key, key.Properties);

            byte[] digest = new byte[] { 0x9f, 0x86, 0xd0, 0x81, 0x88, 0x4c, 0x7d, 0x65, 0x9a, 0x2f, 0xea, 0xa0, 0xc5, 0x5a, 0xd0, 0x15, 0xa3, 0xbf, 0x4f, 0x1b, 0x2b, 0x0b, 0x82, 0x2c, 0xd1, 0x5d, 0x6c, 0x15, 0xb0, 0xf0, 0x0a, 0x08 };
            InvalidOperationException ex = Assert.Throws <InvalidOperationException>(() => provider.Sign(SignatureAlgorithm.PS256, digest, default));

            Assert.AreEqual($"The key \"test\" is not valid after {key.Properties.ExpiresOn.Value:r}.", ex.Message);
        }
        public void EncryptAfterValidDate()
        {
            using RSA rsa = RSA.Create();

            KeyVaultKey key = new KeyVaultKey("test")
            {
                Key        = new JsonWebKey(rsa),
                Properties =
                {
                    ExpiresOn = DateTimeOffset.Now.AddDays(-1),
                },
            };

            RsaCryptographyProvider provider = new RsaCryptographyProvider(key.Key, key.Properties);

            byte[] plaintext             = Encoding.UTF8.GetBytes("test");
            InvalidOperationException ex = Assert.Throws <InvalidOperationException>(() => provider.Encrypt(EncryptOptions.RsaOaep256Options(plaintext), default));

            Assert.AreEqual($"The key \"test\" is not valid after {key.Properties.ExpiresOn.Value:r}.", ex.Message);
        }
        public void WrapKeyAfterValidDate()
        {
            using RSA rsa = RSA.Create();

            KeyVaultKey key = new KeyVaultKey("test")
            {
                Key        = new JsonWebKey(rsa),
                Properties =
                {
                    ExpiresOn = DateTimeOffset.Now.AddDays(-1),
                },
            };

            RsaCryptographyProvider provider = new RsaCryptographyProvider(key.Key, key.Properties);

            byte[] ek = { 0x64, 0xE8, 0xC3, 0xF9, 0xCE, 0x0F, 0x5B, 0xA2, 0x63, 0xE9, 0x77, 0x79, 0x05, 0x81, 0x8A, 0x2A, 0x93, 0xC8, 0x19, 0x1E, 0x7D, 0x6E, 0x8A, 0xE7 };
            InvalidOperationException ex = Assert.Throws <InvalidOperationException>(() => provider.WrapKey(KeyWrapAlgorithm.RsaOaep256, ek, default));

            Assert.AreEqual($"The key \"test\" is not valid after {key.Properties.ExpiresOn.Value:r}.", ex.Message);
        }
        public async Task DeleteRsaHsmKey()
        {
            string keyName = Recording.GenerateId();

            CreateRsaKeyOptions options   = new CreateRsaKeyOptions(keyName, hardwareProtected: true);
            KeyVaultKey         rsaHsmKey = await Client.CreateRsaKeyAsync(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(rsaHsmKey, deletedKey);

            Assert.ThrowsAsync <RequestFailedException>(() => Client.GetKeyAsync(keyName));
        }
Пример #29
0
        public void WrapKeyBeforeValidDate()
        {
            using Aes aes = Aes.Create();

            KeyVaultKey key = new KeyVaultKey("test")
            {
                Key        = new JsonWebKey(aes),
                Properties =
                {
                    NotBefore = DateTimeOffset.Now.AddDays(1),
                },
            };

            AesCryptographyProvider provider = new AesCryptographyProvider(key.Key, key.Properties);

            byte[] ek = { 0x64, 0xE8, 0xC3, 0xF9, 0xCE, 0x0F, 0x5B, 0xA2, 0x63, 0xE9, 0x77, 0x79, 0x05, 0x81, 0x8A, 0x2A, 0x93, 0xC8, 0x19, 0x1E, 0x7D, 0x6E, 0x8A, 0xE7 };
            InvalidOperationException ex = Assert.Throws <InvalidOperationException>(() => provider.WrapKey(KeyWrapAlgorithm.A128KW, ek, default));

            Assert.AreEqual($"The key \"test\" is not valid before {key.Properties.NotBefore.Value:r}.", ex.Message);
        }
        public void EncryptBeforeValidDate()
        {
            using RSA rsa = RSA.Create();

            KeyVaultKey key = new KeyVaultKey("test")
            {
                Key        = new JsonWebKey(rsa),
                Properties =
                {
                    NotBefore = DateTimeOffset.Now.AddDays(1),
                },
            };

            RsaCryptographyProvider provider = new RsaCryptographyProvider(key.Key, key.Properties);

            byte[] plaintext             = Encoding.UTF8.GetBytes("test");
            InvalidOperationException ex = Assert.Throws <InvalidOperationException>(() => provider.Encrypt(EncryptionAlgorithm.RsaOaep256, plaintext, default));

            Assert.AreEqual($"The key \"test\" is not valid before {key.Properties.NotBefore.Value:r}.", ex.Message);
        }