Пример #1
0
        public async Task 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 = 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 key vault supports HSM backed keys , please ensure your 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
        }
        public async Task ProtectsKeysWithKeyVaultKey()
        {
            var credential = new ClientSecretCredential(TenantId, ClientId, ClientSecret);
            var client     = new KeyClient(new Uri(KeyVaultUrl), credential);
            var key        = await client.CreateKeyAsync("TestEncryptionKey", KeyType.Rsa);

            var serviceCollection = new ServiceCollection();

            var testKeyRepository = new TestKeyRepository();

            serviceCollection.AddDataProtection().ProtectKeysWithAzureKeyVault(key.Value.Id.ToString(), credential);

            serviceCollection.Configure <KeyManagementOptions>(options =>
            {
                options.XmlRepository = testKeyRepository;
            });

            var services = serviceCollection.BuildServiceProvider();

            var dataProtector = services.GetService <IDataProtectionProvider>().CreateProtector("Fancy purpose");
            var protectedText = dataProtector.Protect("Hello world!");

            var anotherServices      = serviceCollection.BuildServiceProvider();
            var anotherDataProtector = anotherServices.GetService <IDataProtectionProvider>().CreateProtector("Fancy purpose");
            var unprotectedText      = anotherDataProtector.Unprotect(protectedText);

            Assert.AreEqual("Hello world!", unprotectedText);

            // double check that keys were protected with KeyVault

            foreach (var element in testKeyRepository.GetAllElements())
            {
                StringAssert.Contains("This key is encrypted with Azure KeyVault", element.ToString());
            }
        }
Пример #3
0
        private static async Task StoreKey()
        {
            var client = new KeyClient(new Uri(string.Format(AzureKeyVaultUri, vaultSetting.KeyVaultName)), credential);

            Console.WriteLine("Storing key...");
            Console.Write("> Name: ");
            var name           = Console.ReadLine();
            var keyTypesValues = new List <KeyType>()
            {
                KeyType.Ec,
                KeyType.EcHsm,
                KeyType.Rsa,
                KeyType.RsaHsm,
            };
            var keyTypes = string.Join(", ", keyTypesValues);

            Console.Write($"> Type ({keyTypes}): ");
            var rawKeyType = Console.ReadLine().ToUpper();

            while (!keyTypesValues.Contains(rawKeyType))
            {
                Console.Write("Invalid key type");
                Console.Write($"> Type ({keyTypes}): ");
                rawKeyType = Console.ReadLine();
            }
            var keyType = keyTypesValues.Single(kt => kt == rawKeyType);
            var result  = await client.CreateKeyAsync(name, keyType);

            PrintResult(result);
        }
        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.First(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
#if SNIPPET
            string definitionIdToAssign     = "<roleDefinitionId>";
            string servicePrincipalObjectId = "<objectId>";

            KeyVaultRoleAssignment keysScopedAssignment = await client.CreateRoleAssignmentAsync(KeyVaultRoleScope.Global, definitionIdToAssign, servicePrincipalObjectId);
#else
            Guid roleAssignmentName = Recording.Random.NewGuid();
            KeyVaultRoleAssignment keysScopedAssignment = await client.CreateRoleAssignmentAsync(KeyVaultRoleScope.Keys, definitionIdToAssign, servicePrincipalObjectId, roleAssignmentName).ConfigureAwait(false);
#endif
            #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
#if SNIPPET
            string keyName = "<your-key-name>";
#endif
            KeyVaultKey key = await keyClient.GetKeyAsync(keyName);

#if SNIPPET
            KeyVaultRoleAssignment keyScopedAssignment = await client.CreateRoleAssignmentAsync(new KeyVaultRoleScope(key.Id), definitionIdToAssign, servicePrincipalObjectId);
#else
            KeyVaultRoleAssignment keyScopedAssignment = await client.CreateRoleAssignmentAsync(new KeyVaultRoleScope(key.Id), definitionIdToAssign, servicePrincipalObjectId, roleAssignmentName).ConfigureAwait(false);
#endif
            #endregion

            RegisterForCleanup(keyScopedAssignment);
        }
Пример #5
0
        public async Task CanUprotectExistingKeys()
        {
            var credential = new ClientSecretCredential(
                DataProtectionTestEnvironment.Instance.TenantId,
                DataProtectionTestEnvironment.Instance.ClientId,
                DataProtectionTestEnvironment.Instance.ClientSecret);
            var client = new KeyClient(new Uri(DataProtectionTestEnvironment.Instance.KeyVaultUrl), credential);
            var key    = await client.CreateKeyAsync("TestEncryptionKey2", KeyType.Rsa);

            var serviceCollection = new ServiceCollection();

            var testKeyRepository = new TestKeyRepository();

            AzureDataProtectionBuilderExtensions.ProtectKeysWithAzureKeyVault(
                serviceCollection.AddDataProtection(),
                key.Value.Id.AbsoluteUri,
                DataProtectionTestEnvironment.Instance.ClientId,
                DataProtectionTestEnvironment.Instance.ClientSecret);

            serviceCollection.Configure <KeyManagementOptions>(options =>
            {
                options.XmlRepository = testKeyRepository;
            });

            var servicesOld = serviceCollection.BuildServiceProvider();

            var serviceCollectionNew = new ServiceCollection();

            serviceCollectionNew.AddDataProtection().ProtectKeysWithAzureKeyVault(key.Value.Id, credential);
            serviceCollectionNew.Configure <KeyManagementOptions>(options =>
            {
                options.XmlRepository = testKeyRepository;
            });

            var dataProtector = servicesOld.GetService <IDataProtectionProvider>().CreateProtector("Fancy purpose");
            var protectedText = dataProtector.Protect("Hello world!");

            var newServices = serviceCollectionNew.BuildServiceProvider();
            var newDataProtectionProvider = newServices.GetService <IDataProtectionProvider>().CreateProtector("Fancy purpose");
            var unprotectedText           = newDataProtectionProvider.Unprotect(protectedText);

            Assert.AreEqual("Hello world!", unprotectedText);

            // double check that keys were protected with KeyVault

            foreach (var element in testKeyRepository.GetAllElements())
            {
                StringAssert.Contains("This key is encrypted with Azure", element.ToString());
            }
        }
Пример #6
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.
            BackupOperation backupOperation = await Client.StartBackupAsync(builder.Uri, sasToken);

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

            await WaitForOperationAsync();

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

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

            #region Snippet:SelectiveRestoreAsync
            //@@ string keyName = "<key name to restore>";

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

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

            #endregion

            Assert.That(restoreResult, Is.Not.Null);
            Assert.That(restoreOperation.HasValue, Is.True);

            await WaitForOperationAsync();
        }
Пример #7
0
        public async Task CreateKeyAsync()
        {
            #region CreateKeyAsync
            // Create a key of any type
            Key key = await client.CreateKeyAsync("key-name", KeyType.Rsa);

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

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

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

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

            Console.WriteLine(ecKey.Name);
            Console.WriteLine(ecKey.KeyMaterial.KeyType);
            #endregion
        }
Пример #8
0
 public async Task SetKeyAsync(string key, string value)
 {
     _ = await KeyClient.CreateKeyAsync(key, value);
 }
        /**
         * Azure SQL sample for managing SQL secrets (Server Keys) using Azure Key Vault -
         *  - Create a SQL Server with "system assigned" managed service identity.
         *  - Create an Azure Key Vault with giving access to the SQL Server
         *  - Create, get, list and delete SQL Server Keys
         *  - Delete SQL Server
         */
        public static async Task RunSample(IAzure azure)
        {
            try
            {
                // ============================================================
                // Create a SQL Server with system assigned managed service identity.
                Utilities.Log("Creating a SQL Server with system assigned managed service identity");

                var sqlServer = azure.SqlServers.Define(sqlServerName)
                                .WithRegion(Region.USSouthCentral)
                                .WithNewResourceGroup(rgName)
                                .WithAdministratorLogin(administratorLogin)
                                .WithAdministratorPassword(administratorPassword)
                                .WithSystemAssignedManagedServiceIdentity()
                                .Create();

                Utilities.PrintSqlServer(sqlServer);

                // ============================================================
                // Create an Azure Key Vault and set the access policies.
                Utilities.Log("Creating an Azure Key Vault and set the access policies");
                InitializeCredentials(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));
                if (Azure_SP_ClientId == null || Azure_SP_Secret == null)
                {
                    throw new ArgumentNullException("Missing Client ID and Secret");
                }
                var vault = azure.Vaults.Define(vaultName)
                            .WithRegion(Region.USSouthCentral)
                            .WithExistingResourceGroup(rgName)
                            .DefineAccessPolicy()
                            .ForObjectId(sqlServer.SystemAssignedManagedServiceIdentityPrincipalId)
                            .AllowKeyPermissions(KeyPermissions.WrapKey, KeyPermissions.UnwrapKey, KeyPermissions.Get, KeyPermissions.List)
                            .Attach()
                            .DefineAccessPolicy()
                            .ForServicePrincipal(Azure_SP_ClientId)
                            .AllowKeyAllPermissions()
                            .Attach()
                            .Create();

                SdkContext.DelayProvider.Delay(3 * 60 * 1000);

                // ============================================================
                // Create a SQL server key with Azure Key Vault key.
                Utilities.Log("Creating a SQL server key with Azure Key Vault key");

                var kvClient = new KeyClient(new Uri(vault.VaultUri), new DefaultAzureCredential());

                var keyBundle = await kvClient.CreateKeyAsync(keyName, KeyType.Rsa);

                string keyUri = keyBundle.Value.Key.Id;

                // Work around for SQL server key name must be formatted as "vault_key_version"
                string serverKeyName = $"{vaultName}_{keyName}_" +
                                       keyUri.Substring(keyUri.LastIndexOf("/") + 1);

                var sqlServerKey = sqlServer.ServerKeys.Define()
                                   .WithAzureKeyVaultKey(keyUri)
                                   .Create();

                Utilities.PrintSqlServerKey(sqlServerKey);


                // Validate key exists by getting key
                Utilities.Log("Validating key exists by getting the key");

                sqlServerKey = sqlServer.ServerKeys.Get(serverKeyName);

                Utilities.PrintSqlServerKey(sqlServerKey);


                // Validate key exists by listing keys
                Utilities.Log("Validating key exists by listing keys");

                var serverKeys = sqlServer.ServerKeys.List();
                foreach (var item in serverKeys)
                {
                    Utilities.PrintSqlServerKey(item);
                }


                // Delete key
                Utilities.Log("Deleting the key");
                azure.SqlServers.ServerKeys.DeleteBySqlServer(rgName, sqlServerName, serverKeyName);


                // Delete the SQL Server.
                Utilities.Log("Deleting a Sql Server");
                azure.SqlServers.DeleteById(sqlServer.Id);
            }
            finally
            {
                try
                {
                    Utilities.Log("Deleting Resource Group: " + rgName);
                    azure.ResourceGroups.DeleteByName(rgName);
                    Utilities.Log("Deleted Resource Group: " + rgName);
                }
                catch (Exception e)
                {
                    Utilities.Log(e);
                }
            }
        }
Пример #10
0
        static async Task Main(string[] args)
        {
            // Create a new key client using the default credential from Azure.Identity using environment variables previously set,
            // including AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, and AZURE_TENANT_ID.
            var client = new KeyClient(vaultUri: new Uri(keyVaultUrl), credential: new ClientSecretCredential(tenantId, clientId, clientSecret));

            // next two lines are just to recover key in case we stop program after deleting and before recovering / purging
            //var recoverOperation1 = await client.StartRecoverDeletedKeyAsync("rsa-key-name");
            //await recoverOperation1.WaitForCompletionAsync();

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

            Console.WriteLine("Created the key....");
            Console.WriteLine($"rsaKey.Name: {rsaKey.Name}");
            Console.WriteLine($"rsaKey.KeyType: {rsaKey.KeyType}");
            Console.WriteLine("==================================================");
            Console.WriteLine();

            // Retrieve
            KeyVaultKey key = await client.GetKeyAsync("rsa-key-name");

            Console.WriteLine("Retrieve the key");
            Console.WriteLine($"key.Name: {key.Name}");
            Console.WriteLine($"key.KeyType: {key.KeyType}");
            Console.WriteLine("==================================================");
            Console.WriteLine();


            // Update
            KeyVaultKey updateKey = await client.CreateKeyAsync("rsa-key-name", KeyType.Rsa);

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

            KeyVaultKey updatedKey = await client.UpdateKeyPropertiesAsync(updateKey.Properties);

            Console.WriteLine("Update Initiated.");
            Console.WriteLine($"updatedKey.Name: {updatedKey.Name}");
            Console.WriteLine($"updatedKey.Properties.Version: {updatedKey.Properties.Version}");
            Console.WriteLine($"updatedKey.Properties.UpdatedOn: {updatedKey.Properties.UpdatedOn}");
            Console.WriteLine("==================================================");
            Console.WriteLine();

            /// Delete
            DeleteKeyOperation operation = await client.StartDeleteKeyAsync("rsa-key-name");

            DeletedKey deletedKey = operation.Value;

            Console.WriteLine("Delete operation initialted.");
            Console.WriteLine($"deletedKey.Name: {deletedKey.Name}");
            Console.WriteLine($"deletedKey.DeletedOn: {deletedKey.DeletedOn}");
            Console.WriteLine("==================================================");
            Console.WriteLine();

            // Wait for deletion to complete
            await operation.WaitForCompletionAsync();

            // Recover deleted key
            var recoverOperation = await client.StartRecoverDeletedKeyAsync("rsa-key-name");

            await recoverOperation.WaitForCompletionAsync();

            Console.WriteLine("Recovery completed");
            Console.WriteLine("==================================================");
            Console.WriteLine();

            // Create crypto client and demo of encryption / decryption
            var cryptoClient = new CryptographyClient(keyId: key.Id, credential: new ClientSecretCredential(tenantId, clientId, clientSecret));

            byte[] plaintext = Encoding.UTF8.GetBytes("If you can dream it, you can do it.");

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

            Console.WriteLine("Encryption demo.");
            Console.WriteLine("Encrypted Base64: " + Convert.ToBase64String(encryptResult.Ciphertext));
            Console.WriteLine("==================================================");
            Console.WriteLine();

            // decrypt the encrypted data.
            DecryptResult decryptResult = await cryptoClient.DecryptAsync(EncryptionAlgorithm.RsaOaep, encryptResult.Ciphertext);

            Console.WriteLine("Decryption demo.");
            Console.WriteLine("Decrypted: " + Encoding.UTF8.GetString(decryptResult.Plaintext));
            Console.WriteLine("==================================================");
            Console.WriteLine();

            // Purge
            DeleteKeyOperation deleteOperation = await client.StartDeleteKeyAsync("rsa-key-name");

            await deleteOperation.WaitForCompletionAsync();

            DeletedKey purgekey = deleteOperation.Value;
            await client.PurgeDeletedKeyAsync(purgekey.Name);

            Console.WriteLine("Purge Initiated.");
            Console.WriteLine($"purgekey.Name: {purgekey.Name}");
            Console.WriteLine("==================================================");
            Console.WriteLine();
        }