public void HelloWorldSync() { // Environment variable with the Key Vault endpoint. string keyVaultUrl = Environment.GetEnvironmentVariable("AZURE_KEYVAULT_URL"); // Instantiate a key client that will be used to call the service. Notice that the client is using default Azure // credentials. To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID', // 'AZURE_CLIENT_KEY' and 'AZURE_TENANT_ID' are set with the service principal credentials. var client = new KeyClient(new Uri(keyVaultUrl), new DefaultAzureCredential()); // Let's create a RSA key valid for 1 year. If the key // already exists in the Key Vault, then a new version of the key is created. string rsaKeyName = $"CloudRsaKey-{Guid.NewGuid()}"; var rsaKey = new CreateRsaKeyOptions(rsaKeyName, hardwareProtected: false) { KeySize = 2048, ExpiresOn = DateTimeOffset.Now.AddYears(1) }; client.CreateRsaKey(rsaKey); // Let's Get the Cloud RSA Key from the Key Vault. KeyVaultKey cloudRsaKey = client.GetKey(rsaKeyName); Debug.WriteLine($"Key is returned with name {cloudRsaKey.Name} and type {cloudRsaKey.KeyType}"); // After one year, the Cloud RSA Key is still required, we need to update the expiry time of the key. // The update method can be used to update the expiry attribute of the key. cloudRsaKey.Properties.ExpiresOn.Value.AddYears(1); KeyVaultKey updatedKey = client.UpdateKeyProperties(cloudRsaKey.Properties, cloudRsaKey.KeyOperations); Debug.WriteLine($"Key's updated expiry time is {updatedKey.Properties.ExpiresOn}"); // We need the Cloud RSA key with bigger key size, so you want to update the key in Key Vault to ensure // it has the required size. // Calling CreateRsaKey on an existing key creates a new version of the key in the Key Vault // with the new specified size. var newRsaKey = new CreateRsaKeyOptions(rsaKeyName, hardwareProtected: false) { KeySize = 4096, ExpiresOn = DateTimeOffset.Now.AddYears(1) }; client.CreateRsaKey(newRsaKey); // The Cloud RSA Key is no longer needed, need to delete it from the Key Vault. DeleteKeyOperation operation = client.StartDeleteKey(rsaKeyName); // To ensure the key is deleted on server before we try to purge it. while (!operation.HasCompleted) { Thread.Sleep(2000); operation.UpdateStatus(); } // If the keyvault is soft-delete enabled, then for permanent deletion, deleted key needs to be purged. client.PurgeDeletedKey(rsaKeyName); }
public void HelloWorldSync() { // Environment variable with the Key Vault endpoint. string keyVaultUrl = Environment.GetEnvironmentVariable("AZURE_KEYVAULT_URL"); #region Snippet:KeysSample1KeyClient var client = new KeyClient(new Uri(keyVaultUrl), new DefaultAzureCredential()); #endregion #region Snippet:KeysSample1CreateKey string rsaKeyName = $"CloudRsaKey-{Guid.NewGuid()}"; var rsaKey = new CreateRsaKeyOptions(rsaKeyName, hardwareProtected: false) { KeySize = 2048, ExpiresOn = DateTimeOffset.Now.AddYears(1) }; client.CreateRsaKey(rsaKey); #endregion #region Snippet:KeysSample1GetKey KeyVaultKey cloudRsaKey = client.GetKey(rsaKeyName); Debug.WriteLine($"Key is returned with name {cloudRsaKey.Name} and type {cloudRsaKey.KeyType}"); #endregion #region Snippet:KeysSample1UpdateKeyProperties cloudRsaKey.Properties.ExpiresOn.Value.AddYears(1); KeyVaultKey updatedKey = client.UpdateKeyProperties(cloudRsaKey.Properties, cloudRsaKey.KeyOperations); Debug.WriteLine($"Key's updated expiry time is {updatedKey.Properties.ExpiresOn}"); #endregion #region Snippet:KeysSample1UpdateKey var newRsaKey = new CreateRsaKeyOptions(rsaKeyName, hardwareProtected: false) { KeySize = 4096, ExpiresOn = DateTimeOffset.Now.AddYears(1) }; client.CreateRsaKey(newRsaKey); #endregion #region Snippet:KeysSample1DeleteKey DeleteKeyOperation operation = client.StartDeleteKey(rsaKeyName); #endregion #region Snippet:KeysSample1PurgeKey // You only need to wait for completion if you want to purge or recover the key. while (!operation.HasCompleted) { Thread.Sleep(2000); operation.UpdateStatus(); } client.PurgeDeletedKey(rsaKeyName); #endregion }
private void HelloWorldSync(string keyVaultUrl) { #region Snippet:KeysSample1KeyClient var client = new KeyClient(new Uri(keyVaultUrl), new DefaultAzureCredential()); #endregion #region Snippet:KeysSample1CreateKey string rsaKeyName = $"CloudRsaKey-{Guid.NewGuid()}"; var rsaKey = new CreateRsaKeyOptions(rsaKeyName, hardwareProtected: false) { KeySize = 2048, ExpiresOn = DateTimeOffset.Now.AddYears(1) }; client.CreateRsaKey(rsaKey); #endregion #region Snippet:KeysSample1GetKey KeyVaultKey cloudRsaKey = client.GetKey(rsaKeyName); Debug.WriteLine($"Key is returned with name {cloudRsaKey.Name} and type {cloudRsaKey.KeyType}"); #endregion #region Snippet:KeysSample1UpdateKeyProperties cloudRsaKey.Properties.ExpiresOn.Value.AddYears(1); KeyVaultKey updatedKey = client.UpdateKeyProperties(cloudRsaKey.Properties, cloudRsaKey.KeyOperations); Debug.WriteLine($"Key's updated expiry time is {updatedKey.Properties.ExpiresOn}"); #endregion #region Snippet:KeysSample1UpdateKey var newRsaKey = new CreateRsaKeyOptions(rsaKeyName, hardwareProtected: false) { KeySize = 4096, ExpiresOn = DateTimeOffset.Now.AddYears(1) }; client.CreateRsaKey(newRsaKey); #endregion #region Snippet:KeysSample1DeleteKey DeleteKeyOperation operation = client.StartDeleteKey(rsaKeyName); #endregion #region Snippet:KeysSample1PurgeKey while (!operation.HasCompleted) { Thread.Sleep(2000); operation.UpdateStatus(); } client.PurgeDeletedKey(rsaKeyName); #endregion }
public void HelloWorldSync() { // Environment variable with the Key Vault endpoint. string keyVaultUrl = Environment.GetEnvironmentVariable("AZURE_KEYVAULT_URL"); // Instantiate a key client that will be used to call the service. Notice that the client is using default Azure // credentials. To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID', // 'AZURE_CLIENT_KEY' and 'AZURE_TENANT_ID' are set with the service principal credentials. var client = new KeyClient(new Uri(keyVaultUrl), new DefaultAzureCredential()); // Let's create a RSA key valid for 1 year. If the key // already exists in the Key Vault, then a new version of the key is created. string rsaKeyName = $"CloudRsaKey-{Guid.NewGuid()}"; var rsaKey = new RsaKeyCreateOptions(rsaKeyName, hsm: false, keySize: 2048) { Expires = DateTimeOffset.Now.AddYears(1) }; client.CreateRsaKey(rsaKey); // Let's Get the Cloud RSA Key from the Key Vault. Key cloudRsaKey = client.GetKey(rsaKeyName); Debug.WriteLine($"Key is returned with name {cloudRsaKey.Name} and type {cloudRsaKey.KeyMaterial.KeyType}"); // After one year, the Cloud RSA Key is still required, we need to update the expiry time of the key. // The update method can be used to update the expiry attribute of the key. cloudRsaKey.Expires.Value.AddYears(1); KeyBase updatedKey = client.UpdateKey(cloudRsaKey, cloudRsaKey.KeyMaterial.KeyOps); Debug.WriteLine($"Key's updated expiry time is {updatedKey.Expires}"); // We need the Cloud RSA key with bigger key size, so you want to update the key in Key Vault to ensure // it has the required size. // Calling CreateRsaKey on an existing key creates a new version of the key in the Key Vault // with the new specified size. var newRsaKey = new RsaKeyCreateOptions(rsaKeyName, hsm: false, keySize: 4096) { Expires = DateTimeOffset.Now.AddYears(1) }; client.CreateRsaKey(newRsaKey); // The Cloud RSA Key is no longer needed, need to delete it from the Key Vault. client.DeleteKey(rsaKeyName); // To ensure key is deleted on server side. Assert.IsTrue(WaitForDeletedKey(client, rsaKeyName)); // If the keyvault is soft-delete enabled, then for permanent deletion, deleted key needs to be purged. client.PurgeDeletedKey(rsaKeyName); }
public void CreateKeySync() { #region CreateKeySync // Create a key of any type KeyVaultKey key = client.CreateKey("key-name", KeyType.Rsa); Console.WriteLine(key.Name); Console.WriteLine(key.KeyType); // Create a software RSA key var rsaCreateKey = new CreateRsaKeyOptions("rsa-key-name", hardwareProtected: false); KeyVaultKey rsaKey = client.CreateRsaKey(rsaCreateKey); Console.WriteLine(rsaKey.Name); Console.WriteLine(rsaKey.KeyType); // Create a hardware Elliptic Curve key // Because only premium key vault supports HSM backed keys , please ensure your key vault // SKU is premium when you set "hardwareProtected" value to true var echsmkey = new CreateEcKeyOptions("ec-key-name", hardwareProtected: true); KeyVaultKey ecKey = client.CreateEcKey(echsmkey); Console.WriteLine(ecKey.Name); Console.WriteLine(ecKey.KeyType); #endregion }
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 }
private static async Task SetupAKVKeysAsync() { ClientSecretCredential clientSecretCredential = new ClientSecretCredential(DataTestUtility.AKVTenantId, DataTestUtility.AKVClientId, DataTestUtility.AKVClientSecret); KeyClient keyClient = new KeyClient(DataTestUtility.AKVBaseUri, clientSecretCredential); AsyncPageable <KeyProperties> keys = keyClient.GetPropertiesOfKeysAsync(); IAsyncEnumerator <KeyProperties> enumerator = keys.GetAsyncEnumerator(); bool testAKVKeyExists = false; try { while (await enumerator.MoveNextAsync()) { KeyProperties keyProperties = enumerator.Current; if (keyProperties.Name.Equals(DataTestUtility.AKVKeyName)) { testAKVKeyExists = true; } } } finally { await enumerator.DisposeAsync(); } if (!testAKVKeyExists) { var rsaKeyOptions = new CreateRsaKeyOptions(DataTestUtility.AKVKeyName, hardwareProtected: false) { KeySize = 2048, ExpiresOn = DateTimeOffset.Now.AddYears(1) }; keyClient.CreateRsaKey(rsaKeyOptions); } }
public void CreateKey() { #region Snippet:CreateKey // Create a key. Note that you can specify the type of key // i.e. Elliptic curve, Hardware Elliptic Curve, RSA KeyVaultKey key = client.CreateKey("key-name", KeyType.Rsa); Console.WriteLine(key.Name); Console.WriteLine(key.KeyType); // Create a software RSA key var rsaCreateKey = new CreateRsaKeyOptions("rsa-key-name", hardwareProtected: false); KeyVaultKey rsaKey = client.CreateRsaKey(rsaCreateKey); Console.WriteLine(rsaKey.Name); Console.WriteLine(rsaKey.KeyType); // Create a hardware Elliptic Curve key // Because only premium Azure Key Vault supports HSM backed keys , please ensure your Azure Key Vault // SKU is premium when you set "hardwareProtected" value to true var echsmkey = new CreateEcKeyOptions("ec-key-name", hardwareProtected: true); KeyVaultKey ecKey = client.CreateEcKey(echsmkey); Console.WriteLine(ecKey.Name); Console.WriteLine(ecKey.KeyType); #endregion }
private PSKeyVaultKey CreateKey(KeyClient client, string keyName, PSKeyVaultKeyAttributes keyAttributes, int?size, string curveName) { CreateKeyOptions options; bool isHsm = keyAttributes.KeyType == KeyType.RsaHsm || keyAttributes.KeyType == KeyType.EcHsm; if (keyAttributes.KeyType == KeyType.Rsa || keyAttributes.KeyType == KeyType.RsaHsm) { options = new CreateRsaKeyOptions(keyName, isHsm) { KeySize = size }; } else if (keyAttributes.KeyType == KeyType.Ec || keyAttributes.KeyType == KeyType.EcHsm) { options = new CreateEcKeyOptions(keyName, isHsm) { CurveName = string.IsNullOrEmpty(curveName) ? (KeyCurveName?)null : new KeyCurveName(curveName) }; } else { // oct (AES) is only supported by managed HSM throw new NotSupportedException($"{keyAttributes.KeyType} is not supported"); } options.NotBefore = keyAttributes.NotBefore; options.ExpiresOn = keyAttributes.Expires; options.Enabled = keyAttributes.Enabled; options.Exportable = keyAttributes.Exportable; options.ReleasePolicy = keyAttributes.ReleasePolicy?.ToKeyReleasePolicy();; if (keyAttributes.KeyOps != null) { foreach (var keyOp in keyAttributes.KeyOps) { options.KeyOperations.Add(new KeyOperation(keyOp)); } } if (keyAttributes.Tags != null) { foreach (DictionaryEntry entry in keyAttributes.Tags) { options.Tags.Add(entry.Key.ToString(), entry.Value.ToString()); } } if (keyAttributes.KeyType == KeyType.Rsa || keyAttributes.KeyType == KeyType.RsaHsm) { return(new PSKeyVaultKey(client.CreateRsaKey(options as CreateRsaKeyOptions).Value, _vaultUriHelper, false)); } else if (keyAttributes.KeyType == KeyType.Ec || keyAttributes.KeyType == KeyType.EcHsm) { return(new PSKeyVaultKey(client.CreateEcKey(options as CreateEcKeyOptions).Value, _vaultUriHelper, false)); } else { throw new NotSupportedException($"{keyAttributes.KeyType} is not supported"); } }
public void KeyRotationSync() { // Environment variable with the Key Vault endpoint. string keyVaultUrl = TestEnvironment.KeyVaultUrl; #region Snippet:KeysSample8KeyClient var keyClient = new KeyClient(new Uri(keyVaultUrl), new DefaultAzureCredential()); #endregion #region Snippet:KeysSample8CreateKey string rsaKeyName = $"CloudRsaKey-{Guid.NewGuid()}"; var rsaKey = new CreateRsaKeyOptions(rsaKeyName, hardwareProtected: false) { KeySize = 2048, }; KeyVaultKey cloudRsaKey = keyClient.CreateRsaKey(rsaKey); Debug.WriteLine($"{cloudRsaKey.KeyType} key is returned with name {cloudRsaKey.Name} and version {cloudRsaKey.Properties.Version}"); #endregion #region Snippet:KeysSample8UpdateRotationPolicy KeyRotationPolicy policy = new KeyRotationPolicy() { ExpiresIn = TimeSpan.FromDays(90), LifetimeActions = { new KeyRotationLifetimeAction() { Action = KeyRotationPolicyAction.Rotate, TimeBeforeExpiry = TimeSpan.FromDays(30) } } }; keyClient.UpdateKeyRotationPolicy(rsaKeyName, policy); #endregion #region Snippet:KeysSample8RotateKey KeyVaultKey newRsaKey = keyClient.RotateKey(rsaKeyName); Debug.WriteLine($"Rotated key {newRsaKey.Name} with version {newRsaKey.Properties.Version}"); #endregion DeleteKeyOperation operation = keyClient.StartDeleteKey(rsaKeyName); // You only need to wait for completion if you want to purge or recover the key. while (!operation.HasCompleted) { Thread.Sleep(2000); operation.UpdateStatus(); } // If the keyvault is soft-delete enabled, then for permanent deletion, deleted key needs to be purged. keyClient.PurgeDeletedKey(rsaKeyName); }
public void EncryptDecryptSync() { // Environment variable with the Key Vault endpoint. string keyVaultUrl = Environment.GetEnvironmentVariable("AZURE_KEYVAULT_URL"); // Instantiate a key client that will be used to create a key. Notice that the client is using default Azure // credentials. To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID', // 'AZURE_CLIENT_KEY' and 'AZURE_TENANT_ID' are set with the service principal credentials. var keyClient = new KeyClient(new Uri(keyVaultUrl), new DefaultAzureCredential()); // Let's create a RSA key which will be used to encrypt and decrypt string rsaKeyName = $"CloudRsaKey-{Guid.NewGuid()}"; var rsaKey = new CreateRsaKeyOptions(rsaKeyName, hardwareProtected: false) { KeySize = 2048, }; KeyVaultKey cloudRsaKey = keyClient.CreateRsaKey(rsaKey); Debug.WriteLine($"Key is returned with name {cloudRsaKey.Name} and type {cloudRsaKey.KeyType}"); // Let's create the CryptographyClient which can perform cryptographic operations with the key we just created. // Again we are using the default Azure credential as above. var cryptoClient = new CryptographyClient(cloudRsaKey.Id, new DefaultAzureCredential()); // Next we'll encrypt some arbitrary plain text with the key using the CryptographyClient. Note that RSA encryption // algorithms have no chaining so they can only encrypt a single block of plaintext securely. For RSAOAEP this can be // calculated as (keysize / 8) - 42, or in our case (2048 / 8) - 42 = 214 bytes. byte[] plaintext = Encoding.UTF8.GetBytes("A single block of plaintext"); // First encrypt the data using RSAOAEP with the created key. EncryptResult encryptResult = cryptoClient.Encrypt(EncryptionAlgorithm.RsaOaep, plaintext); Debug.WriteLine($"Encrypted data using the algorithm {encryptResult.Algorithm}, with key {encryptResult.KeyId}. The resulting encrypted data is {Convert.ToBase64String(encryptResult.Ciphertext)}"); // Now decrypt the encrypted data. Note that the same algorithm must always be used for both encrypt and decrypt DecryptResult decryptResult = cryptoClient.Decrypt(EncryptionAlgorithm.RsaOaep, encryptResult.Ciphertext); Debug.WriteLine($"Decrypted data using the algorithm {decryptResult.Algorithm}, with key {decryptResult.KeyId}. The resulting decrypted data is {Encoding.UTF8.GetString(decryptResult.Plaintext)}"); // The Cloud RSA Key is no longer needed, need to delete it from the Key Vault. DeleteKeyOperation operation = keyClient.StartDeleteKey(rsaKeyName); // To ensure the key is deleted on server before we try to purge it. while (!operation.HasCompleted) { Thread.Sleep(2000); operation.UpdateStatus(); } // If the keyvault is soft-delete enabled, then for permanent deletion, deleted key needs to be purged. keyClient.PurgeDeletedKey(rsaKeyName); }
public void WrapUnwrapSync() { // Environment variable with the Key Vault endpoint. string keyVaultUrl = Environment.GetEnvironmentVariable("AZURE_KEYVAULT_URL"); #region Snippet:KeysSample6KeyClient var keyClient = new KeyClient(new Uri(keyVaultUrl), new DefaultAzureCredential()); #endregion #region Snippet:KeysSample6CreateKey string rsaKeyName = $"CloudRsaKey-{Guid.NewGuid()}"; var rsaKey = new CreateRsaKeyOptions(rsaKeyName, hardwareProtected: false) { KeySize = 2048, }; KeyVaultKey cloudRsaKey = keyClient.CreateRsaKey(rsaKey); Debug.WriteLine($"Key is returned with name {cloudRsaKey.Name} and type {cloudRsaKey.KeyType}"); #endregion #region Snippet:KeysSample6CryptographyClient var cryptoClient = new CryptographyClient(cloudRsaKey.Id, new DefaultAzureCredential()); #endregion #region Snippet:KeysSample6GenerateKey byte[] keyData = AesManaged.Create().Key; Debug.WriteLine($"Generated Key: {Convert.ToBase64String(keyData)}"); #endregion #region Snippet:KeysSample6WrapKey WrapResult wrapResult = cryptoClient.WrapKey(KeyWrapAlgorithm.RsaOaep, keyData); Debug.WriteLine($"Encrypted data using the algorithm {wrapResult.Algorithm}, with key {wrapResult.KeyId}. The resulting encrypted data is {Convert.ToBase64String(wrapResult.EncryptedKey)}"); #endregion #region Snippet:KeysSample6UnwrapKey UnwrapResult unwrapResult = cryptoClient.UnwrapKey(KeyWrapAlgorithm.RsaOaep, wrapResult.EncryptedKey); Debug.WriteLine($"Decrypted data using the algorithm {unwrapResult.Algorithm}, with key {unwrapResult.KeyId}. The resulting decrypted data is {Encoding.UTF8.GetString(unwrapResult.Key)}"); #endregion #region Snippet:KeysSample6DeleteKey DeleteKeyOperation operation = keyClient.StartDeleteKey(rsaKeyName); // You only need to wait for completion if you want to purge or recover the key. while (!operation.HasCompleted) { Thread.Sleep(2000); operation.UpdateStatus(); } #endregion // If the keyvault is soft-delete enabled, then for permanent deletion, deleted key needs to be purged. keyClient.PurgeDeletedKey(rsaKeyName); }
public void WrapUnwrapSync() { // Environment variable with the Key Vault endpoint. string keyVaultUrl = Environment.GetEnvironmentVariable("AZURE_KEYVAULT_URL"); // Instantiate a key client that will be used to create a key. Notice that the client is using default Azure // credentials. To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID', // 'AZURE_CLIENT_KEY' and 'AZURE_TENANT_ID' are set with the service principal credentials. var keyClient = new KeyClient(new Uri(keyVaultUrl), new DefaultAzureCredential()); // First create a RSA key which will be used to wrap and unwrap another key string rsaKeyName = $"CloudRsaKey-{Guid.NewGuid()}"; var rsaKey = new CreateRsaKeyOptions(rsaKeyName, hardwareProtected: false) { KeySize = 2048, }; KeyVaultKey cloudRsaKey = keyClient.CreateRsaKey(rsaKey); Debug.WriteLine($"Key is returned with name {cloudRsaKey.Name} and type {cloudRsaKey.KeyType}"); // Let's create the CryptographyClient which can perform cryptographic operations with the key we just created. // Again we are using the default Azure credential as above. var cryptoClient = new CryptographyClient(cloudRsaKey.Id, new DefaultAzureCredential()); // Next we'll generate a symmetric key which we will wrap byte[] keyData = AesManaged.Create().Key; Debug.WriteLine($"Generated Key: {Convert.ToBase64String(keyData)}"); // Wrap the key using RSAOAEP with the created key. WrapResult wrapResult = cryptoClient.WrapKey(KeyWrapAlgorithm.RsaOaep, keyData); Debug.WriteLine($"Encrypted data using the algorithm {wrapResult.Algorithm}, with key {wrapResult.KeyId}. The resulting encrypted data is {Convert.ToBase64String(wrapResult.EncryptedKey)}"); // Now unwrap the encrypted key. Note that the same algorithm must always be used for both wrap and unwrap UnwrapResult unwrapResult = cryptoClient.UnwrapKey(KeyWrapAlgorithm.RsaOaep, wrapResult.EncryptedKey); Debug.WriteLine($"Decrypted data using the algorithm {unwrapResult.Algorithm}, with key {unwrapResult.KeyId}. The resulting decrypted data is {Encoding.UTF8.GetString(unwrapResult.Key)}"); // The Cloud RSA Key is no longer needed, need to delete it from the Key Vault. DeleteKeyOperation operation = keyClient.StartDeleteKey(rsaKeyName); // To ensure the key is deleted on server before we try to purge it. while (!operation.HasCompleted) { Thread.Sleep(2000); operation.UpdateStatus(); } // If the keyvault is soft-delete enabled, then for permanent deletion, deleted key needs to be purged. keyClient.PurgeDeletedKey(rsaKeyName); }
public void EncryptDecryptSync() { // Environment variable with the Key Vault endpoint. string keyVaultUrl = Environment.GetEnvironmentVariable("AZURE_KEYVAULT_URL"); #region Snippet:KeysSample4KeyClient var keyClient = new KeyClient(new Uri(keyVaultUrl), new DefaultAzureCredential()); #endregion #region Snippet:KeysSample4CreateKey // Let's create a RSA key which will be used to encrypt and decrypt string rsaKeyName = $"CloudRsaKey-{Guid.NewGuid()}"; var rsaKey = new CreateRsaKeyOptions(rsaKeyName, hardwareProtected: false) { KeySize = 2048, }; KeyVaultKey cloudRsaKey = keyClient.CreateRsaKey(rsaKey); Debug.WriteLine($"Key is returned with name {cloudRsaKey.Name} and type {cloudRsaKey.KeyType}"); #endregion #region Snippet:KeysSample4CryptographyClient var cryptoClient = new CryptographyClient(cloudRsaKey.Id, new DefaultAzureCredential()); #endregion #region Snippet:KeysSample4EncryptKey byte[] plaintext = Encoding.UTF8.GetBytes("A single block of plaintext"); EncryptResult encryptResult = cryptoClient.Encrypt(EncryptionAlgorithm.RsaOaep, plaintext); Debug.WriteLine($"Encrypted data using the algorithm {encryptResult.Algorithm}, with key {encryptResult.KeyId}. The resulting encrypted data is {Convert.ToBase64String(encryptResult.Ciphertext)}"); #endregion #region Snippet:KeysSample4DecryptKey DecryptResult decryptResult = cryptoClient.Decrypt(EncryptionAlgorithm.RsaOaep, encryptResult.Ciphertext); Debug.WriteLine($"Decrypted data using the algorithm {decryptResult.Algorithm}, with key {decryptResult.KeyId}. The resulting decrypted data is {Encoding.UTF8.GetString(decryptResult.Plaintext)}"); #endregion #region Snippet:KeysSample4DeleteKey DeleteKeyOperation operation = keyClient.StartDeleteKey(rsaKeyName); // You only need to wait for completion if you want to purge or recover the key. while (!operation.HasCompleted) { Thread.Sleep(2000); operation.UpdateStatus(); } #endregion // If the keyvault is soft-delete enabled, then for permanent deletion, deleted key needs to be purged. keyClient.PurgeDeletedKey(rsaKeyName); }
public void BackupAndRestoreSync() { // Environment variable with the Key Vault endpoint. string keyVaultUrl = Environment.GetEnvironmentVariable("AZURE_KEYVAULT_URL"); // Instantiate a key client that will be used to call the service. Notice that the client is using default Azure // credentials. To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID', // 'AZURE_CLIENT_KEY' and 'AZURE_TENANT_ID' are set with the service principal credentials. var client = new KeyClient(new Uri(keyVaultUrl), new DefaultAzureCredential()); // Let's create a RSA key valid for 1 year. If the key // already exists in the Key Vault, then a new version of the key is created. string rsaKeyName = $"CloudRsaKey-{Guid.NewGuid()}"; var rsaKey = new CreateRsaKeyOptions(rsaKeyName, hardwareProtected: false) { KeySize = 2048, ExpiresOn = DateTimeOffset.Now.AddYears(1) }; KeyVaultKey storedKey = client.CreateRsaKey(rsaKey); // Backups are good to have if in case keys get accidentally deleted by you. // For long term storage, it is ideal to write the backup to a file, disk, database, etc. // For the purposes of this sample, we are storing the bakup in a temporary memory area. byte[] backupKey = client.BackupKey(rsaKeyName); using (var memoryStream = new MemoryStream()) { memoryStream.Write(backupKey, 0, backupKey.Length); // The storage account key is no longer in use, so you delete it. DeleteKeyOperation operation = client.StartDeleteKey(rsaKeyName); // To ensure the key is deleted on server before we try to purge it. while (!operation.HasCompleted) { Thread.Sleep(2000); operation.UpdateStatus(); } // If the keyvault is soft-delete enabled, then for permanent deletion, deleted key needs to be purged. client.PurgeDeletedKey(rsaKeyName); // After sometime, the key is required again. We can use the backup value to restore it in the Key Vault. KeyVaultKey restoredKey = client.RestoreKeyBackup(memoryStream.ToArray()); AssertKeysEqual(storedKey.Properties, restoredKey.Properties); } }
protected void DefaultInit() { string tenantId = _configuration["Azure:Tenant_ID"]; string clientId = _configuration["Azure:Client_ID"]; string clientSecret = _configuration["Azure:Client_Secret"]; var clientCredentials = new ClientSecretCredential(tenantId, clientId, clientSecret); var keyClient = new KeyClient(new Uri(_keyVaultUri), clientCredentials); keyClient.CreateRsaKey(new CreateRsaKeyOptions(_keyVaultKeyName)); KeyVaultKey key = keyClient.GetKey(_keyVaultKeyName); _cryptoClient = new CryptographyClient(key.Id, new DefaultAzureCredential()); }
private void BackupAndRestoreSync(string keyVaultUrl) { #region Snippet:KeysSample2KeyClient var client = new KeyClient(new Uri(keyVaultUrl), new DefaultAzureCredential()); #endregion #region Snippet:KeysSample2CreateKey string rsaKeyName = $"CloudRsaKey-{Guid.NewGuid()}"; var rsaKey = new CreateRsaKeyOptions(rsaKeyName, hardwareProtected: false) { KeySize = 2048, ExpiresOn = DateTimeOffset.Now.AddYears(1) }; KeyVaultKey storedKey = client.CreateRsaKey(rsaKey); #endregion #region Snippet:KeysSample2BackupKey byte[] backupKey = client.BackupKey(rsaKeyName); #endregion using (var memoryStream = new MemoryStream()) { memoryStream.Write(backupKey, 0, backupKey.Length); // The storage account key is no longer in use, so you delete it. DeleteKeyOperation operation = client.StartDeleteKey(rsaKeyName); // To ensure the key is deleted on server before we try to purge it. while (!operation.HasCompleted) { Thread.Sleep(2000); operation.UpdateStatus(); } // If the keyvault is soft-delete enabled, then for permanent deletion, deleted key needs to be purged. client.PurgeDeletedKey(rsaKeyName); #region Snippet:KeysSample2RestoreKey KeyVaultKey restoredKey = client.RestoreKeyBackup(memoryStream.ToArray()); #endregion AssertKeysEqual(storedKey.Properties, restoredKey.Properties); } }
public void SignVerifySync() { // Environment variable with the Key Vault endpoint. string keyVaultUrl = Environment.GetEnvironmentVariable("AZURE_KEYVAULT_URL"); // Instantiate a key client that will be used to create a key. Notice that the client is using default Azure // credentials. To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID', // 'AZURE_CLIENT_KEY' and 'AZURE_TENANT_ID' are set with the service principal credentials. var keyClient = new KeyClient(new Uri(keyVaultUrl), new DefaultAzureCredential()); // First we'll create both a RSA key and an EC which will be used to sign and verify string rsaKeyName = $"CloudRsaKey-{Guid.NewGuid()}"; var rsaKey = new RsaKeyCreateOptions(rsaKeyName, hsm: false, keySize: 2048); string ecKeyName = $"CloudEcKey-{Guid.NewGuid()}"; var ecKey = new EcKeyCreateOptions(ecKeyName, hsm: false, curveName: KeyCurveName.P256K); Key cloudRsaKey = keyClient.CreateRsaKey(rsaKey); Debug.WriteLine($"Key is returned with name {cloudRsaKey.Name} and type {cloudRsaKey.KeyMaterial.KeyType}"); Key cloudEcKey = keyClient.CreateEcKey(ecKey); Debug.WriteLine($"Key is returned with name {cloudEcKey.Name} and type {cloudEcKey.KeyMaterial.KeyType}"); // Let's create the CryptographyClient which can perform cryptographic operations with the keys we just created. // Again we are using the default Azure credential as above. var rsaCryptoClient = new CryptographyClient(cloudRsaKey.Id, new DefaultAzureCredential()); var ecCryptoClient = new CryptographyClient(cloudEcKey.Id, new DefaultAzureCredential()); // Next we'll sign some arbitrary data and verify the signatures using the CryptographyClient with both the EC and RSA keys we created. byte[] data = Encoding.UTF8.GetBytes("This is some sample data which we will use to demonstrate sign and verify"); byte[] digest = null; // // Signing with the Sign and Verify methods // // The Sign and Verify methods expect a precalculated digest, and the digest needs to be calculated using the hash algorithm which matches the // singature algorithm being used. SHA256 is the hash algorithm used for both RS256 and ES256K which are the algorithms we'll be using in this sample using (HashAlgorithm hashAlgo = SHA256.Create()) { digest = hashAlgo.ComputeHash(data); } // Get the signature for the computed digest with both keys. Note that the signature algorithm specified must be a valid algorithm for the key type, // and for EC keys the algorithm must also match the curve of the key SignResult rsaSignResult = rsaCryptoClient.Sign(SignatureAlgorithm.Rs256, digest); Debug.WriteLine($"Signed digest using the algorithm {rsaSignResult.Algorithm}, with key {rsaSignResult.KeyId}. The resulting signature is {Convert.ToBase64String(rsaSignResult.Signature)}"); SignResult ecSignResult = ecCryptoClient.Sign(SignatureAlgorithm.Es256K, digest); Debug.WriteLine($"Signed digest using the algorithm {ecSignResult.Algorithm}, with key {ecSignResult.KeyId}. The resulting signature is {Convert.ToBase64String(ecSignResult.Signature)}"); // Verify the signatures VerifyResult rsaVerifyResult = rsaCryptoClient.Verify(SignatureAlgorithm.Rs256, digest, rsaSignResult.Signature); Debug.WriteLine($"Verified the signature using the algorithm {rsaVerifyResult.Algorithm}, with key {rsaVerifyResult.KeyId}. Signature is valid: {rsaVerifyResult.IsValid}"); VerifyResult ecVerifyResult = ecCryptoClient.Verify(SignatureAlgorithm.Es256K, digest, ecSignResult.Signature); Debug.WriteLine($"Verified the signature using the algorithm {ecVerifyResult.Algorithm}, with key {ecVerifyResult.KeyId}. Signature is valid: {ecVerifyResult.IsValid}"); // // Signing with the SignData and VerifyData methods // // The SignData and VerifyData methods take the raw data which is to be signed. The calculate the digest for the user so there is no need to compute the digest // Get the signature for the data with both keys. Note that the signature algorithm specified must be a valid algorithm for the key type, // and for EC keys the algorithm must also match the curve of the key SignResult rsaSignDataResult = rsaCryptoClient.SignData(SignatureAlgorithm.Rs256, data); Debug.WriteLine($"Signed data using the algorithm {rsaSignDataResult.Algorithm}, with key {rsaSignDataResult.KeyId}. The resulting signature is {Convert.ToBase64String(rsaSignDataResult.Signature)}"); SignResult ecSignDataResult = ecCryptoClient.SignData(SignatureAlgorithm.Es256K, data); Debug.WriteLine($"Signed data using the algorithm {ecSignDataResult.Algorithm}, with key {ecSignDataResult.KeyId}. The resulting signature is {Convert.ToBase64String(ecSignDataResult.Signature)}"); // Verify the signatures VerifyResult rsaVerifyDataResult = rsaCryptoClient.VerifyData(SignatureAlgorithm.Rs256, data, rsaSignDataResult.Signature); Debug.WriteLine($"Verified the signature using the algorithm {rsaVerifyDataResult.Algorithm}, with key {rsaVerifyDataResult.KeyId}. Signature is valid: {rsaVerifyDataResult.IsValid}"); VerifyResult ecVerifyDataResult = ecCryptoClient.VerifyData(SignatureAlgorithm.Es256K, data, ecSignDataResult.Signature); Debug.WriteLine($"Verified the signature using the algorithm {ecVerifyDataResult.Algorithm}, with key {ecVerifyDataResult.KeyId}. Signature is valid: {ecVerifyDataResult.IsValid}"); // The Cloud Keys are no longer needed, need to delete them from the Key Vault. keyClient.DeleteKey(rsaKeyName); keyClient.DeleteKey(ecKeyName); // To ensure the keys are deleted on server side. Assert.IsTrue(WaitForDeletedKey(keyClient, rsaKeyName)); Assert.IsTrue(WaitForDeletedKey(keyClient, ecKeyName)); // If the keyvault is soft-delete enabled, then for permanent deletion, deleted keys needs to be purged. keyClient.PurgeDeletedKey(rsaKeyName); keyClient.PurgeDeletedKey(ecKeyName); }
private PSKeyVaultKey CreateKey(KeyClient client, string keyName, PSKeyVaultKeyAttributes keyAttributes, int?size, string curveName) { // todo duplicated code with Track2VaultClient.CreateKey CreateKeyOptions options; bool isHsm = keyAttributes.KeyType == KeyType.RsaHsm || keyAttributes.KeyType == KeyType.EcHsm; if (keyAttributes.KeyType == KeyType.Rsa || keyAttributes.KeyType == KeyType.RsaHsm) { options = new CreateRsaKeyOptions(keyName, isHsm) { KeySize = size }; } else if (keyAttributes.KeyType == KeyType.Ec || keyAttributes.KeyType == KeyType.EcHsm) { options = new CreateEcKeyOptions(keyName, isHsm); if (string.IsNullOrEmpty(curveName)) { (options as CreateEcKeyOptions).CurveName = null; } else { (options as CreateEcKeyOptions).CurveName = new KeyCurveName(curveName); } } else { options = new CreateKeyOptions(); } // Common key attributes options.NotBefore = keyAttributes.NotBefore; options.ExpiresOn = keyAttributes.Expires; options.Enabled = keyAttributes.Enabled; options.Exportable = keyAttributes.Exportable; options.ReleasePolicy = keyAttributes.ReleasePolicy?.ToKeyReleasePolicy(); if (keyAttributes.KeyOps != null) { foreach (var keyOp in keyAttributes.KeyOps) { options.KeyOperations.Add(new KeyOperation(keyOp)); } } if (keyAttributes.Tags != null) { foreach (DictionaryEntry entry in keyAttributes.Tags) { options.Tags.Add(entry.Key.ToString(), entry.Value.ToString()); } } if (keyAttributes.KeyType == KeyType.Rsa || keyAttributes.KeyType == KeyType.RsaHsm) { return(new PSKeyVaultKey(client.CreateRsaKey(options as CreateRsaKeyOptions).Value, _uriHelper, isHsm: true)); } else if (keyAttributes.KeyType == KeyType.Ec || keyAttributes.KeyType == KeyType.EcHsm) { return(new PSKeyVaultKey(client.CreateEcKey(options as CreateEcKeyOptions).Value, _uriHelper, isHsm: true)); } else if (keyAttributes.KeyType == KeyType.Oct || keyAttributes.KeyType.ToString() == "oct-HSM") { return(new PSKeyVaultKey(client.CreateKey(keyName, KeyType.Oct, options).Value, _uriHelper, isHsm: true)); } else { throw new NotSupportedException($"{keyAttributes.KeyType} is not supported"); } }
public void SignVerifySync() { #if NET461 Assert.Ignore("Using CryptographyClient with EC keys is not supported on .NET Framework 4.6.1."); #endif // Environment variable with the Key Vault endpoint. string keyVaultUrl = TestEnvironment.KeyVaultUrl; #region Snippet:KeysSample5KeyClient var keyClient = new KeyClient(new Uri(keyVaultUrl), new DefaultAzureCredential()); #endregion #region Snippet:KeysSample5CreateKey string rsaKeyName = $"CloudRsaKey-{Guid.NewGuid()}"; var rsaKeyOptions = new CreateRsaKeyOptions(rsaKeyName, hardwareProtected: false) { KeySize = 2048, }; string ecKeyName = $"CloudEcKey-{Guid.NewGuid()}"; var ecKeyOptions = new CreateEcKeyOptions(ecKeyName, hardwareProtected: false) { CurveName = KeyCurveName.P256K, }; KeyVaultKey rsaKey = keyClient.CreateRsaKey(rsaKeyOptions); Debug.WriteLine($"Key is returned with name {rsaKey.Name} and type {rsaKey.KeyType}"); KeyVaultKey ecKey = keyClient.CreateEcKey(ecKeyOptions); Debug.WriteLine($"Key is returned with name {ecKey.Name} and type {ecKey.KeyType}"); #endregion #region Snippet:KeysSample5CryptographyClient var rsaCryptoClient = new CryptographyClient(rsaKey.Id, new DefaultAzureCredential()); var ecCryptoClient = new CryptographyClient(ecKey.Id, new DefaultAzureCredential()); #endregion #region Snippet:KeysSample5SignKey byte[] data = Encoding.UTF8.GetBytes("This is some sample data which we will use to demonstrate sign and verify"); byte[] digest = null; using (HashAlgorithm hashAlgo = SHA256.Create()) { digest = hashAlgo.ComputeHash(data); } SignResult rsaSignResult = rsaCryptoClient.Sign(SignatureAlgorithm.RS256, digest); Debug.WriteLine($"Signed digest using the algorithm {rsaSignResult.Algorithm}, with key {rsaSignResult.KeyId}. The resulting signature is {Convert.ToBase64String(rsaSignResult.Signature)}"); SignResult ecSignResult = ecCryptoClient.Sign(SignatureAlgorithm.ES256K, digest); Debug.WriteLine($"Signed digest using the algorithm {ecSignResult.Algorithm}, with key {ecSignResult.KeyId}. The resulting signature is {Convert.ToBase64String(ecSignResult.Signature)}"); #endregion #region Snippet:KeysSample5VerifySign VerifyResult rsaVerifyResult = rsaCryptoClient.Verify(SignatureAlgorithm.RS256, digest, rsaSignResult.Signature); Debug.WriteLine($"Verified the signature using the algorithm {rsaVerifyResult.Algorithm}, with key {rsaVerifyResult.KeyId}. Signature is valid: {rsaVerifyResult.IsValid}"); VerifyResult ecVerifyResult = ecCryptoClient.Verify(SignatureAlgorithm.ES256K, digest, ecSignResult.Signature); Debug.WriteLine($"Verified the signature using the algorithm {ecVerifyResult.Algorithm}, with key {ecVerifyResult.KeyId}. Signature is valid: {ecVerifyResult.IsValid}"); #endregion #region Snippet:KeysSample5SignKeyWithSignData SignResult rsaSignDataResult = rsaCryptoClient.SignData(SignatureAlgorithm.RS256, data); Debug.WriteLine($"Signed data using the algorithm {rsaSignDataResult.Algorithm}, with key {rsaSignDataResult.KeyId}. The resulting signature is {Convert.ToBase64String(rsaSignDataResult.Signature)}"); SignResult ecSignDataResult = ecCryptoClient.SignData(SignatureAlgorithm.ES256K, data); Debug.WriteLine($"Signed data using the algorithm {ecSignDataResult.Algorithm}, with key {ecSignDataResult.KeyId}. The resulting signature is {Convert.ToBase64String(ecSignDataResult.Signature)}"); #endregion #region Snippet:KeysSample5VerifyKeyWithData VerifyResult rsaVerifyDataResult = rsaCryptoClient.VerifyData(SignatureAlgorithm.RS256, data, rsaSignDataResult.Signature); Debug.WriteLine($"Verified the signature using the algorithm {rsaVerifyDataResult.Algorithm}, with key {rsaVerifyDataResult.KeyId}. Signature is valid: {rsaVerifyDataResult.IsValid}"); VerifyResult ecVerifyDataResult = ecCryptoClient.VerifyData(SignatureAlgorithm.ES256K, data, ecSignDataResult.Signature); Debug.WriteLine($"Verified the signature using the algorithm {ecVerifyDataResult.Algorithm}, with key {ecVerifyDataResult.KeyId}. Signature is valid: {ecVerifyDataResult.IsValid}"); #endregion #region Snippet:KeysSample5DeleteKeys DeleteKeyOperation rsaKeyOperation = keyClient.StartDeleteKey(rsaKeyName); DeleteKeyOperation ecKeyOperation = keyClient.StartDeleteKey(ecKeyName); // You only need to wait for completion if you want to purge or recover the key. while (!rsaKeyOperation.HasCompleted || !ecKeyOperation.HasCompleted) { Thread.Sleep(2000); rsaKeyOperation.UpdateStatus(); ecKeyOperation.UpdateStatus(); } #endregion // If the keyvault is soft-delete enabled, then for permanent deletion, deleted keys needs to be purged. keyClient.PurgeDeletedKey(rsaKeyName); keyClient.PurgeDeletedKey(ecKeyName); }
public void SerializeJsonWebKeySync() { // Environment variable with the Key Vault endpoint. string keyVaultUrl = TestEnvironment.KeyVaultUrl; #region Snippet:KeysSample7KeyClient var keyClient = new KeyClient(new Uri(keyVaultUrl), new DefaultAzureCredential()); #endregion #region Snippet:KeysSample7CreateKey string rsaKeyName = $"CloudRsaKey-{Guid.NewGuid()}"; var rsaKey = new CreateRsaKeyOptions(rsaKeyName, hardwareProtected: false) { KeySize = 2048, }; KeyVaultKey cloudRsaKey = keyClient.CreateRsaKey(rsaKey); Debug.WriteLine($"Key is returned with name {cloudRsaKey.Name} and type {cloudRsaKey.KeyType}"); #endregion string dir = Path.Combine(TestContext.CurrentContext.WorkDirectory, "samples", nameof(Sample7_SerializeJsonWebKey)); Directory.CreateDirectory(dir); string path = Path.Combine(dir, $"{nameof(SerializeJsonWebKeySync)}.json"); // Use `using` expression for clean sample, but scope it to close and dispose immediately. { #region Snippet:KeysSample7Serialize using FileStream file = File.Create(path); using (Utf8JsonWriter writer = new Utf8JsonWriter(file)) { JsonSerializer.Serialize(writer, cloudRsaKey.Key); } Debug.WriteLine($"Saved JWK to {path}"); #endregion } #region Snippet:KeysSamples7Deserialize byte[] buffer = File.ReadAllBytes(path); JsonWebKey jwk = JsonSerializer.Deserialize <JsonWebKey>(buffer); Debug.WriteLine($"Read JWK from {path} with ID {jwk.Id}"); #endregion string content = "plaintext"; #region Snippet:KeysSample7Encrypt var encryptClient = new CryptographyClient(jwk); byte[] plaintext = Encoding.UTF8.GetBytes(content); EncryptResult encrypted = encryptClient.Encrypt(EncryptParameters.RsaOaepParameters(plaintext)); Debug.WriteLine($"Encrypted: {Encoding.UTF8.GetString(plaintext)}"); #endregion byte[] ciphertext = encrypted.Ciphertext; #region Snippet:KeysSample7Decrypt CryptographyClient decryptClient = keyClient.GetCryptographyClient(cloudRsaKey.Name, cloudRsaKey.Properties.Version); DecryptResult decrypted = decryptClient.Decrypt(DecryptParameters.RsaOaepParameters(ciphertext)); Debug.WriteLine($"Decrypted: {Encoding.UTF8.GetString(decrypted.Plaintext)}"); #endregion DeleteKeyOperation operation = keyClient.StartDeleteKey(rsaKeyName); // You only need to wait for completion if you want to purge or recover the key. while (!operation.HasCompleted) { Thread.Sleep(2000); operation.UpdateStatus(); } // If the keyvault is soft-delete enabled, then for permanent deletion, deleted key needs to be purged. keyClient.PurgeDeletedKey(rsaKeyName); }
public void GetKeysSync() { // Environment variable with the Key Vault endpoint. string keyVaultUrl = Environment.GetEnvironmentVariable("AZURE_KEYVAULT_URL"); // Instantiate a key client that will be used to call the service. Notice that the client is using default Azure // credentials. To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID', // 'AZURE_CLIENT_KEY' and 'AZURE_TENANT_ID' are set with the service principal credentials. var client = new KeyClient(new Uri(keyVaultUrl), new DefaultAzureCredential()); // Let's create EC and RSA keys valid for 1 year. If the key // already exists in the Key Vault, then a new version of the key is created. string rsaKeyName = $"CloudRsaKey-{Guid.NewGuid()}"; var rsaKey = new RsaKeyCreateOptions(rsaKeyName, hsm: false, keySize: 2048) { Expires = DateTimeOffset.Now.AddYears(1) }; client.CreateRsaKey(rsaKey); string ecKeyName = $"CloudECKey-{Guid.NewGuid()}"; var ecKey = new EcKeyCreateOptions(ecKeyName, hsm: false) { Expires = DateTimeOffset.Now.AddYears(1) }; client.CreateEcKey(ecKey); // You need to check the type of keys that already exist in your Key Vault. // Let's list the keys and print their types. // List operations don't return the keys with key material information. // So, for each returned key we call GetKey to get the key with its key material information. IEnumerable <Response <KeyProperties> > keys = client.GetKeys(); foreach (KeyProperties key in keys) { Key keyWithType = client.GetKey(key.Name); Debug.WriteLine($"Key is returned with name {keyWithType.Name} and type {keyWithType.KeyMaterial.KeyType}"); } // We need the Cloud RSA key with bigger key size, so you want to update the key in Key Vault to ensure // it has the required size. // Calling CreateRsaKey on an existing key creates a new version of the key in the Key Vault // with the new specified size. var newRsaKey = new RsaKeyCreateOptions(rsaKeyName, hsm: false, keySize: 4096) { Expires = DateTimeOffset.Now.AddYears(1) }; client.CreateRsaKey(newRsaKey); // You need to check all the different versions Cloud RSA key had previously. // Lets print all the versions of this key. IEnumerable <Response <KeyProperties> > keysVersions = client.GetKeyVersions(rsaKeyName); foreach (KeyProperties key in keysVersions) { Debug.WriteLine($"Key's version {key.Version} with name {key.Name}"); } // The Cloud RSA Key and the Cloud EC Key are no longer needed. // You need to delete them from the Key Vault. client.DeleteKey(rsaKeyName); client.DeleteKey(ecKeyName); // To ensure secrets are deleted on server side. Assert.IsTrue(WaitForDeletedKey(client, rsaKeyName)); Assert.IsTrue(WaitForDeletedKey(client, ecKeyName)); // You can list all the deleted and non-purged keys, assuming Key Vault is soft-delete enabled. IEnumerable <Response <DeletedKey> > keysDeleted = client.GetDeletedKeys(); foreach (DeletedKey key in keysDeleted) { Debug.WriteLine($"Deleted key's recovery Id {key.RecoveryId}"); } // If the keyvault is soft-delete enabled, then for permanent deletion, deleted keys needs to be purged. client.PurgeDeletedKey(rsaKeyName); client.PurgeDeletedKey(ecKeyName); }
public void GetKeysSync() { // Environment variable with the Key Vault endpoint. string keyVaultUrl = TestEnvironment.KeyVaultUrl; #region Snippet:KeysSample3KeyClient var client = new KeyClient(new Uri(keyVaultUrl), new DefaultAzureCredential()); #endregion #region Snippet:KeysSample3CreateKey string rsaKeyName = $"CloudRsaKey-{Guid.NewGuid()}"; var rsaKey = new CreateRsaKeyOptions(rsaKeyName, hardwareProtected: false) { KeySize = 2048, ExpiresOn = DateTimeOffset.Now.AddYears(1) }; client.CreateRsaKey(rsaKey); string ecKeyName = $"CloudECKey-{Guid.NewGuid()}"; var ecKey = new CreateEcKeyOptions(ecKeyName, hardwareProtected: false) { ExpiresOn = DateTimeOffset.Now.AddYears(1) }; client.CreateEcKey(ecKey); #endregion #region Snippet:KeysSample3ListKeys IEnumerable <KeyProperties> keys = client.GetPropertiesOfKeys(); foreach (KeyProperties key in keys) { #if !SNIPPET if (key.Managed) { continue; } #endif KeyVaultKey keyWithType = client.GetKey(key.Name); Debug.WriteLine($"Key is returned with name {keyWithType.Name} and type {keyWithType.KeyType}"); } #endregion #region Snippet:KeysSample3UpdateKey var newRsaKey = new CreateRsaKeyOptions(rsaKeyName, hardwareProtected: false) { KeySize = 4096, ExpiresOn = DateTimeOffset.Now.AddYears(1) }; client.CreateRsaKey(newRsaKey); #endregion #region Snippet:KeysSample3ListKeyVersions IEnumerable <KeyProperties> keysVersions = client.GetPropertiesOfKeyVersions(rsaKeyName); foreach (KeyProperties key in keysVersions) { Debug.WriteLine($"Key's version {key.Version} with name {key.Name}"); } #endregion #region Snippet:KeysSample3DeletedKeys DeleteKeyOperation rsaKeyOperation = client.StartDeleteKey(rsaKeyName); DeleteKeyOperation ecKeyOperation = client.StartDeleteKey(ecKeyName); // You only need to wait for completion if you want to purge or recover the key. while (!rsaKeyOperation.HasCompleted || !ecKeyOperation.HasCompleted) { Thread.Sleep(2000); rsaKeyOperation.UpdateStatus(); ecKeyOperation.UpdateStatus(); } #endregion #region Snippet:KeysSample3ListDeletedKeys IEnumerable <DeletedKey> keysDeleted = client.GetDeletedKeys(); foreach (DeletedKey key in keysDeleted) { Debug.WriteLine($"Deleted key's recovery Id {key.RecoveryId}"); } #endregion // You only need to wait for completion if you want to purge or recover the key. // If the keyvault is soft-delete enabled, then for permanent deletion, deleted keys needs to be purged. client.PurgeDeletedKey(rsaKeyName); client.PurgeDeletedKey(ecKeyName); }