Пример #1
0
        public static void ReturnSpecifiedVersionOfKeyWhenItIsNotTheMostRecentVersion()
        {
            Uri keyPathUri = new Uri(DataTestUtility.AKVOriginalUrl);
            Uri vaultUri   = new Uri(keyPathUri.GetLeftPart(UriPartial.Authority));

            //If key version is not specified then we cannot test.
            if (KeyIsVersioned(keyPathUri))
            {
                string keyName    = keyPathUri.Segments[2];
                string keyVersion = keyPathUri.Segments[3];
                ClientSecretCredential clientSecretCredential = new ClientSecretCredential(DataTestUtility.AKVTenantId, DataTestUtility.AKVClientId, DataTestUtility.AKVClientSecret);
                KeyClient   keyClient           = new KeyClient(vaultUri, clientSecretCredential);
                KeyVaultKey currentVersionKey   = keyClient.GetKey(keyName);
                KeyVaultKey specifiedVersionKey = keyClient.GetKey(keyName, keyVersion);

                //If specified versioned key is the most recent version of the key then we cannot test.
                if (!KeyIsLatestVersion(specifiedVersionKey, currentVersionKey))
                {
                    SqlColumnEncryptionAzureKeyVaultProvider azureKeyProvider = new SqlColumnEncryptionAzureKeyVaultProvider(clientSecretCredential);
                    // Perform an operation to initialize the internal caches
                    azureKeyProvider.EncryptColumnEncryptionKey(DataTestUtility.AKVOriginalUrl, EncryptionAlgorithm, s_columnEncryptionKey);

                    PropertyInfo keyCryptographerProperty = azureKeyProvider.GetType().GetProperty("KeyCryptographer", BindingFlags.NonPublic | BindingFlags.Instance);
                    var          keyCryptographer         = keyCryptographerProperty.GetValue(azureKeyProvider);
                    MethodInfo   getKeyMethod             = keyCryptographer.GetType().GetMethod("GetKey", BindingFlags.NonPublic | BindingFlags.Instance);
                    KeyVaultKey  key = (KeyVaultKey)getKeyMethod.Invoke(keyCryptographer, new[] { DataTestUtility.AKVOriginalUrl });

                    Assert.Equal(keyVersion, key.Properties.Version);
                }
            }
        }
Пример #2
0
        public void RetrieveKey()
        {
            // Make sure a key exists.
            client.CreateKey("key-name", KeyType.Rsa);

            #region Snippet:RetrieveKey
            KeyVaultKey key = client.GetKey("key-name");

            Console.WriteLine(key.Name);
            Console.WriteLine(key.KeyType);
            #endregion
        }
Пример #3
0
        public override void Configure(IFunctionsHostBuilder builder)
        {
            var websiteResourceGroupEnvironmentVariable = GetWebsiteResourceGroupEnvironmentVariable();

            var credential = new DefaultAzureCredential();

            builder.Services.AddAzureClients((builder) =>
            {
                builder.UseCredential(credential);

                var keyVaultUri = new Uri($"https://{websiteResourceGroupEnvironmentVariable}.vault.azure.net");
                builder.AddSecretClient(keyVaultUri);

                var configurationUri = new Uri($"https://{websiteResourceGroupEnvironmentVariable}.azconfig.io/");
                builder.AddConfigurationClient(configurationUri);

                // To inject the cryptography client with the extension helpers
                // here we need to first find the Key ID.
                var keyClient   = new KeyClient(keyVaultUri, credential);
                KeyVaultKey key = keyClient.GetKey("github-app-private-key");
                builder.AddCryptographyClient(key.Id);
            });

            builder.Services.AddSingleton <IPullRequestTracker, PullRequestTracker>();
            builder.Services.AddSingleton <GitHubRateLimiter>();
            builder.Services.AddSingleton <IGlobalConfigurationProvider, GlobalConfigurationProvider>();
            builder.Services.AddSingleton <IGitHubClientProvider, GitHubClientProvider>();
            builder.Services.AddSingleton <IRepositoryConfigurationProvider, RepositoryConfigurationProvider>();
            builder.Services.AddSingleton <GitHubWebhookProcessor>();
            builder.Services.AddMemoryCache();
        }
Пример #4
0
        static void Main(string[] args)
        {
            string keyVaultUrl = "https://demovault2090.vault.azure.net/";
            var    client      = new KeyClient(vaultUri: new Uri(keyVaultUrl), credential: new DefaultAzureCredential());

            // Getting the Encryption key from the key vault
            KeyVaultKey key = client.GetKey("newkey");

            var cryptoClient = new CryptographyClient(keyId: key.Id, credential: new DefaultAzureCredential());

            byte[] plaintext = Encoding.UTF8.GetBytes("This is sensitive data");

            // Encrypting data
            EncryptResult encryptResult = cryptoClient.Encrypt(EncryptionAlgorithm.RsaOaep256, plaintext);

            //Decrypting data
            DecryptResult decryptResult = cryptoClient.Decrypt(EncryptionAlgorithm.RsaOaep256, encryptResult.Ciphertext);

            Console.WriteLine("Plain text");

            string txt = Encoding.UTF8.GetString(decryptResult.Plaintext);

            Console.WriteLine(txt);
            Console.ReadLine();
        }
Пример #5
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string name = req.Query["name"];

            //var credential = new ClientSecretCredential("231dd9cd-ddc7-4fba-ae78-9f4ac3c912e7", "5f43fe5c-1c2b-4afa-97e6-fda41302e28b", "5ZlLakKHA:DE.6Jq-GbJWF=icJaCwW32");
            var credential = new ManagedIdentityCredential();
            var kvUri      = "https://kvswapana.vault.azure.net/";

            var           secretClient = new SecretClient(new Uri(kvUri), credential);
            var           encryptedDEK = secretClient.GetSecret("DEK");
            var           keyClient    = new KeyClient(new Uri(kvUri), credential);
            var           encryptedKEY = keyClient.GetKey("KEK");
            var           cryptoClient = new CryptographyClient(encryptedKEY.Value.Id, credential);
            DecryptResult decryptDek   = cryptoClient.Decrypt(EncryptionAlgorithm.RsaOaep256, Convert.FromBase64String(encryptedDEK.Value.Value));

            string  requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data        = JsonConvert.DeserializeObject(requestBody);

            name = name ?? data?.name;

            return(name != null
                   // Create MemoryStream
                ? (ActionResult) new OkObjectResult($"Hello, {name}, {encryptedKEY.Value.Id}, {Encoding.UTF8.GetString(decryptDek.Plaintext)}")
                : new BadRequestObjectResult("Please pass a name on the query string or in the request body"));
        }
Пример #6
0
        public void CreateClient()
        {
            // Environment variable with the Key Vault endpoint.
            string vaultUrl = TestEnvironment.KeyVaultUrl;

            #region Snippet:CreateKeyClient
            // Create a new key client using the default credential from Azure.Identity using environment variables previously set,
            // including AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, and AZURE_TENANT_ID.
            var client = new KeyClient(vaultUri: new Uri(vaultUrl), credential: new DefaultAzureCredential());

            // Create a new key using the key client.
            KeyVaultKey key = client.CreateKey("key-name", KeyType.Rsa);

            // Retrieve a key using the key client.
            key = client.GetKey("key-name");
            #endregion

            #region Snippet:CreateCryptographyClient
            // Create a new cryptography client using the same Key Vault or Managed HSM endpoint, service version,
            // and options as the KeyClient created earlier.
            var cryptoClient = client.GetCryptographyClient(key.Name, key.Properties.Version);
            #endregion

            this.client       = client;
            this.cryptoClient = cryptoClient;
        }
Пример #7
0
        public void DeleteKeyFromVault_Purge_CompletelyRemovedKey()
        {
            var storeLogger = _loggerFactory.CreateLogger <KeyVaultKeyStorer>();
            var storer      = new KeyVaultKeyStorer(_client, storeLogger);

            var deleteLogger = _loggerFactory.CreateLogger <KeyVaultKeyDeleter>();
            var deleter      = new KeyVaultKeyDeleter(_client, deleteLogger);

            storer.Store(_keyName, KeyType.Ec);

            deleter.Delete(new KeyVaultKeyDeleteEvent
            {
                Name  = _keyName,
                Purge = true
            });

            Action action = () => _client.GetKey(_keyName);

            action.Should().ThrowExactly <RequestFailedException>().Where(e =>
                                                                          e.Message.Contains($"A key with (name/id) {_keyName} was not found in this key vault.",
                                                                                             StringComparison.InvariantCultureIgnoreCase));
            action = () => _client.GetDeletedKey(_keyName);

            action.Should().ThrowExactly <RequestFailedException>();
        }
Пример #8
0
        public void CreateClient()
        {
            // Environment variable with the Key Vault endpoint.
            string keyVaultUrl = TestEnvironment.KeyVaultUrl;

            #region Snippet:CreateKeyClient
            // Create a new key client using the default credential from Azure.Identity using environment variables previously set,
            // including AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, and AZURE_TENANT_ID.
            var client = new KeyClient(vaultUri: new Uri(keyVaultUrl), credential: new DefaultAzureCredential());

            // Create a new key using the key client.
            KeyVaultKey key = client.CreateKey("key-name", KeyType.Rsa);

            // Retrieve a key using the key client.
            key = client.GetKey("key-name");
            #endregion

            #region Snippet:CreateCryptographyClient
            // Create a new certificate client using the default credential from Azure.Identity using environment variables previously set,
            // including AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, and AZURE_TENANT_ID.
            var cryptoClient = new CryptographyClient(keyId: key.Id, credential: new DefaultAzureCredential());
            #endregion

            this.client       = client;
            this.cryptoClient = cryptoClient;
        }
Пример #9
0
        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);
        }
Пример #10
0
        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
        }
Пример #11
0
        public void RSAKeyTest()
        {
            var keyClient = new KeyClient(new Uri("{{your keyvault uri}}"), new DefaultAzureCredential());
            Response <KeyVaultKey> response = keyClient.GetKey("SingInCredentialsKey");

            RSA rsa = response.Value.Key.ToRSA();

            Assert.NotNull(response.Value.Properties.Version);
        }
Пример #12
0
        //Creates a key in a specified Azure Key Vault to use for customer managed key server side encryption
        private static KeyVaultKey CreateKeyVaultKey(string keyVaultName, string keyVaultKeyName, TokenCredential credential)
        {
            Uri       keyVaultUri = new Uri("https://" + keyVaultName + ".vault.azure.net");
            KeyClient keyClient   = new KeyClient(keyVaultUri, credential);
            KeyType   keyType     = new KeyType("RSA");

            keyClient.CreateKey(keyVaultKeyName, keyType);
            return(keyClient.GetKey(keyVaultKeyName));
        }
        public EncryptResult Encrypt(string keyName, string data, string algorithm)
        {
            _logger.LogInformation("Getting Key with name: {keyName}", keyName);
            var key = _client.GetKey(keyName).Value;


            _logger.LogInformation("Encrypting data with keyid {Id}", key.Id.ToString());
            var client = _factory.CreateCryptographyClient(key.Id.ToString());

            return(client.Encrypt(new EncryptionAlgorithm(algorithm ?? "RSA1_5"), data.JsonDataToByteArray()));
        }
        public DecryptResult Decrypt(string keyName, string encryptedData, string algorithm)
        {
            _logger.LogInformation("Getting Key with name: {KeyName}", keyName);
            var key = _keyClient.GetKey(keyName).Value;

            var cryptoClient = _clientFactory.CreateCryptographyClient(key.Id.ToString());

            _logger.LogInformation("Decrypting data with keyid {Id}", key.Id.ToString());

            return(cryptoClient.Decrypt(new EncryptionAlgorithm(algorithm ?? "RSA1_5"), encryptedData.GetBytes()));
        }
        public byte[] Sign(string keyId, SignatureAlgorithm algorithm, byte[] digest)
        {
            KeyVaultKey cloudRsaKey     = client.GetKey(keyId);
            var         rsaCryptoClient = new CryptographyClient(cloudRsaKey.Id, defaultAzureCredential);

            SignResult rsaSignResult = rsaCryptoClient.Sign(algorithm, digest);

            Debug.WriteLine($"Signed digest using the algorithm {rsaSignResult.Algorithm}, with key {rsaSignResult.KeyId}. " +
                            $"The resulting signature is {Convert.ToBase64String(rsaSignResult.Signature)}");

            return(rsaSignResult.Signature);
        }
Пример #16
0
        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
        }
Пример #17
0
        static void list()
        {
            Console.WriteLine("Enter KeyVault URI");
            var keyvaultURI = Console.ReadLine();

            Console.WriteLine("Enter key name in key vault");
            var key = Console.ReadLine();

            var client = new KeyClient(new Uri(keyvaultURI), new DefaultAzureCredential());

            client.GetKey(key);
        }
Пример #18
0
        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);
        }
Пример #19
0
        static void Main(string[] args)
        {
            var credential = new InteractiveBrowserCredential();

            var kvUri = "[key vault uri]";

            var           client              = new KeyClient(new Uri(kvUri), credential);
            var           key                 = client.GetKey("[kek key name]");
            var           cryptoClient        = new CryptographyClient(key.Value.Id, credential);
            var           secretClient        = new SecretClient(new Uri(kvUri), credential);
            var           encryptedDEK        = secretClient.GetSecret("[dek key name]");
            DecryptResult decryptDek          = cryptoClient.Decrypt(EncryptionAlgorithm.RsaOaep256, Convert.FromBase64String(encryptedDEK.Value.Value));
            var           keynew              = decryptDek.Plaintext[0..16];
Пример #20
0
        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());
        }
Пример #21
0
        protected override Jwks GetKeysFromSource()
        {
            var keys = new List <Jwk>();

            foreach (var keyProperties in _client.GetPropertiesOfKeys())
            {
                var kvKey = _client.GetKey(keyProperties.Name);
                Jwk?key   = null;
                if (kvKey.Value.KeyType == KeyType.Oct)
                {
                    key = SymmetricJwk.FromByteArray(kvKey.Value.Key.K, false);
                }
                else if (kvKey.Value.KeyType == KeyType.Rsa || kvKey.Value.KeyType == KeyType.RsaHsm)
                {
                    key = RsaJwk.FromParameters(kvKey.Value.Key.ToRSA(true).ExportParameters(true), false);
                }
#if !NETFRAMEWORK
                else if (kvKey.Value.KeyType == KeyType.Ec || kvKey.Value.KeyType == KeyType.EcHsm)
                {
                    ECJwk.FromParameters(ConvertToECParameters(kvKey.Value), computeThumbprint: false);
                }
#endif

                if (!(key is null))
                {
                    key.Kid = JsonEncodedText.Encode(kvKey.Value.Key.Id);
                    if (kvKey.Value.Key.KeyOps != null)
                    {
                        foreach (var operation in kvKey.Value.Key.KeyOps)
                        {
                            key.KeyOps.Add(JsonEncodedText.Encode(operation.ToString()));
                        }
                    }

                    keys.Add(key);
                }
            }

            return(new Jwks(_client.VaultUri.ToString(), keys));
        }
Пример #22
0
        static void Main(string[] args)
        {
            Console.WriteLine("Read from keyvault");

            // Setup in Azure:
            // -> Create a Service Principal in Azure AD using Azure CLI
            // az ad sp create-for-rbac -n {keyvaultname} --skip-assignemtn
            // The above generates a result that should be set an environment variables
            // appId = AZURE_CLIENT_ID
            // password = AZURE_CLIENT_SECRET
            // tenant = AZURE_TENANT_ID

            // Set access policy on KeyVault
            // az keyvault set-policy --name {keyvaultname} --spn "{appId from above}" --secret-permissions get list delete (etc, etc)
            var keyVaultUrl = "https://trainingvaultdrb.vault.azure.net/";

            // DefaultAzureCredentials will get the settings from above from the environment variables
            var secretClient = new SecretClient(vaultUri: new Uri(keyVaultUrl), credential: new DefaultAzureCredential());

            // Get a Secret
            KeyVaultSecret secret = secretClient.GetSecret("apppwd");

            Console.WriteLine($"{secret.Name}, {secret.Value}");

            // Get a Key
            var keyClient = new KeyClient(vaultUri: new Uri(keyVaultUrl), credential: new DefaultAzureCredential());

            KeyVaultKey key = keyClient.GetKey("drbenckey");

            // Encrypts using the key - these are Azure libraries
            var cyptoClient = new CryptographyClient(key.Id, credential: new DefaultAzureCredential());

            byte[]        plaintext = Encoding.UTF8.GetBytes("text to encrypt");
            EncryptResult result    = cyptoClient.Encrypt(EncryptionAlgorithm.RsaOaep256, plaintext);

            Console.WriteLine(Encoding.UTF8.GetString(result.Ciphertext));
        }
 public KeyVaultKey Get(string name)
 {
     return(_client.GetKey(name));
 }
        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
            }
        }
Пример #25
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);
        }
Пример #26
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);
        }
Пример #27
0
 private PSKeyVaultKey GetKey(KeyClient client, string keyName, string keyVersion)
 {
     return(new PSKeyVaultKey(client.GetKey(keyName, keyVersion).Value, _vaultUriHelper));
 }
Пример #28
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();

            var keyClient = new KeyClient(
                new Uri(""), // e.g. https://scottbrady91-test.vault.azure.net/
                new ClientSecretCredential(
                    tenantId: "",
                    clientId: "",
                    clientSecret: ""));

            Response <KeyVaultKey> response = keyClient.GetKey(""); // e.g. IdentityServerSigningKeyEcc

            AsymmetricSecurityKey key;
            string algorithm;

            if (response.Value.KeyType == KeyType.Ec)
            {
                ECDsa ecDsa = response.Value.Key.ToECDsa();
                key = new ECDsaSecurityKey(ecDsa)
                {
                    KeyId = response.Value.Properties.Version
                };

                // parse from curve
                if (response.Value.Key.CurveName == KeyCurveName.P256)
                {
                    algorithm = "ES256";
                }
                else if (response.Value.Key.CurveName == KeyCurveName.P384)
                {
                    algorithm = "ES384";
                }
                else if (response.Value.Key.CurveName == KeyCurveName.P521)
                {
                    algorithm = "ES521";
                }
                else
                {
                    throw new NotSupportedException();
                }
            }
            else if (response.Value.KeyType == KeyType.Rsa)
            {
                RSA rsa = response.Value.Key.ToRSA();
                key = new RsaSecurityKey(rsa)
                {
                    KeyId = response.Value.Properties.Version
                };

                // you define
                algorithm = "PS256";
            }
            else
            {
                throw new NotSupportedException();
            }

            services.AddIdentityServer()
            .AddTestUsers(TestUsers.Users)
            .AddInMemoryIdentityResources(Config.Ids)
            .AddInMemoryApiResources(Config.Apis)
            .AddInMemoryClients(Config.Clients)
            .AddSigningCredential(key, algorithm);

            services.AddTransient <ITokenCreationService, KeyVaultTokenCreationService>();
        }