public Secret UpdateSecret(string vaultName, string secretName, string secretVersion, SecretAttributes secretAttributes) { if (string.IsNullOrEmpty(vaultName)) { throw new ArgumentNullException("vaultName"); } if (string.IsNullOrEmpty(secretName)) { throw new ArgumentNullException("secretName"); } if (secretAttributes == null) { throw new ArgumentNullException("secretAttributes"); } var secretIdentifier = new SecretIdentifier(this.vaultUriHelper.CreateVaultAddress(vaultName), secretName, secretVersion); Azure.KeyVault.Models.SecretAttributes attributes = (Azure.KeyVault.Models.SecretAttributes)secretAttributes; SecretBundle secret; try { secret = this.keyVaultClient.UpdateSecretAsync(secretIdentifier.Identifier, secretAttributes.ContentType, attributes, secretAttributes.TagsDictionary).GetAwaiter().GetResult(); } catch (Exception ex) { throw GetInnerException(ex); } return(new Secret(secret, this.vaultUriHelper)); }
public Secret GetSecret(string vaultName, string secretName, string secretVersion) { if (string.IsNullOrEmpty(vaultName)) { throw new ArgumentNullException("vaultName"); } if (string.IsNullOrEmpty(secretName)) { throw new ArgumentNullException("secretName"); } var secretIdentifier = new SecretIdentifier(this.vaultUriHelper.CreateVaultAddress(vaultName), secretName, secretVersion); SecretBundle secret; try { secret = this.keyVaultClient.GetSecretAsync(secretIdentifier.Identifier).GetAwaiter().GetResult(); } catch (Exception ex) { throw GetInnerException(ex); } return(new Secret(secret, this.vaultUriHelper)); }
static async Task Main(string[] args) { var keyIdentifier = new KeyIdentifier("https://nosecrets-vault05.vault.azure.net:443/keys/EncryptionCertificate02/5cc49b815ea349c5bda9d08366ea780f"); var secretIdentifier = new SecretIdentifier("https://nosecrets-vault05.vault.azure.net:443/secrets/EncryptionCertificate02/5cc49b815ea349c5bda9d08366ea780f"); var azureServiceTokenProvider = new AzureServiceTokenProvider(); var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback)); var secret = await keyVaultClient.GetSecretAsync(secretIdentifier.Identifier); var publicCertificate = new X509Certificate2(Convert.FromBase64String(secret.Value), string.Empty, X509KeyStorageFlags.Exportable); var rsa = keyVaultClient.ToRSA(keyIdentifier, publicCertificate); var plainText = "Hello World"; var encryptedData = Encrypt(rsa, plainText); Console.WriteLine("-------------encrypted string------------"); Console.WriteLine(Convert.ToBase64String(encryptedData)); var decryptedData = Decrypt(rsa, encryptedData); Console.WriteLine("-------------decrypted string------------"); Console.WriteLine(decryptedData); Console.WriteLine("Press any key to continue"); Console.Read(); }
private ListViewItemSecret(ISession session, SecretIdentifier identifier, SecretAttributes attributes, string contentTypeStr, IDictionary <string, string> tags) : base(session, ContentTypeEnumConverter.GetValue(contentTypeStr).IsCertificate() ? CertificatesGroup : SecretsGroup, identifier, tags, attributes.Enabled, attributes.Created, attributes.Updated, attributes.NotBefore, attributes.Expires) { Attributes = attributes; ContentTypeStr = contentTypeStr; ContentType = ContentTypeEnumConverter.GetValue(contentTypeStr); }
/// <summary> /// Retrieves a configuration value or resolves the settings to its corresponding object /// Uses an in-memory cache in which throws away content after a certain time. /// </summary> /// <param name="settingName"> The setting name to get resolved or retrieved </param> /// <param name="cachedExpirationTimeSpan"> The cache expiration time span </param> /// <returns> The retrieved or resolved setting </returns> public static async Task <string> GetSettingAsync(string settingName, TimeSpan?cachedExpirationTimeSpan = null) { var settingValue = GetConfigurationSetting(settingName); // The secret value is cached along with the secret URL as a seperate cached entry because otherwise each time the secret URL would be // retrieved from configuration file and if the secret value overwrites the secret URL, from different threads, the secret could be retrieved multiple times if (SecretIdentifier.IsSecretIdentifier(settingValue)) { return(await ResolveSecretSettingAsync(settingValue, cachedExpirationTimeSpan).ConfigureAwait(false)); } // this could be extended to other types of resolution return(settingValue); }
private (SecretAttributes attributes, SecretBundle bundle) CreateSecret(string name, string value, Func <SecretAttributes> attributesFactory = null, Action <SecretBundle> bundleAction = null) { var id = new SecretIdentifier(VaultUri, name).Identifier; var secretAttributes = attributesFactory?.Invoke() ?? new SecretAttributes() { Enabled = true }; var secretBundle = new SecretBundle(VaultUri, id); secretBundle.Id = id; secretBundle.Attributes = secretAttributes; secretBundle.Value = value; bundleAction?.Invoke(secretBundle); return(secretAttributes, secretBundle); }
public void KeyVaultGetSecretVersionTest() { using (var undoContext = UndoContext.Current) { undoContext.Start(); var client = GetKeyVaultClient(); var secretName = "mysecretname"; var secretValue = "mysecretvalue"; var secretOlder = client.SetSecretAsync(_vaultAddress, secretName, secretValue).GetAwaiter().GetResult(); try { // Get the latest secret using its identifier without version var secretIdentifier = new SecretIdentifier(secretOlder.Id); var getSecret = client.GetSecretAsync(_vaultAddress, secretIdentifier.Name).GetAwaiter().GetResult(); VerifySecretValuesAreEqual(getSecret.Value, secretOlder.Value); VerifyIdsAreEqual(secretOlder.Id, getSecret.Id); var secretNewer = client.SetSecretAsync(_vaultAddress, secretName, secretValue).GetAwaiter().GetResult(); // Get the older secret version using its name and version var getSecretOlder = client.GetSecretAsync(_vaultAddress, secretIdentifier.Name, secretIdentifier.Version) .GetAwaiter() .GetResult(); VerifySecretValuesAreEqual(getSecretOlder.Value, secretOlder.Value); VerifyIdsAreEqual(secretOlder.Id, getSecretOlder.Id); // Get the latest secret using its identifier with version var secretIdentifierNewer = new SecretIdentifier(secretNewer.Id); var getSecretNewer = client.GetSecretAsync(_vaultAddress, secretIdentifierNewer.Name, secretIdentifierNewer.Version) .GetAwaiter() .GetResult(); VerifySecretValuesAreEqual(getSecretNewer.Value, secretNewer.Value); VerifyIdsAreEqual(secretNewer.Id, getSecretNewer.Id); } finally { // Delete the secret client.DeleteSecretAsync(_vaultAddress, secretName).GetAwaiter().GetResult(); } } }
private IConfigurationProvider FromKeyVault(IEnumerable <KeyValuePair <string, string> > data) { const string vaultUri = "https://vault"; var client = new Mock <IKeyVaultClient>(MockBehavior.Strict); var rawData = data.ToList(); var nextPageLink = vaultUri; for (var i = 0; i < rawData.Count; i++) { var currentPageLink = nextPageLink; nextPageLink = i < (rawData.Count - 1) ? $"next{i}" : null; var secretId = new SecretIdentifier(vaultUri, rawData[i].Key).Identifier; var pageMock = new PageMock { NextPageLink = nextPageLink, Value = new[] { new SecretItem { Id = secretId, Attributes = new SecretAttributes { Enabled = true } } } }; if (i == 0) { client.Setup(c => c.GetSecretsAsync(currentPageLink)).ReturnsAsync(pageMock); } else { client.Setup(c => c.GetSecretsNextAsync(currentPageLink)).ReturnsAsync(pageMock); } client.Setup(c => c.GetSecretAsync(secretId)).ReturnsAsync(new SecretBundle() { Value = rawData[i].Value, Id = secretId }); } return(new AzureKeyVaultConfigurationProvider( client.Object, vaultUri, new DefaultKeyVaultSecretManager())); }
static async Task Main(string[] args) { var keyIdentifier = new KeyIdentifier("https://nosecrets-vault05.vault.azure.net:443/keys/SigningCertificate01/2c86727652f14814b77018601a2e5ed4"); var secretIdentifier = new SecretIdentifier("https://nosecrets-vault05.vault.azure.net:443/secrets/SigningCertificate01/2c86727652f14814b77018601a2e5ed4"); var azureServiceTokenProvider = new AzureServiceTokenProvider(); var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback)); var secret = await keyVaultClient.GetSecretAsync(secretIdentifier.Identifier); var publicCertificate = new X509Certificate2(Convert.FromBase64String(secret.Value), string.Empty, X509KeyStorageFlags.Exportable); var rsa = keyVaultClient.ToRSA(keyIdentifier, publicCertificate); var xml = GetXml(); var signedXml = SignXml(rsa, xml); Console.WriteLine("-------------signed xml------------"); Console.WriteLine(signedXml); Console.WriteLine("Press any key to continue"); Console.Read(); }
static async Task Main(string[] args) { var keyIdentifier = new KeyIdentifier("https://nosecrets-vault02.vault.azure.net/keys/Document-Signing01/797aef42588b4a7a8638edc7de08b400"); var secretIdentifier = new SecretIdentifier("https://nosecrets-vault02.vault.azure.net/secrets/Document-Signing01/797aef42588b4a7a8638edc7de08b400"); var azureServiceTokenProvider = new AzureServiceTokenProvider(); var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback)); var secret = await keyVaultClient.GetSecretAsync(secretIdentifier.Identifier); var publicCertificate = new X509Certificate2(Convert.FromBase64String(secret.Value), string.Empty, X509KeyStorageFlags.Exportable); var rsa = keyVaultClient.ToRSA(keyIdentifier, publicCertificate); var xml = GetXml(); var signedXml = SignXml(rsa, xml); Console.WriteLine("-------------signed xml------------"); Console.WriteLine(signedXml); Console.WriteLine("Press any key to continue"); Console.Read(); }
public void SecretIdentifierTest() { string baseId = string.Format("{0}/secrets/{1}", vault, name); string versionedId = string.Format("{0}/{1}", baseId, version); //unversioned var id = new SecretIdentifier(baseId); Assert.Equal(baseId, id.BaseIdentifier); Assert.Equal(baseId, id.Identifier); Assert.Equal(vault, id.Vault); Assert.Equal(name, id.Name); Assert.Equal(string.Empty, id.Version); Assert.True(SecretIdentifier.IsSecretIdentifier(baseId)); //versioned id = new SecretIdentifier(versionedId); Assert.Equal(baseId, id.BaseIdentifier); Assert.Equal(versionedId, id.Identifier); Assert.Equal(vault, id.Vault); Assert.Equal(name, id.Name); Assert.Equal(version, id.Version); Assert.True(SecretIdentifier.IsSecretIdentifier(versionedId)); }
/// <summary> /// Demonstrates management of SAS definitions for KeyVault-managed storage accounts. /// </summary> /// <returns>Task representing the asynchronous execution of this method.</returns> internal static async Task DemonstrateSASManagementAndUsageAsync() { // This sample demonstrates the management operations applicable to // SAS definitions corresponding to KeyVault-managed storage accounts, // and performs the following workflow: // // - list existing storage accounts in a vault // - if the expected sample storage account does not exist, it will be created // - attempt to retrieve an existing managed storage account // - list existing SAS definitions associated with the managed storage account // - if the expected sample SAS definition does not exist, it will be created // - retrieve the SAS definition // - retrieve a SAS token based on the SAS definition // - delete a SAS definition // - if the vault is soft-delete enabled: // - retrieve a deleted SAS definition // - recover the deleted managed storage account // // Note that the sample attempts to reuse the same managed storage account as // in the DemonstrateStorageAccountManagementAsync method. // // Also note that SAS definitions may not be backed up individually, nor may they be purged. // instantiate the samples object var sample = new KeyVaultManagedStorageSamples(); var rgName = sample.context.ResourceGroupName; var vaultName = sample.context.VaultName; var managedStorageName = "msakmgmtsample"; var managedSasDefName = "sassample"; var storageAccountName = sample.context.StorageAccountName; var storageAccountResId = sample.context.StorageAccountResourceId; // retrieve the vault or create one if it doesn't exist var vault = await sample.CreateOrRetrieveVaultAsync(rgName, vaultName, enableSoftDelete : true, enablePurgeProtection : false); var vaultUri = vault.Properties.VaultUri; Console.WriteLine("Operating with vault name '{0}' in resource group '{1}' and location '{2}'; storage account '{3}' (resId '{4}')", vaultName, rgName, vault.Location, storageAccountName, storageAccountResId); try { // list msas List <StorageAccountItem> msaList = new List <StorageAccountItem>(); AzureOperationResponse <IPage <StorageAccountItem> > pageResponse; bool msaExists = false; // outer loop, retrieving storage accounts one page at a time for (pageResponse = await sample.DataClient.GetStorageAccountsWithHttpMessagesAsync(vault.Properties.VaultUri).ConfigureAwait(false); ; pageResponse = await sample.DataClient.GetStorageAccountsNextWithHttpMessagesAsync(pageResponse.Body.NextPageLink).ConfigureAwait(false)) { // inner loop, looking for a matching name for (var it = pageResponse.Body.GetEnumerator(); it.MoveNext();) { msaExists = (it.Current.Identifier.Name == managedStorageName); if (msaExists) { break; } } // break if found, or reached the last page if (msaExists || null == pageResponse.Body.NextPageLink) { break; } } AzureOperationResponse <StorageBundle> retrievedMsaResponse; string regenPeriodStr; if (msaExists) { // get msa from vault Console.Write("Retrieving managed storage account - first attempt..."); retrievedMsaResponse = await sample.DataClient.GetStorageAccountWithHttpMessagesAsync(vaultUri, managedStorageName).ConfigureAwait(false); Console.WriteLine("done."); } else { // create msa: set Key1 as active, enable auto-regeneratio with a period of 30 days. Console.Write("Creating a managed storage account..."); regenPeriodStr = System.Xml.XmlConvert.ToString(TimeSpan.FromDays(30.0)); var createdMsaResponse = await sample.DataClient.SetStorageAccountWithHttpMessagesAsync(vaultUri, managedStorageName, storageAccountResId, "key1", autoRegenerateKey : true, regenerationPeriod : regenPeriodStr) .ConfigureAwait(false); Console.WriteLine("done."); // confirm creation, retrieve msa Console.Write("Retrieving managed storage account - second attempt..."); retrievedMsaResponse = await sample.DataClient.GetStorageAccountWithHttpMessagesAsync(vaultUri, managedStorageName).ConfigureAwait(false); Console.WriteLine("done."); } // list sas definitions List <SasDefinitionItem> sasList = new List <SasDefinitionItem>(); AzureOperationResponse <IPage <SasDefinitionItem> > sasPageResponse; bool sasExists = false; // outer loop, retrieving sas definitions one page at a time for (sasPageResponse = await sample.DataClient.GetSasDefinitionsWithHttpMessagesAsync(vaultUri, managedStorageName).ConfigureAwait(false); ; sasPageResponse = await sample.DataClient.GetSasDefinitionsNextWithHttpMessagesAsync(sasPageResponse.Body.NextPageLink).ConfigureAwait(false)) { // inner loop, looking for a matching name for (var it = sasPageResponse.Body.GetEnumerator(); it.MoveNext();) { sasExists = (it.Current.Identifier.Name == managedSasDefName); if (sasExists) { // we may have found a match, but it might have expired. // check the attributes, and reset the flag if the sas definition is disabled. sasExists &= it.Current.Attributes.Enabled.HasValue && it.Current.Attributes.Enabled.Value; break; } } // break if found, or reached the last page if (sasExists || null == sasPageResponse.Body.NextPageLink) { break; } } AzureOperationResponse <SasDefinitionBundle> retrievedSasResponse; if (sasExists) { // get sas from vault Console.Write("Retrieving existing sas definition..."); retrievedSasResponse = await sample.DataClient.GetSasDefinitionWithHttpMessagesAsync(vaultUri, managedStorageName, managedSasDefName).ConfigureAwait(false); Console.WriteLine("done."); } else { var validityPeriod = System.Xml.XmlConvert.ToString(TimeSpan.FromHours(24.0)); // create sas: use a predefined SAS template uri, 1 hour validity Console.Write("Creating a SAS definition..."); var createdSasResponse = await sample.DataClient.SetSasDefinitionWithHttpMessagesAsync(vaultUri, managedStorageName, managedSasDefName, SampleConstants.SasTemplateUri, SampleConstants.SasType.account.ToString(), validityPeriod) .ConfigureAwait(false); Console.WriteLine("done."); // confirm creation, retrieve sas Console.Write("Retrieving newly created sas definition..."); retrievedSasResponse = await sample.DataClient.GetSasDefinitionWithHttpMessagesAsync(vaultUri, managedStorageName, managedSasDefName).ConfigureAwait(false); Console.WriteLine("done."); } // retrieve a token, via the secret corresponding to this sas definition Console.Write("Retrieving sas from corresponding secret..."); var secretName = new SecretIdentifier(retrievedSasResponse.Body.SecretId).Name; var retrievedSecretResponse = await sample.DataClient.GetSecretWithHttpMessagesAsync(vaultUri, secretName, String.Empty).ConfigureAwait(false); Console.WriteLine("done."); // verify access to storage using the issued SAS await VerifyStorageAccessAsync(storageAccountName, retrievedSecretResponse.Body.Value).ConfigureAwait(false); // delete sas Console.Write("Deleting sas definition..."); await sample.DataClient.DeleteSasDefinitionWithHttpMessagesAsync(vaultUri, managedStorageName, managedSasDefName).ConfigureAwait(false); Console.WriteLine("done."); // if s/d enabled if (vault.Properties.EnableSoftDelete.HasValue && vault.Properties.EnableSoftDelete.Value) { Console.Write("Retrieving deleted managed sas definition..."); AzureOperationResponse <DeletedSasDefinitionBundle> deletedSasResponse = null; await RetryHttpRequestAsync( async() => { return(deletedSasResponse = await sample.DataClient.GetDeletedSasDefinitionWithHttpMessagesAsync(vaultUri, managedStorageName, managedSasDefName).ConfigureAwait(false)); }, "get deleted managed sas definition", SampleConstants.RetryPolicies.DefaultSoftDeleteRetryPolicy) .ConfigureAwait(false); Console.WriteLine("done."); // recover sas Console.Write("Recovering deleted managed sas definition..."); var recoveredSasResponse = await sample.DataClient.RecoverDeletedSasDefinitionWithHttpMessagesAsync(vaultUri, managedStorageName, managedSasDefName).ConfigureAwait(false); Console.WriteLine("done."); // confirm recovery Console.Write("Retrieving recovered managed sas definition..."); await RetryHttpRequestAsync( async() => { return(retrievedSasResponse = await sample.DataClient.GetSasDefinitionWithHttpMessagesAsync(vaultUri, managedStorageName, managedSasDefName).ConfigureAwait(false)); }, "retrieve deleted managed sas definition", SampleConstants.RetryPolicies.DefaultSoftDeleteRetryPolicy) .ConfigureAwait(false); Console.WriteLine("done."); } } catch (KeyVaultErrorException kvee) { Console.WriteLine("Unexpected KeyVault exception encountered: {0} ({1})", kvee.Message, kvee.Response.Content); throw; } catch (CloudException ce) { Console.WriteLine("Unexpected ARM exception encountered: {0}", ce.Message); throw; } catch (Exception e) { Console.WriteLine("Unexpected exception encountered: {0}", e.Message); throw; } }
///GENMHASH:4D33A73A344E127F784620E76B686786:C93F0B75434DD302173E0DC1D7D38D38 public async override Task DeleteByIdAsync(string id, CancellationToken cancellationToken = default(CancellationToken)) { SecretIdentifier identifier = new SecretIdentifier(id); await inner.DeleteSecretAsync(identifier.Vault, identifier.Name, cancellationToken); }
private async Task MigrationGuide() { #region Snippet:Microsoft_Azure_KeyVault_Snippets_MigrationGuide_Create AzureServiceTokenProvider provider = new AzureServiceTokenProvider(); KeyVaultClient client = new KeyVaultClient( new KeyVaultClient.AuthenticationCallback(provider.KeyVaultTokenCallback)); #endregion Snippet:Microsoft_Azure_KeyVault_Snippets_MigrationGuide_Create #region Snippet:Microsoft_Azure_KeyVault_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_Snippets_MigrationGuide_CreateWithOptions { #region Snippet:Microsoft_Azure_KeyVault_Snippets_MigrationGuide_SetSecret SecretBundle secret = await client.SetSecretAsync("https://myvault.vault.azure.net", "secret-name", "secret-value"); #endregion Snippet:Microsoft_Azure_KeyVault_Snippets_MigrationGuide_SetSecret } { #region Snippet:Microsoft_Azure_KeyVault_Snippets_MigrationGuide_GetSecret // Get the latest secret value. SecretBundle secret = await client.GetSecretAsync("https://myvault.vault.azure.net", "secret-name", null); // Get a specific secret value. SecretBundle secretVersion = await client.GetSecretAsync("https://myvault.vault.azure.net", "secret-name", "e43af03a7cbc47d4a4e9f11540186048"); #endregion Snippet:Microsoft_Azure_KeyVault_Snippets_MigrationGuide_GetSecret } { #region Snippet:Microsoft_Azure_KeyVault_Snippets_MigrationGuide_ListSecrets IPage <SecretItem> page = await client.GetSecretsAsync("https://myvault.vault.azure.net"); foreach (SecretItem item in page) { SecretIdentifier secretId = item.Identifier; SecretBundle secret = await client.GetSecretAsync(secretId.Vault, secretId.Name); } while (page.NextPageLink != null) { page = await client.GetSecretsNextAsync(page.NextPageLink); foreach (SecretItem item in page) { SecretIdentifier secretId = item.Identifier; SecretBundle secret = await client.GetSecretAsync(secretId.Vault, secretId.Name); } } #endregion Snippet:Microsoft_Azure_KeyVault_Snippets_MigrationGuide_ListSecrets } { #region Snippet:Microsoft_Azure_KeyVault_Snippets_MigrationGuide_DeleteSecret // Delete the secret. DeletedSecretBundle deletedSecret = await client.DeleteSecretAsync("https://myvault.vault.azure.net", "secret-name"); // Purge or recover the deleted secret if soft delete is enabled. if (deletedSecret.RecoveryId != null) { DeletedSecretIdentifier deletedSecretId = deletedSecret.RecoveryIdentifier; // Deleting a secret does not happen immediately. Wait a while and check if the deleted secret exists. while (true) { try { await client.GetDeletedSecretAsync(deletedSecretId.Vault, deletedSecretId.Name); // Finally deleted. break; } catch (KeyVaultErrorException ex) when(ex.Response.StatusCode == HttpStatusCode.NotFound) { // Not yet deleted... } } // Purge the deleted secret. await client.PurgeDeletedSecretAsync(deletedSecretId.Vault, deletedSecretId.Name); // You can also recover the deleted secret using RecoverDeletedSecretAsync. } #endregion Snippet:Microsoft_Azure_KeyVault_Snippets_MigrationGuide_DeleteSecret } }
string GetSecretIdentifier(string secretName, string version = null) { var sid = new SecretIdentifier(this.vaultUri, secretName, version); return(sid.Identifier); }