Пример #1
0
        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);
        }
Пример #2
0
 public KeyVaultService(IApiConfig apiConfig)
 {
     _apiConfig = apiConfig;
     _clientSecretCredential = new(_apiConfig.AzureIdentity.TenantId, _apiConfig.AzureIdentity.ClientId, _apiConfig.AzureIdentity.ClientSecret);
     _keyClient = new(new(_apiConfig.KeyVaultUri), _clientSecretCredential);
 }
        private async Task MigrationGuide()
        {
            #region Snippet:Azure_Security_KeyVault_Keys_Snippets_MigrationGuide_Create
            KeyClient client = new KeyClient(
                new Uri("https://myvault.vault.azure.net"),
                new DefaultAzureCredential());

            CryptographyClient cryptoClient = new CryptographyClient(
                new Uri("https://myvault.vault.azure.net"),
                new DefaultAzureCredential());
            #endregion Snippet:Azure_Security_KeyVault_Keys_Snippets_MigrationGuide_Create

            #region Snippet:Azure_Security_KeyVault_Keys_Snippets_MigrationGuide_CreateWithOptions
            using (HttpClient httpClient = new HttpClient())
            {
                KeyClientOptions options = new KeyClientOptions
                {
                    Transport = new HttpClientTransport(httpClient)
                };

#if SNIPPET
                KeyClient client = new KeyClient(
#else
                client = new KeyClient(
#endif
                    new Uri("https://myvault.vault.azure.net"),
                    new DefaultAzureCredential(),
                    options);

                CryptographyClientOptions cryptoOptions = new CryptographyClientOptions
                {
                    Transport = new HttpClientTransport(httpClient)
                };

#if SNIPPET
                CryptographyClient cryptoClient = new CryptographyClient(
#else
                cryptoClient = new CryptographyClient(
#endif
                    new Uri("https://myvault.vault.azure.net"),
                    new DefaultAzureCredential(),
                    cryptoOptions);
            }
            #endregion Snippet:Azure_Security_KeyVault_Keys_Snippets_MigrationGuide_CreateWithOptions

            {
                #region Snippet:Azure_Security_KeyVault_Keys_Snippets_MigrationGuide_CreateKeys
                // Create RSA key.
                CreateRsaKeyOptions createRsaOptions = new CreateRsaKeyOptions("rsa-key-name")
                {
                    KeySize = 4096
                };

                KeyVaultKey rsaKey = await client.CreateRsaKeyAsync(createRsaOptions);

                // Create Elliptic-Curve key.
                CreateEcKeyOptions createEcOptions = new CreateEcKeyOptions("ec-key-name")
                {
                    CurveName = KeyCurveName.P256
                };

                KeyVaultKey ecKey = await client.CreateEcKeyAsync(createEcOptions);

                #endregion Snippet:Azure_Security_KeyVault_Keys_Snippets_MigrationGuide_CreateKeys
            }

            {
                #region Snippet:Azure_Security_KeyVault_Keys_Snippets_MigrationGuide_ListKeys
                // List all keys asynchronously.
                await foreach (KeyProperties item in client.GetPropertiesOfKeysAsync())
                {
                    KeyVaultKey key = await client.GetKeyAsync(item.Name);
                }

                // List all keys synchronously.
                foreach (KeyProperties item in client.GetPropertiesOfKeys())
                {
                    KeyVaultKey key = client.GetKey(item.Name);
                }
                #endregion Snippet:Azure_Security_KeyVault_Keys_Snippets_MigrationGuide_ListKeys
            }

            {
                #region Snippet:Azure_Security_KeyVault_Keys_Snippets_MigrationGuide_DeleteKey
                // Delete the key.
                DeleteKeyOperation deleteOperation = await client.StartDeleteKeyAsync("key-name");

                // Purge or recover the deleted key if soft delete is enabled.
                if (deleteOperation.Value.RecoveryId != null)
                {
                    // Deleting a key does not happen immediately. Wait for the key to be deleted.
                    DeletedKey deletedKey = await deleteOperation.WaitForCompletionAsync();

                    // Purge the deleted key.
                    await client.PurgeDeletedKeyAsync(deletedKey.Name);

                    // You can also recover the deleted key using StartRecoverDeletedKeyAsync,
                    // which returns RecoverDeletedKeyOperation you can await like DeleteKeyOperation above.
                }
                #endregion Snippet:Azure_Security_KeyVault_Keys_Snippets_MigrationGuide_DeleteKey
            }

            {
                #region Snippet:Azure_Security_KeyVault_Keys_Snippets_MigrationGuide_Encrypt
                // Encrypt a message. The plaintext must be small enough for the chosen algorithm.
                byte[] plaintext        = Encoding.UTF8.GetBytes("Small message to encrypt");
                EncryptResult encrypted = await cryptoClient.EncryptAsync(EncryptionAlgorithm.RsaOaep256, plaintext);

                // Decrypt the message.
                DecryptResult decrypted = await cryptoClient.DecryptAsync(encrypted.Algorithm, encrypted.Ciphertext);

                string message = Encoding.UTF8.GetString(decrypted.Plaintext);
                                                         #endregion Snippet:Azure_Security_KeyVault_Keys_Snippets_MigrationGuide_Encrypt
            }

            {
                #region Snippet:Azure_Security_KeyVault_Keys_Snippets_MigrationGuide_Wrap
                using (Aes aes = Aes.Create())
                {
                    // Use a symmetric key to encrypt large amounts of data, possibly streamed...

                    // Now wrap the key and store the encrypted key and plaintext IV to later decrypt the key to decrypt the data.
                    WrapResult wrapped = await cryptoClient.WrapKeyAsync(KeyWrapAlgorithm.RsaOaep256, aes.Key);

                    // Read the IV and the encrypted key from the payload, then unwrap the key.
                    UnwrapResult unwrapped = await cryptoClient.UnwrapKeyAsync(wrapped.Algorithm, wrapped.EncryptedKey);

                    aes.Key = unwrapped.Key;

                    // Decrypt the payload with the symmetric key.
                }
                       #endregion Snippet:Azure_Security_KeyVault_Keys_Snippets_MigrationGuide_Wrap
            }
        }
Пример #4
0
 private PSKeyRotationPolicy GetKeyRotationPolicy(KeyClient client, string managedHsmName, string keyName)
 {
     return(new PSKeyRotationPolicy(client.GetKeyRotationPolicy(keyName), managedHsmName, keyName));
 }
Пример #5
0
        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");
            }
        }
Пример #6
0
        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 KeyVaultKeyDecryptor(ILogger <KeyVaultKeyDecryptor> logger, CryptographyClientFactory clientFactory, KeyClient keyClient)
 {
     _logger        = logger;
     _clientFactory = clientFactory;
     _keyClient     = keyClient;
 }
 public KeyVaultCredentialRotator(KeyClient keyClient, SecretClient secretClient, ILogger <KeyVaultCredentialRotator> logger)
 {
     _keyClient    = keyClient;
     _secretClient = secretClient;
     _logger       = logger;
 }
Пример #9
0
        public async Task InitialRequestTimesOut()
        {
            const string tenantId = "72f988bf-86f1-41af-91ab-2d7cd011db47";

            int requestIndex = 0;
            Func <MockRequest, MockResponse> factory = request =>
            {
                switch (requestIndex++)
                {
                case 0:
                    // Mimics the exact exception thrown during the initial request.
                    throw new RequestFailedException("Operation timed out", new HttpRequestException("Operation timed out", new SocketException(60)));

                case 1:
                    return(new MockResponse(401)
                           .WithHeader("WWW-Authenticate", $@"Bearer authorization=""https://login.windows.net/{tenantId}"", resource=""https://vault.azure.net""")
                           .WithContent(@"{""error"":{""code"":""Unauthorized"",""message"":""Error validating token: IDX10223""}}"));

                case 2:
                    Assert.IsNotNull(request.Content);
                    Assert.IsTrue(request.Content.TryComputeLength(out long length));
                    Assert.AreNotEqual(0, length);

                    return(new MockResponse(200)
                           // Copied from SessionRecords/KeyClientLiveTests/CreateRsaKey.json
                           .WithContent(@"{
  ""key"": {
    ""kid"": ""https://heathskeyvault.vault.azure.net/keys/625710934/ef3685592e1c4e839206aaa10f0f058e"",
    ""kty"": ""RSA"",
    ""key_ops"": [
      ""encrypt"",
      ""decrypt"",
      ""sign"",
      ""verify"",
      ""wrapKey"",
      ""unwrapKey""
    ],
    ""n"": ""7tp-vHhIdmj7phgSABe9eFb3WM3J8edzlZ9aXrBZFY6SlvCmSMPuHtNVteC_bFY42eqWb6xHz21Q8pSKmoD-ebPr00Rv2TK7k2miZRx-a_iF4hYWUMySVzUNszPoiRgUjEbEFpL2pPxpCVIO-C3nM2HPBUPZX5ATOUmO_Ioiw4vo_Q4pSaBXWrmT4Wf7c7WaVZ3KYofntuS0V4k0Q94fUyTVUEvWVeLg9Q_RhDVcY1pJX_cNaQUSm7v7yd6gPDKsEjC8HjGgV5QYWmO3ZBLnb0sY8Ond_iRWpBTM6dK7GB9W7jdvZd80azPbDxIhr68BWomwvRa_D19t0nSSGZDexQ"",
    ""e"": ""AQAB""
  },
  ""attributes"": {
    ""enabled"": true,
    ""created"": 1613807137,
    ""updated"": 1613807137,
    ""recoveryLevel"": ""Recoverable\u002BPurgeable"",
    ""recoverableDays"": 90
  }
}"));

                default:
                    // Should be done after the previous request.
                    throw new NotSupportedException("Should not have gotten this far");
                }
            };

            KeyClient client = InstrumentClient(
                new KeyClient(
                    new Uri("https://heathskeyvault.vault.azure.net"),
                    new MockCredential(),
                    new()
            {
                Transport = new MockTransport(factory),
            }));

            KeyVaultKey key = await client.CreateRsaKeyAsync(new("625710934")
            {
                KeySize = 2048,
            });
Пример #10
0
        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);
        }
Пример #11
0
 /// <summary>Initializes a new instance of the <see cref="KeyVaultKeyProvider"/> class.</summary>
 public KeyVaultKeyProvider(KeyClient client, long minimumRefreshInterval = DefaultMinimumRefreshInterval, long automaticRefreshInterval = DefaultAutomaticRefreshInterval)
     : base(minimumRefreshInterval, automaticRefreshInterval)
 {
     _client = client ?? throw new ArgumentNullException(nameof(client));
 }
Пример #12
0
 /// <summary>Initializes a new instance of the <see cref="KeyVaultKeyProvider"/> class.</summary>
 public KeyVaultKeyProvider(string issuer, KeyClient client)
 {
     _issuer = issuer ?? throw new ArgumentNullException(nameof(issuer));
     _client = client ?? throw new ArgumentNullException(nameof(client));
 }
Пример #13
0
 /// <summary>Configure the signature behavior with Key Vault for a specific <paramref name="client"/>.</summary>
 public static TokenValidationPolicyBuilder RequireSignatureWithKeyVault(this TokenValidationPolicyBuilder builder, KeyClient client, SignatureAlgorithm algorithm, long minimumRefreshInterval = CachedKeyProvider.DefaultMinimumRefreshInterval, long automaticRefreshInterval = CachedKeyProvider.DefaultAutomaticRefreshInterval)
 => builder.RequireSignature(client.VaultUri.ToString(), new KeyVaultKeyProvider(client, minimumRefreshInterval, automaticRefreshInterval), algorithm);
Пример #14
0
        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);
        }
Пример #15
0
 public KeyVaultIntegration(KeyVaultOptions options)
 {
     SecretClient      = new SecretClient(vaultUri: new Uri(options.Url), credential: new DefaultAzureCredential(), options: options.SecretOptions);
     CertificateClient = new CertificateClient(vaultUri: new Uri(options.Url), credential: new DefaultAzureCredential(), options: options.CertificateOptions);
     KeyClient         = new KeyClient(vaultUri: new Uri(options.Url), credential: new DefaultAzureCredential(), options: options.KeyOptions);
 }
Пример #16
0
        static async Task Main(string[] args)
        {
            // Create a new key client using the default credential from Azure.Identity using environment variables previously set,
            // including AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, and AZURE_TENANT_ID.
            var client = new KeyClient(vaultUri: new Uri(keyVaultUrl), credential: new ClientSecretCredential(tenantId, clientId, clientSecret));

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

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

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

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

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


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

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

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

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

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

            DeletedKey deletedKey = operation.Value;

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

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

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

            await recoverOperation.WaitForCompletionAsync();

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

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

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

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

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

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

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

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

            await deleteOperation.WaitForCompletionAsync();

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

            Console.WriteLine("Purge Initiated.");
            Console.WriteLine($"purgekey.Name: {purgekey.Name}");
            Console.WriteLine("==================================================");
            Console.WriteLine();
        }
Пример #17
0
        static async Task <int> Main()
        {
            // 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());

            int       repeat = 0;
            const int total  = 3;

            while (++repeat <= total)
            {
                Console.WriteLine("Repeat #{0}...", repeat);
                try
                {
                    // 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)
                    };

                    await client.CreateRsaKeyAsync(rsaKey);

                    // Let's Get the Cloud RSA Key from the Key Vault.
                    KeyVaultKey cloudRsaKey = await client.GetKeyAsync(rsaKeyName);

                    Console.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 = await client.UpdateKeyPropertiesAsync(cloudRsaKey.Properties, cloudRsaKey.KeyOperations);

                    Console.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)
                    };

                    await client.CreateRsaKeyAsync(newRsaKey);

                    // The Cloud RSA Key is no longer needed, need to delete it from the Key Vault.
                    DeleteKeyOperation operation = await client.StartDeleteKeyAsync(rsaKeyName);

                    #region Snippet:KeysSample1PurgeKeyAsync
                    // You only need to wait for completion if you want to purge or recover the key.
                    await operation.WaitForCompletionAsync();

                    await client.PurgeDeletedKeyAsync(rsaKeyName);

                    #endregion
                }
                catch (RequestFailedException ex)
                {
                    Console.WriteLine($"Request failed! {ex.Message} {ex.StackTrace}");
                    return(-1);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Unexpected exception! {ex.Message} {ex.StackTrace}");
                    return(-1);
                }
            }
            Console.WriteLine("Success!");
            return(0);
        }
Пример #18
0
 private PSKeyVaultKey GetKey(KeyClient client, string keyName, string keyVersion)
 {
     return(new PSKeyVaultKey(client.GetKey(keyName, keyVersion).Value, _vaultUriHelper));
 }
Пример #19
0
        public async Task SignVerifyAsync()
        {
#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 = 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 CreateRsaKeyOptions(rsaKeyName, hardwareProtected: false)
            {
                KeySize = 2048,
            };

            string ecKeyName = $"CloudEcKey-{Guid.NewGuid()}";
            var    ecKey     = new CreateEcKeyOptions(ecKeyName, hardwareProtected: false)
            {
                CurveName = KeyCurveName.P256K,
            };

            KeyVaultKey cloudRsaKey = await keyClient.CreateRsaKeyAsync(rsaKey);

            Debug.WriteLine($"Key is returned with name {cloudRsaKey.Name} and type {cloudRsaKey.KeyType}");

            KeyVaultKey cloudEcKey = await keyClient.CreateEcKeyAsync(ecKey);

            Debug.WriteLine($"Key is returned with name {cloudEcKey.Name} and type {cloudEcKey.KeyType}");

            // Let's create the CryptographyClient which can perform cryptographic operations with the keys we just created using the same credential created 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 SignAsync and VerifyAsync methods
            //

            // The SignAsync and VerifyAsync methods expect a precalculated digest, and the digest needs to be calculated using the hash algorithm which matches the
            // signature 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 = await rsaCryptoClient.SignAsync(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 = await ecCryptoClient.SignAsync(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 = await rsaCryptoClient.VerifyAsync(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 = await ecCryptoClient.VerifyAsync(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 SignDataAsync and VerifyDataAsync methods
            //

            // The SignDataAsync and VerifyDataAsync 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 = await rsaCryptoClient.SignDataAsync(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 = await ecCryptoClient.SignDataAsync(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 = await rsaCryptoClient.VerifyDataAsync(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 = await ecCryptoClient.VerifyDataAsync(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.
            DeleteKeyOperation rsaKeyOperation = await keyClient.StartDeleteKeyAsync(rsaKeyName);

            DeleteKeyOperation ecKeyOperation = await keyClient.StartDeleteKeyAsync(ecKeyName);

            // You only need to wait for completion if you want to purge or recover the key.
            await Task.WhenAll(
                rsaKeyOperation.WaitForCompletionAsync().AsTask(),
                ecKeyOperation.WaitForCompletionAsync().AsTask());

            // If the keyvault is soft-delete enabled, then for permanent deletion, deleted keys needs to be purged.
            await Task.WhenAll(
                keyClient.PurgeDeletedKeyAsync(rsaKeyName),
                keyClient.PurgeDeletedKeyAsync(ecKeyName));
        }
Пример #20
0
 private PSKeyVaultKey RotateKey(KeyClient client, string keyName)
 {
     return(new PSKeyVaultKey(client.RotateKey(keyName), _vaultUriHelper));
 }
Пример #21
0
 private PSKeyVaultKey RotateKey(KeyClient client, string keyName)
 {
     return(new PSKeyVaultKey(client.RotateKey(keyName), _uriHelper, isHsm: true));
 }
Пример #22
0
 private PSKeyRotationPolicy GetKeyRotationPolicy(KeyClient client, string vaultName, string keyName)
 {
     return(new PSKeyRotationPolicy(client.GetKeyRotationPolicy(keyName), vaultName, keyName));
 }
Пример #23
0
 private PSKeyRotationPolicy SetKeyRotationPolicy(KeyClient client, string managedHsmName, string keyName, KeyRotationPolicy keyRotationPolicy)
 {
     return(new PSKeyRotationPolicy(client.UpdateKeyRotationPolicy(keyName, keyRotationPolicy), managedHsmName, keyName));
 }
Пример #24
0
 private PSKeyRotationPolicy SetKeyRotationPolicy(KeyClient client, string vaultName, string keyName, KeyRotationPolicy policy)
 {
     return(new PSKeyRotationPolicy(client.UpdateKeyRotationPolicy(keyName, policy), vaultName, keyName));
 }
        public async Task SerializeJsonWebKeyAsync()
        {
            // Environment variable with the Key Vault endpoint.
            string keyVaultUrl = TestEnvironment.KeyVaultUrl;

            var keyClient = new KeyClient(new Uri(keyVaultUrl), new DefaultAzureCredential());

            string rsaKeyName = $"CloudRsaKey-{Guid.NewGuid()}";
            var    rsaKey     = new CreateRsaKeyOptions(rsaKeyName, hardwareProtected: false)
            {
                KeySize = 2048,
            };

            KeyVaultKey cloudRsaKey = await keyClient.CreateRsaKeyAsync(rsaKey);

            Debug.WriteLine($"Key is returned with name {cloudRsaKey.Name} and type {cloudRsaKey.KeyType}");

            string dir = Path.Combine(TestContext.CurrentContext.WorkDirectory, "samples", nameof(Sample7_SerializeJsonWebKey));

            Directory.CreateDirectory(dir);

            string path = Path.Combine(dir, $"{nameof(SerializeJsonWebKeyAsync)}.json");

            // Use `using` expression for clean sample, but scope it to close and dispose immediately.
            {
                using FileStream file = File.Create(path);
                await JsonSerializer.SerializeAsync(file, cloudRsaKey.Key);

                Debug.WriteLine($"Saved JWK to {path}");
            }

            // Use `using` expression for clean sample, but scope it to close and dispose immediately.
            JsonWebKey jwk = null;
            {
                using FileStream file = File.Open(path, FileMode.Open);
                jwk = await JsonSerializer.DeserializeAsync <JsonWebKey>(file);

                Debug.WriteLine($"Read JWK from {path} with ID {jwk.Id}");
            }

            string content = "plaintext";

            var encryptClient = new CryptographyClient(jwk);

            byte[]        plaintext = Encoding.UTF8.GetBytes(content);
            EncryptResult encrypted = await encryptClient.EncryptAsync(EncryptParameters.RsaOaepParameters(plaintext));

            Debug.WriteLine($"Encrypted: {Encoding.UTF8.GetString(plaintext)}");

            byte[] ciphertext = encrypted.Ciphertext;

            CryptographyClient decryptClient = keyClient.GetCryptographyClient(cloudRsaKey.Name, cloudRsaKey.Properties.Version);
            DecryptResult      decrypted     = await decryptClient.DecryptAsync(DecryptParameters.RsaOaepParameters(ciphertext));

            Debug.WriteLine($"Decrypted: {Encoding.UTF8.GetString(decrypted.Plaintext)}");

            DeleteKeyOperation operation = await keyClient.StartDeleteKeyAsync(rsaKeyName);

            // You only need to wait for completion if you want to purge or recover the key.
            await operation.WaitForCompletionAsync();

            // If the keyvault is soft-delete enabled, then for permanent deletion, deleted key needs to be purged.
            keyClient.PurgeDeletedKey(rsaKeyName);
        }
Пример #26
0
        public void BackupAndRestoreSync()
        {
            // Environment variable with the Key Vault endpoint.
            string keyVaultUrl = Environment.GetEnvironmentVariable("AZURE_KEYVAULT_URL");

            #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);

                // Delete and purge the restored key.
                operation = client.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();
                }

                client.PurgeDeletedKey(rsaKeyName);
            }
        }
Пример #27
0
        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);
        }
        /**
         * Azure SQL sample for managing SQL secrets (Server Keys) using Azure Key Vault -
         *  - Create a SQL Server with "system assigned" managed service identity.
         *  - Create an Azure Key Vault with giving access to the SQL Server
         *  - Create, get, list and delete SQL Server Keys
         *  - Delete SQL Server
         */
        public static async Task RunSample(IAzure azure)
        {
            try
            {
                // ============================================================
                // Create a SQL Server with system assigned managed service identity.
                Utilities.Log("Creating a SQL Server with system assigned managed service identity");

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

                Utilities.PrintSqlServer(sqlServer);

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

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

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

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

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

                string keyUri = keyBundle.Value.Key.Id;

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

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

                Utilities.PrintSqlServerKey(sqlServerKey);


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

                sqlServerKey = sqlServer.ServerKeys.Get(serverKeyName);

                Utilities.PrintSqlServerKey(sqlServerKey);


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

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


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


                // Delete the SQL Server.
                Utilities.Log("Deleting a Sql Server");
                azure.SqlServers.DeleteById(sqlServer.Id);
            }
            finally
            {
                try
                {
                    Utilities.Log("Deleting Resource Group: " + rgName);
                    azure.ResourceGroups.DeleteByName(rgName);
                    Utilities.Log("Deleted Resource Group: " + rgName);
                }
                catch (Exception e)
                {
                    Utilities.Log(e);
                }
            }
        }
Пример #29
0
        public async Task GetKeysAsync()
        {
            // 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 CreateRsaKeyOptions(rsaKeyName, hardwareProtected: false)
            {
                KeySize   = 2048,
                ExpiresOn = DateTimeOffset.Now.AddYears(1)
            };

            await client.CreateRsaKeyAsync(rsaKey);

            string ecKeyName = $"CloudECKey-{Guid.NewGuid()}";
            var    ecKey     = new CreateEcKeyOptions(ecKeyName, hardwareProtected: false)
            {
                ExpiresOn = DateTimeOffset.Now.AddYears(1)
            };

            await client.CreateEcKeyAsync(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 actual key, but only properties of the key.
            // So, for each returned key we call GetKey to get the actual key.
            await foreach (KeyProperties key in client.GetPropertiesOfKeysAsync())
            {
                KeyVaultKey keyWithType = await client.GetKeyAsync(key.Name);

                Debug.WriteLine($"Key is returned with name {keyWithType.Name} and type {keyWithType.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 CreateRsaKeyOptions(rsaKeyName, hardwareProtected: false)
            {
                KeySize   = 4096,
                ExpiresOn = DateTimeOffset.Now.AddYears(1)
            };

            await client.CreateRsaKeyAsync(newRsaKey);

            // You need to check all the different versions Cloud RSA key had previously.
            // Lets print all the versions of this key.
            await foreach (KeyProperties key in client.GetPropertiesOfKeyVersionsAsync(rsaKeyName))
            {
                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.
            DeleteKeyOperation rsaKeyOperation = await client.StartDeleteKeyAsync(rsaKeyName);

            DeleteKeyOperation ecKeyOperation = await client.StartDeleteKeyAsync(ecKeyName);

            // You only need to wait for completion if you want to purge or recover the key.
            await Task.WhenAll(
                rsaKeyOperation.WaitForCompletionAsync().AsTask(),
                ecKeyOperation.WaitForCompletionAsync().AsTask());

            // You can list all the deleted and non-purged keys, assuming Key Vault is soft-delete enabled.
            await foreach (DeletedKey key in client.GetDeletedKeysAsync())
            {
                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.
            await Task.WhenAll(
                client.PurgeDeletedKeyAsync(rsaKeyName),
                client.PurgeDeletedKeyAsync(ecKeyName));
        }
Пример #30
0
        public async Task GetKeysAsync(string realm)
        {
            var result = await KeyClient.GetKeysAsync(realm);

            Assert.NotNull(result);
        }