From bf9351ed886da94cbe2d41601e61fafead6869b7 Mon Sep 17 00:00:00 2001 From: Heath Stewart Date: Mon, 7 Oct 2019 15:47:35 -0700 Subject: [PATCH] Update Key Vault README samples (#7943) Fixes #7189 and fixes #7889 --- .../README.md | 73 +++--- .../samples/SampleSnippets.cs | 102 ++++++++ .../Azure.Security.KeyVault.Keys/ChangeLog.md | 1 + .../Azure.Security.KeyVault.Keys/README.md | 226 +++++++++--------- .../samples/SampleSnippets.cs | 223 +++++++++++++++++ .../ChangeLog.md | 2 +- .../Azure.Security.KeyVault.Secrets/README.md | 142 ++++++----- .../samples/SampleSnippets.cs | 168 +++++++++++++ 8 files changed, 716 insertions(+), 221 deletions(-) create mode 100644 sdk/keyvault/Azure.Security.KeyVault.Certificates/samples/SampleSnippets.cs create mode 100644 sdk/keyvault/Azure.Security.KeyVault.Keys/samples/SampleSnippets.cs create mode 100644 sdk/keyvault/Azure.Security.KeyVault.Secrets/samples/SampleSnippets.cs diff --git a/sdk/keyvault/Azure.Security.KeyVault.Certificates/README.md b/sdk/keyvault/Azure.Security.KeyVault.Certificates/README.md index 6cbb984c067f5..ee61918764d94 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Certificates/README.md +++ b/sdk/keyvault/Azure.Security.KeyVault.Certificates/README.md @@ -63,13 +63,12 @@ Use the [Azure CLI][azure_cli] snippet below to create/get client secret credent #### Create CertificateClient Once you've populated the **AZURE_CLIENT_ID**, **AZURE_CLIENT_SECRET** and **AZURE_TENANT_ID** environment variables and replaced **your-vault-url** with the above returned URI, you can create the [CertificateClient][certificate_client_class]: -```c# -using Azure.Identity; -using Azure.Security.KeyVault.Certificates; - -// Create a new key client using the default credential from Azure.Identity -var client = new CertificateClient(vaultUri: , credential: new DefaultAzureCredential()); +```C# CreateClient +// Create a new certificate 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 CertificateClient(vaultUri: new Uri(keyVaultUrl), credential: new DefaultAzureCredential()); ``` + ## Key concepts With a `CertificateClient` you can get certificates from the vault, create new certificates and new versions of existing certificates, update certificate metadata, and delete certificates. You @@ -88,44 +87,55 @@ This section contains code snippets covering common tasks: `StartCreateCertificate` creates a Certificate to be stored in the Azure Key Vault. If a certificate with the same name already exists, then a new version of the certificate is created. When creating the certificate the user can specify the policy which controls the certificate lifetime. If no policy is specified the default policy will be used. The `StartCreateCertificate` operation returns a `CertificateOperation`. The following example creates a self signed certificate with the default policy. -```c# -// create a certificate, this starts a long running operation to create and sign the certificate -CertificateOperation operation = await Client.StartCreateCertificateAsync("MyCertificate"); -// optionally you can await the completion of the certificate opteration -// NOTE: -CertificateWithPolicy certificate = await WaitForCompletion(operation); +```C# CreateCertificate +// Create a certificate. This starts a long running operation to create and sign the certificate. +CertificateOperation operation = await client.StartCreateCertificateAsync("MyCertificate"); + +// You can await the completion of the create certificate operation. +CertificateWithPolicy certificate = await operation.WaitCompletionAsync(); ``` > NOTE: Depending on the certificate issuer and validation methods, certificate creation and signing can take an indeterministic amount of time. Users should only wait on certificate operations when the operation can be reasonably completed in the scope of the application, such as with self signed certificates or issuers with well known response times. ### Retrieve a Certificate `GetCertificateWithPolicy` retrieves the latest version of a certificate stored in the Key Vault along with its `CertificatePolicy`. -```c# -CertificateWithPolicy certificateWithPolicy = await Client.GetCertificateWithPolicyAsync("MyCertificate"); + +```C# RetrieveCertificate +CertificateWithPolicy certificateWithPolicy = await client.GetCertificateWithPolicyAsync("MyCertificate"); ``` `GetCertificate` retrieves a specific version of a certificate in the vault. -```c# -Certificate certificate = await Client.GetCertificateAsync(certificateWithPolicy.Name, certificateWithPolicy.Version); + +```C# GetCertificate +Certificate certificate = await client.GetCertificateAsync(certificateWithPolicy.Name, certificateWithPolicy.Properties.Version); ``` + ### Update an existing Certificate `UpdateCertificate` updates a certificate stored in the Key Vault. -```c# -IDictionary tags = new Dictionary() { { "key1", "value1" } }; -Certificate updated = await Client.UpdateCertificateAsync(certName, certVersion, tags: expTags); +```C# UpdateCertificate +CertificateProperties certificateProperties = new CertificateProperties(certificate.Id) +{ + Tags = + { + ["key1"] = "value1" + } +}; + +Certificate updated = await client.UpdateCertificatePropertiesAsync(certificateProperties); ``` ### Delete a Certificate `DeleteCertificate` deletes all versions of a certificate stored in the Key Vault. When [soft-delete][soft_delete] is not enabled for the Key Vault, this operation permanently deletes the certificate. If soft delete is enabled the certificate is marked for deletion and can be optionally purged or recovered up until its scheduled purge date. -```c# -DeletedCertificate deletedCert = await Client.DeleteCertificateAsync(certName); + +```C# DeleteCertificate +DeletedCertificate deletedCert = await client.DeleteCertificateAsync("MyCertificate"); Console.WriteLine(deletedCert.ScheduledPurgeDate); -await Client.PurgeDeletedCertificate(certName); +await client.PurgeDeletedCertificateAsync("MyCertificate"); ``` ## Troubleshooting @@ -135,26 +145,26 @@ When you interact with the Azure Key Vault Certificate client library using the For example, if you try to retrieve a Key that doesn't exist in your Key Vault, a `404` error is returned, indicating `Not Found`. -```c# +```C# NotFound try { - Key key = await Client.GetCertficateAsync("MyCertificate"); + CertificateWithPolicy certificateWithPolicy = await client.GetCertificateWithPolicyAsync("SomeCertificate"); } catch (RequestFailedException ex) { - System.Console.WriteLine(ex.ToString()); + Console.WriteLine(ex.ToString()); } ``` You will notice that additional information is logged, like the Client Request ID of the operation. ``` -Message: +Message: Azure.RequestFailedException : Service request failed. - Status: 404 (Not Found) + Status: 404 (Not Found) Content: {"error":{"code":"CertificateNotFound","message":"Certificate not found: MyCertificate"}} - + Headers: Cache-Control: no-cache Pragma: no-cache @@ -172,6 +182,7 @@ Headers: Content-Type: application/json; charset=utf-8 Expires: -1 ``` + ## Next steps Key Vault Certificates client library samples are available to you in this GitHub repository. These samples provide example code for additional scenarios commonly encountered while working with Key Vault: * [HelloWorld.cs][hello_world_sync] and [HelloWorldAsync.cs][hello_world_async] - for working with Azure Key Vault certificates, including: @@ -188,9 +199,9 @@ Key Vault Certificates client library samples are available to you in this GitHu * List deleted certificates in the Key Vault ### Additional Documentation -- For more extensive documentation on Azure Key Vault, see the [API reference documentation][keyvault_rest]. -- For Secrets client library see [Secrets client library][secrets_client_library]. -- For Keys client library see [Keys client library][keys_client_library]. +* For more extensive documentation on Azure Key Vault, see the [API reference documentation][keyvault_rest]. +* For Secrets client library see [Secrets client library][secrets_client_library]. +* For Keys client library see [Keys client library][keys_client_library]. ## Contributing This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com. diff --git a/sdk/keyvault/Azure.Security.KeyVault.Certificates/samples/SampleSnippets.cs b/sdk/keyvault/Azure.Security.KeyVault.Certificates/samples/SampleSnippets.cs new file mode 100644 index 0000000000000..de90acd93de1f --- /dev/null +++ b/sdk/keyvault/Azure.Security.KeyVault.Certificates/samples/SampleSnippets.cs @@ -0,0 +1,102 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using Azure.Core.Testing; +using Azure.Identity; +using NUnit.Framework; +using System; +using System.Threading.Tasks; + +namespace Azure.Security.KeyVault.Certificates.Samples +{ + /// + /// Samples that are used in the associated README.md file. + /// + [LiveOnly] + public partial class Snippets + { +#pragma warning disable IDE1006 // Naming Styles + private CertificateClient client; +#pragma warning restore IDE1006 // Naming Styles + + [OneTimeSetUp] + public async Task CreateClientAsync() + { + // Environment variable with the Key Vault endpoint. + string keyVaultUrl = Environment.GetEnvironmentVariable("AZURE_KEYVAULT_URL"); + + #region CreateClient + // Create a new certificate 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 CertificateClient(vaultUri: new Uri(keyVaultUrl), credential: new DefaultAzureCredential()); + #endregion + + #region CreateCertificate + // Create a certificate. This starts a long running operation to create and sign the certificate. + CertificateOperation operation = await client.StartCreateCertificateAsync("MyCertificate"); + + // You can await the completion of the create certificate operation. + CertificateWithPolicy certificate = await operation.WaitCompletionAsync(); + #endregion + + this.client = client; + } + + [Test] + public async Task RetrieveCertificateAsync() + { + #region RetrieveCertificate + CertificateWithPolicy certificateWithPolicy = await client.GetCertificateWithPolicyAsync("MyCertificate"); + #endregion + + #region GetCertificate + Certificate certificate = await client.GetCertificateAsync(certificateWithPolicy.Name, certificateWithPolicy.Properties.Version); + #endregion + } + + [Test] + public async Task UpdateCertificateAsync() + { + CertificateWithPolicy certificate = await client.GetCertificateWithPolicyAsync("MyCertificate"); + + #region UpdateCertificate + CertificateProperties certificateProperties = new CertificateProperties(certificate.Id) + { + Tags = + { + ["key1"] = "value1" + } + }; + + Certificate updated = await client.UpdateCertificatePropertiesAsync(certificateProperties); + #endregion + } + + [Test] + public async Task NotFoundAsync() + { + #region NotFound + try + { + CertificateWithPolicy certificateWithPolicy = await client.GetCertificateWithPolicyAsync("SomeCertificate"); + } + catch (RequestFailedException ex) + { + Console.WriteLine(ex.ToString()); + } + #endregion + } + + [OneTimeTearDown] + public async Task DeleteCertificateAsync() + { + #region DeleteCertificate + DeletedCertificate deletedCert = await client.DeleteCertificateAsync("MyCertificate"); + + Console.WriteLine(deletedCert.ScheduledPurgeDate); + + await client.PurgeDeletedCertificateAsync("MyCertificate"); + #endregion + } + } +} diff --git a/sdk/keyvault/Azure.Security.KeyVault.Keys/ChangeLog.md b/sdk/keyvault/Azure.Security.KeyVault.Keys/ChangeLog.md index 620ee6519a545..88c5934285453 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Keys/ChangeLog.md +++ b/sdk/keyvault/Azure.Security.KeyVault.Keys/ChangeLog.md @@ -14,6 +14,7 @@ ### Major changes - `KeyClient.UpdateKey` and `KeyClient.UpdateKeyAsync` now allow the `keyOperations` parameter to be null, resulting in no changes to the allowed key operations. +- `RSA` and `ECDsa` support have been implemented for `CryptographyClient` to use locally if key operations and key material allow; otherwise, operations will be performed in Azure Key Vault. ## 4.0.0-preview.1 (2019-06-28) diff --git a/sdk/keyvault/Azure.Security.KeyVault.Keys/README.md b/sdk/keyvault/Azure.Security.KeyVault.Keys/README.md index 2fd85d88d3197..0ab4c3710d488 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Keys/README.md +++ b/sdk/keyvault/Azure.Security.KeyVault.Keys/README.md @@ -47,11 +47,11 @@ Use the [Azure CLI][azure_cli] snippet below to create/get client secret credent } ``` * Use the returned credentials above to set **AZURE_CLIENT_ID**(appId), **AZURE_CLIENT_SECRET**(password) and **AZURE_TENANT_ID**(tenant) environment variables. The following example shows a way to do this in Powershell: -```cmd -$Env:AZURE_CLIENT_ID="generated-app-ID" -$Env:AZURE_CLIENT_SECRET="random-password" -$Env:AZURE_TENANT_ID="tenant-ID" -``` + ```PowerShell + $Env:AZURE_CLIENT_ID="generated-app-ID" + $Env:AZURE_CLIENT_SECRET="random-password" + $Env:AZURE_TENANT_ID="tenant-ID" + ``` * Grant the above mentioned application authorization to perform key operations on the key vault: ```PowerShell @@ -68,30 +68,26 @@ $Env:AZURE_TENANT_ID="tenant-ID" #### Create KeyClient Once you've populated the **AZURE_CLIENT_ID**, **AZURE_CLIENT_SECRET** and **AZURE_TENANT_ID** environment variables and replaced **your-vault-url** with the above returned URI, you can create the [KeyClient][key_client_class]: -```c# -using Azure.Identity; -using Azure.Security.KeyVault.Keys; - -// Create a new key client using the default credential from Azure.Identity -var client = new KeyClient(vaultUri: , credential: new DefaultAzureCredential()); - -// Create a new key using the key client -Key key = await Client.CreateKey("key-name", KeyType.EllipticCurve); +```C# CreateKeyClient +// 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 DefaultAzureCredential()); + +// Create a new key using the key client +Key key = client.CreateKey("key-name", KeyType.Rsa); ``` -> new DefaultAzureCredential(): -> Uses the environment variables previously set (`AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET`, and `AZURE_TENANT_ID`). #### Create CryptographyClient Once you've created a `Key` in the key vault, you can also create the [CryptographyClient][crypto_client_class]: -```c# -using Azure.Identity; -using Azure.Security.KeyVault.Keys.Cryptography; - -// Create a new cryptography client using the default credential from Azure.Identity -var cryptoClient = new CryptographyClient(keyId: key.Id, credential: new DefaultAzureCredential()); +```C# CreateCryptographyClient +// Create a new certificate 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 cryptoClient = new CryptographyClient(keyId: key.Id, credential: new DefaultAzureCredential()); ``` + ## Key concepts + ### Keys Azure Key Vault supports multiple key types and algorithms, and enables the use of Hardware Security Modules (HSM) for high value keys. @@ -119,113 +115,113 @@ The following section provides several code snippets using the [above created](# ### Create a Key Create a Key to be stored in the Azure Key Vault. If a key with the same name already exists, then a new version of the key is created. -```c# -// Create a key. Note that you can specify the type of key -// i.e. Elliptic curve, Hardware Elliptic Curve, RSA -Key key = client.CreateKey("key-name", KeyType.EllipticCurve); - -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 = client.CreateRsaKey(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 = client.CreateEcKey(echsmkey); - -Console.WriteLine(ecKey.Name); -Console.WriteLine(ecKey.KeyMaterial.KeyType); +```C# CreateKey +// Create a key. Note that you can specify the type of key +// i.e. Elliptic curve, Hardware Elliptic Curve, RSA +Key key = client.CreateKey("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 = client.CreateRsaKey(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 = client.CreateEcKey(echsmkey); + +Console.WriteLine(ecKey.Name); +Console.WriteLine(ecKey.KeyMaterial.KeyType); ``` ### Retrieve a Key `GetKey` retrieves a key previously stored in the Key Vault. -```c# -Key key = client.GetKey("key-name"); - -Console.WriteLine(key.Name); -Console.WriteLine(key.KeyMaterial.KeyType); +```C# RetrieveKey +Key key = client.GetKey("key-name"); + +Console.WriteLine(key.Name); +Console.WriteLine(key.KeyMaterial.KeyType); ``` ### Update an existing Key `UpdateKey` updates a key previously stored in the Key Vault. -```c# -Key key = client.CreateKey("key-name", KeyType.EllipticCurve); - -// You can specify additional application-specific metadata in the form of tags. -key.Tags["foo"] = "updated tag"; - -KeyProperties updatedKey = client.UpdateKey(key, key.KeyMaterial.KeyOps); - -Console.WriteLine(updatedKey.Name); -Console.WriteLine(updatedKey.Version); -Console.WriteLine(updatedKey.Updated); +```C# UpdateKey +Key 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"; + +Key updatedKey = client.UpdateKeyProperties(key.Properties, key.KeyMaterial.KeyOps); + +Console.WriteLine(updatedKey.Name); +Console.WriteLine(updatedKey.Properties.Version); +Console.WriteLine(updatedKey.Properties.Updated); ``` ### Delete a Key `DeleteKey` deletes a key previously stored in the Key Vault. When [soft-delete][soft_delete] is not enabled for the Key Vault, this operation permanently deletes the key. -```c# -DeletedKey key = client.DeleteKey("key-name"); - -Console.WriteLine(key.Name); -Console.WriteLine(key.DeletedDate); +```C# DeleteKey +DeletedKey key = client.DeleteKey("key-name"); + +Console.WriteLine(key.Name); +Console.WriteLine(key.DeletedDate); ``` ### List Keys This example lists all the keys in the specified Key Vault. -```c# -Pageable allKeys = client.GetKeys(); - -foreach (Key key in allKeys) -{ - Console.WriteLine(key.Name); -} +```C# ListKeys +Pageable allKeys = client.GetKeys(); + +foreach (KeyProperties key in allKeys) +{ + Console.WriteLine(key.Name); +} ``` ### Encrypt and Decrypt This example creates a CryptographyClient and uses it to encrypt and decrypt with a key in Key Vault. -```c# -byte[] plaintext = Encoding.UTF8.GetBytes("A single block of plaintext"); - -// encrypt the data using the algorithm RSAOAEP -EncryptResult encryptResult = cryptoClient.Encrypt(EncryptionAlgorithm.RSAOAEP, plaintext); - -// decrypt the encrypted data. -DecryptResult decryptResult = cryptoClient.Decrypt(EncryptionAlgorithm.RSAOAEP, encryptResult.Ciphertext); +```C# EncryptDecrypt +byte[] plaintext = Encoding.UTF8.GetBytes("A single block of plaintext"); + +// encrypt the data using the algorithm RSAOAEP +EncryptResult encryptResult = cryptoClient.Encrypt(EncryptionAlgorithm.RsaOaep, plaintext); + +// decrypt the encrypted data. +DecryptResult decryptResult = cryptoClient.Decrypt(EncryptionAlgorithm.RsaOaep, encryptResult.Ciphertext); ``` ### Async create a Key Async APIs are identical to their synchronous counterparts. Note that all methods end with `Async`. -```c# -// Create a key of any type -Key key = await client.CreateKeyAsync("key-name", KeyType.EllipticCurve); - -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(rsarsaCreateKeyKey); - -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); +```C# 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); ``` ## Troubleshooting @@ -235,26 +231,26 @@ When you interact with the Azure Key Vault Key client library using the .NET SDK For example, if you try to retrieve a Key that doesn't exist in your Key Vault, a `404` error is returned, indicating `Not Found`. -```c# -try -{ - Key key = await Client.GetKeyAsync("some_key"); -} -catch (RequestFailedException ex) -{ - System.Console.WriteLine(ex.ToString()); -} +```C# NotFound +try +{ + Key key = await client.GetKeyAsync("some_key"); +} +catch (RequestFailedException ex) +{ + Console.WriteLine(ex.ToString()); +} ``` You will notice that additional information is logged, like the Client Request ID of the operation. ``` -Message: +Message: Azure.RequestFailedException : Service request failed. - Status: 404 (Not Found) + Status: 404 (Not Found) Content: {"error":{"code":"KeyNotFound","message":"Key not found: some_key"}} - + Headers: Cache-Control: no-cache Pragma: no-cache @@ -298,16 +294,14 @@ Several Key Vault Keys client library samples are available to you in this GitHu * [SignVerify.cs][sign_verify_sync] and [SignVerifyAsync.cs][sign_verify_async] - Example code for working with Key Vault keys, including: * Sign a precalculated digest and verify the signature with Sign and Verify * Sign raw data and verify the signature with SignData and VerifyData - * [WrapUnwrap.cs][wrap_unwrap_sync] and [WrapUnwrapAsync.cs][wrap_unwrap_async] - Example code for working with Key Vault keys, including: * Wrap and Unwrap a symmetric key - ### Additional Documentation -- For more extensive documentation on Azure Key Vault, see the [API reference documentation][keyvault_rest]. -- For Secrets client library see [Secrets client library][secrets_client_library]. -- For Certificates client library see [Certificates client library][certificates_client_library]. +* For more extensive documentation on Azure Key Vault, see the [API reference documentation][keyvault_rest]. +* For Secrets client library see [Secrets client library][secrets_client_library]. +* For Certificates client library see [Certificates client library][certificates_client_library]. ## Contributing This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com. diff --git a/sdk/keyvault/Azure.Security.KeyVault.Keys/samples/SampleSnippets.cs b/sdk/keyvault/Azure.Security.KeyVault.Keys/samples/SampleSnippets.cs new file mode 100644 index 0000000000000..5ed6d558365ce --- /dev/null +++ b/sdk/keyvault/Azure.Security.KeyVault.Keys/samples/SampleSnippets.cs @@ -0,0 +1,223 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using Azure.Core.Testing; +using Azure.Identity; +using Azure.Security.KeyVault.Keys.Cryptography; +using NUnit.Framework; +using System; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace Azure.Security.KeyVault.Keys.Samples +{ + /// + /// Samples that are used in the associated README.md file. + /// + [LiveOnly] + public partial class Snippets + { +#pragma warning disable IDE1006 // Naming Styles + private KeyClient client; + private CryptographyClient cryptoClient; +#pragma warning restore IDE1006 // Naming Styles + + [OneTimeSetUp] + public void CreateClient() + { + // Environment variable with the Key Vault endpoint. + string keyVaultUrl = Environment.GetEnvironmentVariable("AZURE_KEYVAULT_URL"); + + #region CreateKeyClient + // 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 DefaultAzureCredential()); + + // Create a new key using the key client + Key key = client.CreateKey("key-name", KeyType.Rsa); + #endregion + + #region CreateCryptographyClient + // Create a new certificate 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 cryptoClient = new CryptographyClient(keyId: key.Id, credential: new DefaultAzureCredential()); + #endregion + + this.client = client; + this.cryptoClient = cryptoClient; + } + + [Test] + public void CreateKey() + { + #region CreateKey + // Create a key. Note that you can specify the type of key + // i.e. Elliptic curve, Hardware Elliptic Curve, RSA + Key key = client.CreateKey("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 = client.CreateRsaKey(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 = client.CreateEcKey(echsmkey); + + Console.WriteLine(ecKey.Name); + Console.WriteLine(ecKey.KeyMaterial.KeyType); + #endregion + } + + [Test] + 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 + } + + [Test] + public void RetrieveKey() + { + // Make sure a key exists. + client.CreateKey("key-name", KeyType.Rsa); + + #region RetrieveKey + Key key = client.GetKey("key-name"); + + Console.WriteLine(key.Name); + Console.WriteLine(key.KeyMaterial.KeyType); + #endregion + } + + [Test] + public void UpdateKey() + { + #region UpdateKey + Key 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"; + + Key updatedKey = client.UpdateKeyProperties(key.Properties, key.KeyMaterial.KeyOps); + + Console.WriteLine(updatedKey.Name); + Console.WriteLine(updatedKey.Properties.Version); + Console.WriteLine(updatedKey.Properties.Updated); + #endregion + } + + [Test] + public void ListKeys() + { + #region ListKeys + Pageable allKeys = client.GetKeys(); + + foreach (KeyProperties key in allKeys) + { + Console.WriteLine(key.Name); + } + #endregion + } + + [Test] + public void EncryptDecrypt() + { + #region EncryptDecrypt + byte[] plaintext = Encoding.UTF8.GetBytes("A single block of plaintext"); + + // encrypt the data using the algorithm RSAOAEP + EncryptResult encryptResult = cryptoClient.Encrypt(EncryptionAlgorithm.RsaOaep, plaintext); + + // decrypt the encrypted data. + DecryptResult decryptResult = cryptoClient.Decrypt(EncryptionAlgorithm.RsaOaep, encryptResult.Ciphertext); + #endregion + } + + [Test] + public async Task NotFoundAsync() + { + #region NotFound + try + { + Key key = await client.GetKeyAsync("some_key"); + } + catch (RequestFailedException ex) + { + Console.WriteLine(ex.ToString()); + } + #endregion + } + + [OneTimeTearDown] + public void DeleteKey() + { + #region DeleteKey + DeletedKey key = client.DeleteKey("key-name"); + + Console.WriteLine(key.Name); + Console.WriteLine(key.DeletedDate); + #endregion + + DeletedKey rsaKey = client.DeleteKey("rsa-key-name"); + DeletedKey ecKey = client.DeleteKey("ec-key-name"); + + try + { + // Deleting a key when soft delete is enabled may not happen immediately. + WaitForDeletedKey(key.Name); + WaitForDeletedKey(rsaKey.Name); + WaitForDeletedKey(ecKey.Name); + + client.PurgeDeletedKey(key.Name); + client.PurgeDeletedKey(rsaKey.Name); + client.PurgeDeletedKey(ecKey.Name); + } + catch + { + // Merely attempt to purge a deleted key since the Key Vault may not have soft delete enabled. + } + } + + private void WaitForDeletedKey(string keyName) + { + int maxIterations = 20; + for (int i = 0; i < maxIterations; i++) + { + try + { + client.GetDeletedKey(keyName); + } + catch + { + Thread.Sleep(5000); + } + } + } + } +} diff --git a/sdk/keyvault/Azure.Security.KeyVault.Secrets/ChangeLog.md b/sdk/keyvault/Azure.Security.KeyVault.Secrets/ChangeLog.md index bcb4162355ce9..d316326daa464 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Secrets/ChangeLog.md +++ b/sdk/keyvault/Azure.Security.KeyVault.Secrets/ChangeLog.md @@ -8,7 +8,7 @@ - `Secret` and `DeletedSecret` no longer extend `SecretProperties`, but instead contain a `SecretProperties` property named `Properties`. - `SecretClient.Update` has been renamed to `SecretClient.UpdateProperties`. - `SecretProperties.Vault` has been renamed to `SecretProperties.VaultUri`. -- All methods in `SecretClient` now include "Secret" consistent with `KeyClient` and `CertificateClient`. +- All methods in `SecretClient` now include the word "Secret" consistent with `KeyClient` and `CertificateClient`. ## 4.0.0-preview.1 (2019-06-28) Version 4.0.0-preview.1 is the first preview of our efforts to create a user-friendly client library for Azure Key Vault. For more information about diff --git a/sdk/keyvault/Azure.Security.KeyVault.Secrets/README.md b/sdk/keyvault/Azure.Security.KeyVault.Secrets/README.md index 3e4a1c4fd396d..36ee5b2d5890a 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Secrets/README.md +++ b/sdk/keyvault/Azure.Security.KeyVault.Secrets/README.md @@ -47,12 +47,12 @@ Use the [Azure CLI][azure_cli] snippet below to create/get client secret credent } ``` * Use the returned credentials above to set **AZURE_CLIENT_ID**(appId), **AZURE_CLIENT_SECRET**(password) and **AZURE_TENANT_ID**(tenant) environment variables. The following example shows a way to do this in Powershell: -```cmd -$Env:AZURE_CLIENT_ID="generated-app-ID" -$Env:AZURE_CLIENT_SECRET="random-password" -$Env:AZURE_TENANT_ID="tenant-ID" -``` - + ```PowerShell + $Env:AZURE_CLIENT_ID="generated-app-ID" + $Env:AZURE_CLIENT_SECRET="random-password" + $Env:AZURE_TENANT_ID="tenant-ID" + ``` + * Grant the above mentioned application authorization to perform secret operations on the key vault: ```PowerShell az keyvault set-policy --name --spn $AZURE_CLIENT_ID --secret-permissions backup delete get list set @@ -68,18 +68,14 @@ $Env:AZURE_TENANT_ID="tenant-ID" #### Create SecretClient Once you've populated the **AZURE_CLIENT_ID**, **AZURE_CLIENT_SECRET** and **AZURE_TENANT_ID** environment variables and replaced **your-vault-url** with the above returned URI, you can create the [SecretClient][secret_client_class]: -```c# -using Azure.Identity; -using Azure.Security.KeyVault.Secrets; - -// Create a new secret client using the default credential from Azure.Identity -var client = new SecretClient(vaultUri: , credential: new DefaultAzureCredential()); - -// Create a new secret using the secret client -Secret secret = client.Set("secret-name", "secret-value"); +```C# CreateClient +// Create a new secret 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 SecretClient(vaultUri: new Uri(keyVaultUrl), credential: new DefaultAzureCredential()); + +// Create a new secret using the secret client +Secret secret = client.SetSecret("secret-name", "secret-value"); ``` -> new DefaultAzureCredential(): -> Uses the environment variables previously set (`AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET`, and `AZURE_TENANT_ID`) ## Key concepts ### Secret @@ -106,76 +102,76 @@ The following section provides several code snippets using the [above created](# ### Create a Secret `Set` creates a Secret to be stored in the Azure Key Vault. If a secret with the same name already exists, then a new version of the secret is created. -```c# -Secret secret = client.Set("secret-name", "secret-value"); - -Console.WriteLine(secret.Name); -Console.WriteLine(secret.Value); -Console.WriteLine(secret.Version); -Console.WriteLine(secret.Enabled); +```C# CreateSecret +Secret secret = client.SetSecret("secret-name", "secret-value"); + +Console.WriteLine(secret.Name); +Console.WriteLine(secret.Value); +Console.WriteLine(secret.Properties.Version); +Console.WriteLine(secret.Properties.Enabled); ``` ### Retrieve a Secret `Get` retrieves a secret previously stored in the Key Vault. -```c# -Secret secret = client.Get("secret-name"); - -Console.WriteLine(secret.Name); -Console.WriteLine(secret.Value); +```C# RetrieveSecret +Secret secret = client.GetSecret("secret-name"); + +Console.WriteLine(secret.Name); +Console.WriteLine(secret.Value); ``` ### Update an existing Secret `Update` updates a secret previously stored in the Key Vault. Only the attributes of the secret are updated. To update the value, call `SecretClient.Set` on a `Secret` with the same name. -```c# -Secret secret = new Secret("secret-name", "secret-value"); - -// Clients may specify the content type of a secret to assist in interpreting the secret data when it's retrieved -secret.ContentType = "text/plain"; - -// You can specify additional application-specific metadata in the form of tags. -secret.Tags["foo"] = "updated tag"; - -SecretProperties updatedSecret = client.Update(secret); - -Console.WriteLine(updatedSecret.Name); -Console.WriteLine(updatedSecret.Value); -Console.WriteLine(updatedSecret.Version); -Console.WriteLine(updatedSecret.ContentType); +```C# UpdateSecret +Secret secret = client.GetSecret("secret-name"); + +// Clients may specify the content type of a secret to assist in interpreting the secret data when it's retrieved. +secret.Properties.ContentType = "text/plain"; + +// You can specify additional application-specific metadata in the form of tags. +secret.Properties.Tags["foo"] = "updated tag"; + +SecretProperties updatedSecretProperties = client.UpdateSecretProperties(secret.Properties); + +Console.WriteLine(updatedSecretProperties.Name); +Console.WriteLine(updatedSecretProperties.Version); +Console.WriteLine(updatedSecretProperties.ContentType); ``` ### Delete a Secret `Delete` deletes a secret previously stored in the Key Vault. When [soft-delete][soft_delete] is not enabled for the Key Vault, this operation permanently deletes the secret. -```c# -DeletedSecret secret = client.Delete("secret-name"); - -Console.WriteLine(secret.Name); -Console.WriteLine(secret.Value); +```C# DeleteSecret +DeletedSecret secret = client.DeleteSecret("secret-name"); + +Console.WriteLine(secret.Name); +Console.WriteLine(secret.Value); ``` ### List secrets This example lists all the secrets in the specified Key Vault. The value is not returned when listing all secrets. You will need to call `SecretClient.Get` to retrive the value. -```c# -Pageable allSecrets = client.GetSecrets(); - -foreach (SecretProperties secret in allSecrets) -{ - Console.WriteLine(secret.Name); -} +```C# ListSecrets +Pageable allSecrets = client.GetSecrets(); + +foreach (SecretProperties secret in allSecrets) +{ + Console.WriteLine(secret.Name); +} ``` + ### Async create a secret Async APIs are identical to their synchronous counterparts. Note that all methods end with `Async`. This example creates a secret in the Key Vault with the specified optional arguments. -```c# -Secret secret = await client.SetAsync("secret-name", "secret-value"); - -Console.WriteLine(secret.Name); -Console.WriteLine(secret.Value); +```C# CreateSecretAsync +Secret secret = await client.SetSecretAsync("secret-name", "secret-value"); + +Console.WriteLine(secret.Name); +Console.WriteLine(secret.Value); ``` ## Troubleshooting @@ -185,15 +181,15 @@ When you interact with the Azure Key Vault Secret client library using the .NET For example, if you try to retrieve a Secret that doesn't exist in your Key Vault, a `404` error is returned, indicating `Not Found`. -```c# -try -{ - Secret secret = client.Get("some_secret"); -} -catch (RequestFailedException ex) -{ - System.Console.WriteLine(ex.ToString()); -} +```C# NotFound +try +{ + Secret secret = client.GetSecret("some_secret"); +} +catch (RequestFailedException ex) +{ + Console.WriteLine(ex.ToString()); +} ``` You will notice that additional information is logged, like the Client Request ID of the operation. @@ -243,9 +239,9 @@ Several Key Vault Secrets client library samples are available to you in this Gi * List deleted secrets in the Key Vault ### Additional Documentation -- For more extensive documentation on Azure Key Vault, see the [API reference documentation][keyvault_rest]. -- For Keys client library see [Keys client library][keys_client_library]. -- For Certificates client library see [Certificates client library][certificates_client_library]. +* For more extensive documentation on Azure Key Vault, see the [API reference documentation][keyvault_rest]. +* For Keys client library see [Keys client library][keys_client_library]. +* For Certificates client library see [Certificates client library][certificates_client_library]. ## Contributing This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com. diff --git a/sdk/keyvault/Azure.Security.KeyVault.Secrets/samples/SampleSnippets.cs b/sdk/keyvault/Azure.Security.KeyVault.Secrets/samples/SampleSnippets.cs new file mode 100644 index 0000000000000..e153d581027b2 --- /dev/null +++ b/sdk/keyvault/Azure.Security.KeyVault.Secrets/samples/SampleSnippets.cs @@ -0,0 +1,168 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using Azure.Core.Testing; +using Azure.Identity; +using NUnit.Framework; +using System; +using System.Threading; +using System.Threading.Tasks; + +namespace Azure.Security.KeyVault.Secrets.Samples +{ + /// + /// Samples that are used in the associated README.md file. + /// + [LiveOnly] + public partial class Snippets + { +#pragma warning disable IDE1006 // Naming Styles + private SecretClient client; +#pragma warning restore IDE1006 // Naming Styles + + [OneTimeSetUp] + public void CreateClient() + { + // Environment variable with the Key Vault endpoint. + string keyVaultUrl = Environment.GetEnvironmentVariable("AZURE_KEYVAULT_URL"); + + #region CreateClient + // Create a new secret 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 SecretClient(vaultUri: new Uri(keyVaultUrl), credential: new DefaultAzureCredential()); + + // Create a new secret using the secret client + Secret secret = client.SetSecret("secret-name", "secret-value"); + #endregion + + this.client = client; + } + + [Test] + public void CreateSecret() + { + #region CreateSecret + Secret secret = client.SetSecret("secret-name", "secret-value"); + + Console.WriteLine(secret.Name); + Console.WriteLine(secret.Value); + Console.WriteLine(secret.Properties.Version); + Console.WriteLine(secret.Properties.Enabled); + #endregion + } + + [Test] + public async Task CreateSecretAsync() + { + #region CreateSecretAsync + Secret secret = await client.SetSecretAsync("secret-name", "secret-value"); + + Console.WriteLine(secret.Name); + Console.WriteLine(secret.Value); + #endregion + } + + [Test] + public void RetrieveSecret() + { + // Make sure a secret exists. + client.SetSecret("secret-name", "secret-value"); + + #region RetrieveSecret + Secret secret = client.GetSecret("secret-name"); + + Console.WriteLine(secret.Name); + Console.WriteLine(secret.Value); + #endregion + } + + [Test] + public void UpdateSecret() + { + // Make sure a secret exists. + client.SetSecret("secret-name", "secret-value"); + + #region UpdateSecret + Secret secret = client.GetSecret("secret-name"); + + // Clients may specify the content type of a secret to assist in interpreting the secret data when it's retrieved. + secret.Properties.ContentType = "text/plain"; + + // You can specify additional application-specific metadata in the form of tags. + secret.Properties.Tags["foo"] = "updated tag"; + + SecretProperties updatedSecretProperties = client.UpdateSecretProperties(secret.Properties); + + Console.WriteLine(updatedSecretProperties.Name); + Console.WriteLine(updatedSecretProperties.Version); + Console.WriteLine(updatedSecretProperties.ContentType); + #endregion + } + + [Test] + public void ListSecrets() + { + #region ListSecrets + Pageable allSecrets = client.GetSecrets(); + + foreach (SecretProperties secret in allSecrets) + { + Console.WriteLine(secret.Name); + } + #endregion + } + + [Test] + public void NotFound() + { + #region NotFound + try + { + Secret secret = client.GetSecret("some_secret"); + } + catch (RequestFailedException ex) + { + Console.WriteLine(ex.ToString()); + } + #endregion + } + + [OneTimeTearDown] + public void DeleteSecret() + { + #region DeleteSecret + DeletedSecret secret = client.DeleteSecret("secret-name"); + + Console.WriteLine(secret.Name); + Console.WriteLine(secret.Value); + #endregion + + try + { + // Deleting a secret when soft delete is enabled may not happen immediately. + WaitForDeletedSecret(secret.Name); + + client.PurgeDeletedSecret(secret.Name); + } + catch + { + // Merely attempt to purge a deleted secret since the Key Vault may not have soft delete enabled. + } + } + private void WaitForDeletedSecret(string secretName) + { + int maxIterations = 20; + for (int i = 0; i < maxIterations; i++) + { + try + { + client.GetDeletedSecret(secretName); + } + catch + { + Thread.Sleep(5000); + } + } + } + } +}