public async Task <KeyBundle> CreateKey(string keyName) { var keyBundle = GenerateKeyBundle(); var tags = GetDefaultKeyTags(); return(await keyVaultClient.CreateKeyAsync(keyVaultUri, keyName, keyBundle.Key.Kty, keyAttributes : keyBundle.Attributes, tags : tags)); }
/// <summary> /// Adds or update the dictionary values with a specific key to the KeyVault /// </summary> /// <param name="key">The unique key</param> /// <param name="values">The dictionary values to be added</param> /// <returns></returns> /// <remarks>If an exception is generated the method returns it without any wrap</remarks> public async Task AddOrUpdateAsync(string key, IDictionary <String, String> values) { var tags = new Dictionary <String, String>(); foreach (var item in values) { if (!String.IsNullOrEmpty(item.Value) && item.Value.Length > 256) { // If the item is longer than 256 split in chunks of 256 for (var chunk = 0; chunk <= item.Value.Length / 256; chunk++) { tags.Add($"{item.Key}_{chunk}", item.Value.Substring(chunk * 256, (item.Value.Length - chunk * 256) > 256 ? 256 : item.Value.Length - chunk * 256)); } } else if (!String.IsNullOrEmpty(item.Value)) { // If the item is shorter than 256 add it directly tags.Add(item.Key, item.Value); } } var attributes = new KeyAttributes(recoveryLevel: "Purgeable"); attributes.Expires = DateTime.UtcNow.AddHours(12); var retry = new RetryWithExponentialBackoff(); await retry.RunAsync(async() => { var createdKey = await keyVaultClient.CreateKeyAsync(vaultAddress, key, JsonWebKeyType.Rsa, keyAttributes: attributes, tags: tags); }); }
/// <summary> /// Read configuration secret /// </summary> /// <param name="method"></param> /// <param name="vaultUri"></param> /// <param name="keyName"></param> /// <param name="connectionString"></param> /// <returns></returns> private static async Task <KeyVaultClient> TryInititalizeKeyAsync( string method, string vaultUri, string keyName, string connectionString = null) { var tokenProvider = new AzureServiceTokenProvider(connectionString); try { var keyVaultClient = new KeyVaultClient( new KeyVaultClient.AuthenticationCallback( tokenProvider.KeyVaultTokenCallback)); try { var key = await keyVaultClient.GetKeyAsync(vaultUri, keyName); } catch { // Try create key await keyVaultClient.CreateKeyAsync(vaultUri, keyName, new NewKeyParameters { KeySize = 2048, Kty = JsonWebKeyType.Rsa, KeyOps = new List <string> { JsonWebKeyOperation.Wrap, JsonWebKeyOperation.Unwrap } }); } // Worked - we have a working keyvault client. return(keyVaultClient); } catch (Exception ex) { Log.Logger.Debug("Failed to authenticate to keyvault {url} using " + "{method}: {message}", vaultUri, method, ex.Message); return(null); } }
/// <summary> /// Read configuration secret /// </summary> /// <param name="keyVaultClient"></param> /// <param name="vaultUri"></param> /// <param name="keyName"></param> /// <returns></returns> private static async Task <bool> TryInititalizeKeyAsync( KeyVaultClient keyVaultClient, string vaultUri, string keyName) { try { try { var key = await keyVaultClient.GetKeyAsync(vaultUri, keyName); } catch { // Try create key await keyVaultClient.CreateKeyAsync(vaultUri, keyName, new NewKeyParameters { KeySize = 2048, Kty = JsonWebKeyType.Rsa, KeyOps = new List <string> { JsonWebKeyOperation.Wrap, JsonWebKeyOperation.Unwrap } }); } // Worked - we have a working keyvault client. return(true); } catch (Exception ex) { Log.Logger.Debug("Failed to authenticate to keyvault {url}: {message}", vaultUri, ex.Message); return(false); } }
private static async Task RunSample() { var keyVaultClient = new KeyVaultClient(GetAccessToken); // create a key :) var keyCreate = await keyVaultClient.CreateKeyAsync( vault : _keyVaultUrl, keyName : _keyVaultEncryptionKeyName, keyType : _keyType, keyAttributes : new KeyAttributes() { Enabled = true, Expires = UnixEpoch.FromUnixTime(int.MaxValue), NotBefore = UnixEpoch.FromUnixTime(0), }, tags : new Dictionary <string, string> { { "purpose", "StackOverflow Demo" } }); Console.WriteLine(string.Format( "Created {0} ", keyCreate.KeyIdentifier.Name)); // retrieve the key var keyRetrieve = await keyVaultClient.GetKeyAsync( _keyVaultUrl, _keyVaultEncryptionKeyName); Console.WriteLine(string.Format( "Retrieved {0} ", keyRetrieve.KeyIdentifier.Name)); }
public async Task <string> CreateKeyAsync(string keyName) { var keyBundle = GetKeyBundle(); var createdKey = await KeyVaultClient.CreateKeyAsync(VaultAddress, keyName, keyBundle.Key.Kty, keyAttributes : keyBundle.Attributes, tags : GetKeyTags()); return(createdKey.KeyIdentifier.Identifier); }
public async Task <KeyBundle> CreateKey(string keyName, string value) { var client = new KeyVaultClient(AuthCallback); var r = await client.CreateKeyAsync(VaultBaseUrl, keyName, value); return(r); }
/// <summary> /// Generate vault key /// </summary> /// <param name="vault"></param> /// <param name="keyName"></param> /// <returns></returns> public KeyIdentifier GenerateVaultKey(Vault vault, string keyName) { string vaultUri = vault.Properties.VaultUri; var attributes = new KeyAttributes(); var createdKey = keyVaultClient.CreateKeyAsync(vaultUri, keyName, JsonWebKeyType.Rsa, keyOps: JsonWebKeyOperation.AllOperations).GetAwaiter().GetResult(); return(new KeyIdentifier(createdKey.Key.Kid)); }
private static async Task AddItem(string vaultAddress, KeyVaultClient keyVaultClient, String key) { var tags = new Dictionary <String, String>(); tags.Add("Key1", "Value1"); tags.Add("Key2", "Value2"); var createdKey = await keyVaultClient.CreateKeyAsync(vaultAddress, key, JsonWebKeyType.Rsa, tags : tags); }
private static async Task CreateKeyIfNotExists() { var versions = await keyVaultClient.GetKeyVersionsAsync(keyVaultUrl, keyName); // var existingKey = await keyVaultClient.GetKeyAsync(keyVaultUrl, keyVaultUrl, new CancellationToken()); if (!versions.Any()) { await keyVaultClient.CreateKeyAsync(keyVaultUrl, keyName, "RSA", 2048); } }
private static async Task <KeyBundle> GenerateKeyAsync() { var newKeyParams = new NewKeyParameters { Kty = "RSA", KeySize = 2048, }; var keyBundle = await _keyVaultClient.CreateKeyAsync(VaultBaseUrl, KeyName, newKeyParams); return(keyBundle); }
public async Task <string> CreateKeyAsync(string keyName) { if (string.IsNullOrEmpty(keyName)) { throw new ArgumentNullException(keyName); } var keyBundle = GetKeyBundle(); var createdKey = await KeyVaultClient.CreateKeyAsync(VaultAddress, keyName, keyBundle.Key.Kty, keyAttributes : keyBundle.Attributes, tags : GetKeyTags()); return(createdKey.KeyIdentifier.Identifier); }
private static async Task <TenantInfo> CreateTenantAsync(Guid id) { var containerName = $"tenant-{id}"; await CreateBlobContainerAsync(containerName); var keyName = $"key-{id}"; var keyVaultClient = new KeyVaultClient(GetTokenAsync); await keyVaultClient.CreateKeyAsync(KeyVaultUrl, keyName, JsonWebKeyType.Rsa); return(new TenantInfo(id, containerName, keyName)); }
static void Main() { var x = new CredentialsService(); var serviceClientCredentials = x.GetCredentials().Result; var client = new KeyVaultClient(serviceClientCredentials); var key = client.CreateKeyAsync("https://kv-???????.vault.azure.net/", "testkey1", JsonWebKeyType.Rsa).Result; var csr = GetCSR(key.Key); var keyOperationResult = client.SignAsync("testkey1", "RS256", csr.GetDataToSign()).Result; csr.SignRequest(keyOperationResult.Result); Console.Out.WriteLine("done"); Console.In.ReadLine(); }
/// <summary> /// Creates a new key, stores it, then returns key parameters and attributes. /// </summary> /// <param name="keyName"></param> /// <param name="keyParameters"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public async Task <KeyBundle> CreateKeyAsync( string keyName, NewKeyParameters keyParameters, CancellationToken cancellationToken = default ) { var keyBundle = await _keyVaultClient .CreateKeyAsync( _keyVault.Properties.VaultUri, keyName, keyParameters, cancellationToken ); return(keyBundle); }
public KeyVaultTestFixture() { Initialize(string.Empty); if (vaultAddress != null && HttpMockServer.Mode == HttpRecorderMode.Record) { //Create one key to use for testing. Key creation is expensive. var myClient = new KeyVaultClient(new TestKeyVaultCredential(GetAccessToken), GetHandlers()); keyName = "sdktestkey"; var attributes = new KeyAttributes(); var createdKey = myClient.CreateKeyAsync(vaultAddress, keyName, JsonWebKeyType.Rsa, 2048, JsonWebKeyOperation.AllOperations, attributes).GetAwaiter().GetResult(); keyIdentifier = new KeyIdentifier(createdKey.Key.Kid); keyName = keyIdentifier.Name; keyVersion = keyIdentifier.Version; tokenCache = new TokenCache(); } }
/// <summary> /// Created the specified key /// </summary> /// <param name="keyBundle"> key bundle to create </param> /// <returns> created key bundle </returns> private static KeyBundle CreateKey(KeyBundle keyBundle, out string keyName) { // Get key bundle which is needed for creating a key keyBundle = keyBundle ?? inputValidator.GetKeyBundle(); var vaultAddress = inputValidator.GetVaultAddress(); keyName = inputValidator.GetKeyName(); var tags = inputValidator.GetTags(); // Create key in the KeyVault key vault var createdKey = keyVaultClient.CreateKeyAsync(vaultAddress, keyName, keyBundle.Key.Kty, keyAttributes: keyBundle.Attributes, tags: tags).GetAwaiter().GetResult(); Console.Out.WriteLine("Created key:---------------"); PrintoutKey(createdKey); // Store the created key for the next operation if we have a sequence of operations return(createdKey); }
/// <summary> /// Creates a new key, stores it, then returns key parameters and attributes. /// </summary> /// <param name="keyName"></param> /// <param name="keyParameters"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public async Task <KeyBundle> CreateKeyAsync( string keyName, NewKeyParameters keyParameters, CancellationToken cancellationToken = default ) { if (string.IsNullOrEmpty(keyName)) { throw new ArgumentNullException(nameof(keyName)); } var keyBundle = await _keyVaultClient .CreateKeyAsync( _keyVault.Properties.VaultUri, keyName, keyParameters, cancellationToken ); return(keyBundle); }
public KeyVaultTestFixture() { Initialize(string.Empty); if (vaultAddress != null && HttpMockServer.Mode == HttpRecorderMode.Record) { //Create one key to use for testing. Key creation is expensive. var myClient = new KeyVaultClient(new TestKeyVaultCredential(GetAccessToken), GetHandlers()); keyName = "sdktestkey"; var attributes = new KeyAttributes(); var createdKey = myClient.CreateKeyAsync(vaultAddress, keyName, JsonWebKeyType.Rsa, 2048, JsonWebKeyOperation.AllOperations, attributes).GetAwaiter().GetResult(); keyIdentifier = new KeyIdentifier(createdKey.Key.Kid); keyName = keyIdentifier.Name; keyVersion = keyIdentifier.Version; tokenCache = new TokenCache(); _deviceCodeForStorageTests = null; retryExecutor = new RetryPolicy <SoftDeleteErrorDetectionStrategy>(new ExponentialBackoffRetryStrategy(8, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(60), TimeSpan.FromSeconds(5))); } else { retryExecutor = new RetryPolicy <SoftDeleteErrorDetectionStrategy>(new FixedIntervalRetryStrategy(5, TimeSpan.FromSeconds(5.0))); } }
private void AddWCADataProtection(IServiceCollection services, WCACoreSettings wcaCoreSettings) { const string dpapiKeyName = "wca-web-dpapi"; var cloudStorageAccount = CloudStorageAccount.Parse(Configuration.GetConnectionString("StorageConnection")); var newCloudStorageAccount = Microsoft.Azure.Storage.CloudStorageAccount.Parse(Configuration.GetConnectionString("StorageConnection")); services.AddSingleton(cloudStorageAccount); var azureServiceTokenProvider = new AzureServiceTokenProvider(); // If you have issues with authenticating to Azure Key Vault, make sure you're using the correct principal // by checking azureServiceTokenProvider.PrincipalUsed.UserPrincipalName. // For local dev this uses the account that you're logged in to VS2017 with. #pragma warning disable CA2000 // Dispose objects before losing scope: Not disposing as we're registering it as a singleton var wcaKeyVaultClient = new KeyVaultClient( new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback)); #pragma warning restore CA2000 // Dispose objects before losing scope services.AddSingleton <IKeyVaultClient>(wcaKeyVaultClient); if (wcaCoreSettings.UseAzureStorageAndKeyVaultForDPAPI) { string dpapiKeyIdentifier; try { var keyTask = wcaKeyVaultClient.GetKeyAsync(wcaCoreSettings.CredentialAzureKeyVaultUrl, dpapiKeyName); keyTask.Wait(); dpapiKeyIdentifier = keyTask.Result.KeyIdentifier.Identifier; } catch (AggregateException aex) { if ((aex.InnerException as KeyVaultErrorException)?.Response.StatusCode == System.Net.HttpStatusCode.NotFound) { var createKeyTask = wcaKeyVaultClient.CreateKeyAsync( wcaCoreSettings.CredentialAzureKeyVaultUrl, dpapiKeyName, new NewKeyParameters() { Kty = "RSA", KeySize = 4096 }); createKeyTask.Wait(); dpapiKeyIdentifier = createKeyTask.Result.KeyIdentifier.Identifier; } else { throw; } } // Ensure container exists for DPAPI cloudStorageAccount.CreateCloudBlobClient().GetContainerReference(dpapiKeyName).CreateIfNotExistsAsync(); // Configure Data Protection (DPAPI) to use Azure Storage/Key Vault // so that sessions are persisted across deployments/slot swaps. services.AddDataProtection(opts => { opts.ApplicationDiscriminator = "WCA.Web"; }) .PersistKeysToAzureBlobStorage(newCloudStorageAccount, $"/{dpapiKeyName}/keys.xml") .ProtectKeysWithAzureKeyVault(wcaKeyVaultClient, dpapiKeyIdentifier); } else { services.AddDataProtection(opts => { opts.ApplicationDiscriminator = "WCA.Web"; }); } }
public ActionResult Index() { string keyVaultName = "<YOUR_VAULT's_NAME>"; string vaultBaseURL = $"https://{keyVaultName}.vault.azure.net"; //Get a token for accessing the Key Vault. var azureServiceTokenProvider = new AzureServiceTokenProvider(); //Create a Key Vault client for accessing the items in the vault; var keyVault = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback)); // Manage secrets in the Key Vault. // Create a new secret string secretName = "secret-az204"; Task.Run(async() => await keyVault.SetSecretAsync(vaultBaseURL, secretName, "This is a secret testing value")).Wait(); var secret = Task.Run(async() => await keyVault.GetSecretAsync ($"{vaultBaseURL}/secrets/{secretName}")).GetAwaiter().GetResult(); // Update an existing secret Task.Run(async() => await keyVault.SetSecretAsync(vaultBaseURL, secretName, "Updated the secret testing value")).Wait(); secret = Task.Run(async() => await keyVault.GetSecretAsync ($"{vaultBaseURL}/secrets/{secretName}")).GetAwaiter().GetResult(); // Delete the secret Task.Run(async() => await keyVault.DeleteSecretAsync(vaultBaseURL, secretName)).Wait(); // Manage certificates in the Key Vault string certName = "cert-az204"; // Create a new self-signed certificate var policy = new CertificatePolicy { IssuerParameters = new IssuerParameters { Name = "Self", }, KeyProperties = new KeyProperties { Exportable = true, KeySize = 2048, KeyType = "RSA" }, SecretProperties = new SecretProperties { ContentType = "application/x-pkcs12" }, X509CertificateProperties = new X509CertificateProperties { Subject = "CN=AZ204KEYVAULTDEMO" } }; Task.Run(async() => await keyVault.CreateCertificateAsync(vaultBaseURL, certName, policy, new CertificateAttributes { Enabled = true })).Wait(); // When you create a new certificate in the Key Vault it takes some time // before it's ready. // We added some wait time here for the sake of simplicity. Thread.Sleep(10000); var certificate = Task.Run(async() => await keyVault.GetCertificateAsync (vaultBaseURL, certName)).GetAwaiter().GetResult(); // Update properties associated with the certificate. CertificatePolicy updatePolicy = new CertificatePolicy { X509CertificateProperties = new X509CertificateProperties { SubjectAlternativeNames = new SubjectAlternativeNames { DnsNames = new[] { "az204.examref.testing" } } } }; Task.Run(async() => await keyVault.UpdateCertificatePolicyAsync( vaultBaseURL, certName, updatePolicy)).Wait(); Task.Run(async() => await keyVault.CreateCertificateAsync(vaultBaseURL, certName)).Wait(); Thread.Sleep(10000); certificate = Task.Run(async() => await keyVault.GetCertificateAsync( vaultBaseURL, certName)). GetAwaiter().GetResult(); Task.Run(async() => await keyVault.UpdateCertificateAsync(certificate. CertificateIdentifier.Identifier, null, new CertificateAttributes { Enabled = false })).Wait(); Thread.Sleep(10000); // Delete the self-signed certificate. Task.Run(async() => await keyVault.DeleteCertificateAsync(vaultBaseURL, certName)).Wait(); // Manage keys in the Key Vault string keyName = "key-az204"; NewKeyParameters keyParameters = new NewKeyParameters { Kty = "EC", CurveName = "SECP256K1", KeyOps = new[] { "sign", "verify" } }; Task.Run(async() => await keyVault.CreateKeyAsync(vaultBaseURL, keyName, keyParameters)).Wait(); var key = Task.Run(async() => await keyVault.GetKeyAsync(vaultBaseURL, keyName)).GetAwaiter().GetResult(); // Update keys in the Key Vault Task.Run(async() => await keyVault.UpdateKeyAsync(vaultBaseURL, keyName, null, new KeyAttributes { Expires = DateTime.UtcNow. AddYears(1) })).Wait(); key = Task.Run(async() => await keyVault.GetKeyAsync(vaultBaseURL, keyName)).GetAwaiter().GetResult(); // Delete keys from the Key Vault Task.Run(async() => await keyVault.DeleteKeyAsync(vaultBaseURL, keyName)). Wait(); return(View()); }
private async Task CreateKey() { var kv = new KeyVaultClient(GetAccessTokenAsync, new HttpClient()); kv.CreateKeyAsync(this.KeyVaultAddress, "Siva", ""); }
private async Task KeysMigrationGuide() { #region Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_Create AzureServiceTokenProvider provider = new AzureServiceTokenProvider(); KeyVaultClient client = new KeyVaultClient( new KeyVaultClient.AuthenticationCallback(provider.KeyVaultTokenCallback)); #endregion Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_Create #region Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_CreateWithOptions using (HttpClient httpClient = new HttpClient()) { //@@AzureServiceTokenProvider provider = new AzureServiceTokenProvider(); /*@@*/ provider = new AzureServiceTokenProvider(); //@@KeyVaultClient client = new KeyVaultClient( /*@@*/ client = new KeyVaultClient( new KeyVaultClient.AuthenticationCallback(provider.KeyVaultTokenCallback), httpClient); } #endregion Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_CreateWithOptions { #region Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_CreateKey // Create RSA key. NewKeyParameters createRsaParameters = new NewKeyParameters { Kty = JsonWebKeyType.Rsa, KeySize = 4096 }; KeyBundle rsaKey = await client.CreateKeyAsync("https://myvault.vault.azure.net", "rsa-key-name", createRsaParameters); // Create Elliptic-Curve key. NewKeyParameters createEcParameters = new NewKeyParameters { Kty = JsonWebKeyType.EllipticCurve, CurveName = "P-256" }; KeyBundle ecKey = await client.CreateKeyAsync("https://myvault.vault.azure.net", "ec-key-name", createEcParameters); #endregion Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_CreateKey } { #region Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_ListKeys IPage <KeyItem> page = await client.GetKeysAsync("https://myvault.vault.azure.net"); foreach (KeyItem item in page) { KeyIdentifier keyId = item.Identifier; KeyBundle key = await client.GetKeyAsync(keyId.Vault, keyId.Name); } while (page.NextPageLink != null) { page = await client.GetKeysNextAsync(page.NextPageLink); foreach (KeyItem item in page) { KeyIdentifier keyId = item.Identifier; KeyBundle key = await client.GetKeyAsync(keyId.Vault, keyId.Name); } } #endregion Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_ListKeys } { #region Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_DeleteKey // Delete the key. DeletedKeyBundle deletedKey = await client.DeleteKeyAsync("https://myvault.vault.azure.net", "key-name"); // Purge or recover the deleted key if soft delete is enabled. if (deletedKey.RecoveryId != null) { DeletedKeyIdentifier deletedKeyId = deletedKey.RecoveryIdentifier; // Deleting a key does not happen immediately. Wait a while and check if the deleted key exists. while (true) { try { await client.GetDeletedKeyAsync(deletedKeyId.Vault, deletedKeyId.Name); // Finally deleted. break; } catch (KeyVaultErrorException ex) when(ex.Response.StatusCode == HttpStatusCode.NotFound) { // Not yet deleted... } } // Purge the deleted key. await client.PurgeDeletedKeyAsync(deletedKeyId.Vault, deletedKeyId.Name); // You can also recover the deleted key using RecoverDeletedKeyAsync. } #endregion Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_DeleteKey } { #region Snippet:Microsoft_Azure_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"); KeyOperationResult encrypted = await client.EncryptAsync("rsa-key-name", JsonWebKeyEncryptionAlgorithm.RSAOAEP256, plaintext); // Decrypt the message. KeyOperationResult decrypted = await client.DecryptAsync("rsa-key-name", JsonWebKeyEncryptionAlgorithm.RSAOAEP256, encrypted.Result); string message = Encoding.UTF8.GetString(decrypted.Result); #endregion Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_Encrypt } { #region Snippet:Microsoft_Azure_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. KeyOperationResult wrapped = await client.WrapKeyAsync( "https://myvault.vault.azure.net", "rsa-key-name", null, JsonWebKeyEncryptionAlgorithm.RSAOAEP256, aes.Key); // Read the IV and the encrypted key from the payload, then unwrap the key. KeyOperationResult unwrapped = await client.UnwrapKeyAsync( "https://myvault.vault.azure.net", "rsa-key-name", null, JsonWebKeyEncryptionAlgorithm.RSAOAEP256, wrapped.Result); aes.Key = unwrapped.Result; // Decrypt the payload with the symmetric key. } #endregion Snippet:Microsoft_Azure_KeyVault_Keys_Snippets_MigrationGuide_Wrap } }
/** * 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 void 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"); KeyVaultClient kvClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(GetToken)); var keyBundle = kvClient.CreateKeyAsync(vault.VaultUri, keyName, Microsoft.Azure.KeyVault.WebKey.JsonWebKeyType.Rsa, keyOps: Microsoft.Azure.KeyVault.WebKey.JsonWebKeyOperation.AllOperations).GetAwaiter().GetResult(); string keyUri = keyBundle.Key.Kid; // 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); } } }
/// <summary> /// Creates KeyVault Key /// </summary> /// <param name="KeyName">KeyVault Key Name</param> /// <param name="KeyType">KeyVault Key Type - (RSA,EC)</param> /// <param name="Size">KeyVault Key Size - (2048,3072,4096)</param> public void CreateKeyVaultKey(string KeyName, string KeyType, int?Size) { keyVaultClient.CreateKeyAsync(vaultUrl, KeyName, KeyType, Size).GetAwaiter().GetResult(); }