Example #1
0
        public void KeyVaultCreateHsmKeyTest()
        {
            using (var undoContext = UndoContext.Current)
            {
                undoContext.Start();
                var client = GetKeyVaultClient();

                var attributes = new KeyAttributes();
                var createdKey = client.CreateKeyAsync(_vaultAddress, "CreateHsmKeyTest", JsonWebKeyType.RsaHsm, 2048,
                                                       JsonWebKeyOperation.AllOperations, attributes).GetAwaiter().GetResult();

                try
                {
                    Trace.WriteLine("Verify generated key is as expected");
                    VerifyKeyAttributesAreEqual(attributes, createdKey.Attributes);
                    Assert.Equal(JsonWebKeyType.RsaHsm, createdKey.Key.Kty);

                    Trace.WriteLine("Get the key");
                    var retrievedKey = client.GetKeyAsync(createdKey.Key.Kid).GetAwaiter().GetResult();
                    VerifyKeyAttributesAreEqual(attributes, retrievedKey.Attributes);
                    VerifyWebKeysAreEqual(createdKey.Key, retrievedKey.Key);
                }
                finally
                {
                    Trace.WriteLine("Delete the key");
                    var deletedKey = client.DeleteKeyAsync(_vaultAddress, "CreateHsmKeyTest").GetAwaiter().GetResult();

                    VerifyKeyAttributesAreEqual(deletedKey.Attributes, createdKey.Attributes);
                    VerifyWebKeysAreEqual(deletedKey.Key, createdKey.Key);
                }
            }
        }
        /// <summary>
        /// Adds or update the dictionary values with a specific key to the KeyVault
        /// </summary>
        /// <param name="key">The unique key</param>
        /// <param name="values">The dictionary values to be added</param>
        /// <returns></returns>
        /// <remarks>If an exception is generated the method returns it without any wrap</remarks>
        public async Task AddOrUpdateAsync(string key, IDictionary <String, String> values)
        {
            var tags = new Dictionary <String, String>();

            foreach (var item in values)
            {
                if (!String.IsNullOrEmpty(item.Value) && item.Value.Length > 256)
                {
                    // If the item is longer than 256 split in chunks of 256
                    for (var chunk = 0; chunk <= item.Value.Length / 256; chunk++)
                    {
                        tags.Add($"{item.Key}_{chunk}", item.Value.Substring(chunk * 256,
                                                                             (item.Value.Length - chunk * 256) > 256 ? 256 : item.Value.Length - chunk * 256));
                    }
                }
                else if (!String.IsNullOrEmpty(item.Value))
                {
                    // If the item is shorter than 256 add it directly
                    tags.Add(item.Key, item.Value);
                }
            }

            var attributes = new KeyAttributes(recoveryLevel: "Purgeable");

            attributes.Expires = DateTime.UtcNow.AddHours(12);

            var retry = new RetryWithExponentialBackoff();
            await retry.RunAsync(async() =>
            {
                var createdKey = await keyVaultClient.CreateKeyAsync(vaultAddress, key, JsonWebKeyType.Rsa, keyAttributes: attributes, tags: tags);
            });
        }
Example #3
0
        public void KeyVaultCreateGetDeleteKeyTest()
        {
            using (var undoContext = UndoContext.Current)
            {
                undoContext.Start();
                var client = GetKeyVaultClient();

                var attributes = new KeyAttributes();
                var tags       = new Dictionary <string, string>()
                {
                    { "purpose", "unit test" }, { "test name ", "CreateGetDeleteKeyTest" }
                };
                var createdKey = client.CreateKeyAsync(_vaultAddress, "CreateSoftKeyTest", JsonWebKeyType.Rsa, 2048,
                                                       JsonWebKeyOperation.AllOperations, attributes, tags).GetAwaiter().GetResult();

                try
                {
                    VerifyKeyAttributesAreEqual(attributes, createdKey.Attributes);
                    Assert.Equal(JsonWebKeyType.Rsa, createdKey.Key.Kty);
                    Assert.Equal("CreateSoftKeyTest", createdKey.KeyIdentifier.Name);
                    var retrievedKey = client.GetKeyAsync(createdKey.Key.Kid).GetAwaiter().GetResult();
                    VerifyKeyAttributesAreEqual(attributes, retrievedKey.Attributes);
                    VerifyWebKeysAreEqual(createdKey.Key, retrievedKey.Key);
                    VerifyTagsAreEqual(tags, retrievedKey.Tags);
                }
                finally
                {
                    var deletedKey = client.DeleteKeyAsync(_vaultAddress, "CreateSoftKeyTest").GetAwaiter().GetResult();

                    VerifyKeyAttributesAreEqual(deletedKey.Attributes, createdKey.Attributes);
                    VerifyWebKeysAreEqual(deletedKey.Key, createdKey.Key);
                }
            }
        }
Example #4
0
        public void SetFixture(KeyVaultTestFixture data)
        {
            data.Initialize(TestUtilities.GetCallingClass());
            if (HttpMockServer.Mode == HttpRecorderMode.Record)
            {
                // SECURITY: DO NOT USE IN PRODUCTION CODE; FOR TEST PURPOSES ONLY
                ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;

                this._credential   = data._ClientCredential;
                this._tokenCache   = new TokenCache();
                this._vaultAddress = data.vaultAddress;

                //Create one key to use for testing. Key creation is expensive.
                var myClient   = CreateKeyVaultClient();
                var keyName    = "sdktestkey";
                var attributes = new KeyAttributes();
                var createdKey = myClient.CreateKeyAsync(_vaultAddress, keyName, JsonWebKeyType.Rsa, 2048,
                                                         JsonWebKeyOperation.AllOperations, attributes).GetAwaiter().GetResult();
                var keyIdentifier = new KeyIdentifier(createdKey.Key.Kid);

                _keyName    = keyIdentifier.Name;
                _keyVersion = keyIdentifier.Version;

                _keyIdentifier = new KeyIdentifier(_vaultAddress, _keyName, _keyVersion);
            }
        }
        public KeyBundle CreateKey(string vaultName, string keyName, KeyAttributes keyAttributes)
        {
            if (string.IsNullOrEmpty(vaultName))
                throw new ArgumentNullException("vaultName");
            if (string.IsNullOrEmpty(keyName))
                throw new ArgumentNullException("keyName");
            if (keyAttributes == null)
                throw new ArgumentNullException("keyAttributes");

            string vaultAddress = this.vaultUriHelper.CreateVaultAddress(vaultName);
            var attributes = (Azure.KeyVault.Models.KeyAttributes)keyAttributes;

            Azure.KeyVault.Models.KeyBundle keyBundle;
            try
            {
                keyBundle = this.keyVaultClient.CreateKeyAsync(
                    vaultAddress,
                    keyName,
                    keyAttributes.KeyType,
                    keyOps: keyAttributes.KeyOps == null ? null : new List<string> (keyAttributes.KeyOps),
                    keyAttributes: attributes,
                    tags: keyAttributes.TagsDirectionary).GetAwaiter().GetResult();
            }
            catch (Exception ex)
            {
                throw GetInnerException(ex);
            }

            return new KeyBundle(keyBundle, this.vaultUriHelper);
        }        
Example #6
0
        /// <summary>
        /// Generate vault key
        /// </summary>
        /// <param name="vault"></param>
        /// <param name="keyName"></param>
        /// <returns></returns>
        public KeyIdentifier GenerateVaultKey(Vault vault, string keyName)
        {
            string vaultUri   = vault.Properties.VaultUri;
            var    attributes = new KeyAttributes();
            var    createdKey = keyVaultClient.CreateKeyAsync(vaultUri, keyName, JsonWebKeyType.Rsa,
                                                              keyOps: JsonWebKeyOperation.AllOperations).GetAwaiter().GetResult();

            return(new KeyIdentifier(createdKey.Key.Kid));
        }
Example #7
0
 internal KeyData(ResourceIdentifier id, string name, ResourceType type, SystemData systemData, string location, IReadOnlyDictionary <string, string> tags, KeyAttributes attributes, JsonWebKeyType?kty, IList <JsonWebKeyOperation> keyOps, int?keySize, JsonWebKeyCurveName?curveName, string keyUri, string keyUriWithVersion) : base(id, name, type, systemData, location, tags)
 {
     Attributes        = attributes;
     Kty               = kty;
     KeyOps            = keyOps;
     KeySize           = keySize;
     CurveName         = curveName;
     KeyUri            = keyUri;
     KeyUriWithVersion = keyUriWithVersion;
 }
Example #8
0
        public override void ExecuteCmdlet()
        {
            KeyAttributes attributes = new KeyAttributes
            {
                Enabled   = this.Enable,
                Expires   = this.Expires,
                NotBefore = this.NotBefore,
                KeyOps    = this.KeyOps
            };

            WriteObject(DataServiceClient.SetKey(VaultName, Name, attributes));
        }
Example #9
0
        public void KeyVaultUpdateKeyAttributesTest()
        {
            using (var undoContext = UndoContext.Current)
            {
                undoContext.Start();
                var client  = GetKeyVaultClient();
                var keyName = "UpdateKeyAttributesTest";
                try
                {
                    // Create a key
                    var attributes = new KeyAttributes();
                    var operations = new string[] { JsonWebKeyOperation.Decrypt, JsonWebKeyOperation.Encrypt };
                    var createdKey =
                        client.CreateKeyAsync(_vaultAddress, keyName, JsonWebKeyType.Rsa, 2048,
                                              JsonWebKeyOperation.AllOperations).GetAwaiter().GetResult();

                    // Update the current version
                    attributes.Enabled   = true;
                    attributes.NotBefore = new DateTime(1980, 1, 1).ToUniversalTime();
                    attributes.Expires   = new DateTime(1981, 1, 1).ToUniversalTime();

                    var updatedKey =
                        client.UpdateKeyAsync(_vaultAddress, keyName, operations, attributes)
                        .GetAwaiter()
                        .GetResult();

                    VerifyKeyAttributesAreEqual(updatedKey.Attributes, attributes);
                    VerifyKeyOperationsAreEqual(updatedKey.Key.KeyOps, operations);
                    VerifyWebKeysAreEqual(updatedKey.Key, createdKey.Key);

                    // Create a new version of the key
                    var newkeyVersion = client.CreateKeyAsync(_vaultAddress, keyName, JsonWebKeyType.Rsa, 2048,
                                                              JsonWebKeyOperation.AllOperations).GetAwaiter().GetResult();

                    // Update the original version
                    attributes.Enabled   = false;
                    attributes.NotBefore = new DateTime(1990, 1, 1).ToUniversalTime();
                    attributes.Expires   = new DateTime(1991, 1, 1).ToUniversalTime();

                    updatedKey =
                        client.UpdateKeyAsync(createdKey.Key.Kid, operations, attributes).GetAwaiter().GetResult();

                    VerifyKeyAttributesAreEqual(updatedKey.Attributes, attributes);
                    VerifyKeyOperationsAreEqual(updatedKey.Key.KeyOps, operations);
                    VerifyWebKeysAreEqual(updatedKey.Key, createdKey.Key);
                }
                finally
                {
                    client.DeleteKeyAsync(_vaultAddress, keyName).Wait();
                }
            }
        }
Example #10
0
        private string GetKeyVaultSecretJsonForPrivateKey(X509Certificate2 certificate)
        {
            try
            {
                using (RSA rsa = (RSA)certificate.PrivateKey)
                {
                    var parameters = rsa.ExportParameters(true);

                    KeyBundle bundle = new KeyBundle
                    {
                        Key = new JsonWebKey
                        {
                            Kty = JsonWebKeyType.Rsa,
                            // Private stuff
                            D  = parameters.D,
                            DP = parameters.DP,
                            DQ = parameters.DQ,
                            P  = parameters.P,
                            Q  = parameters.Q,
                            QI = parameters.InverseQ,
                            // Public stuff
                            N = parameters.Modulus,
                            E = parameters.Exponent,
                        },
                    };

                    KeyAttributes attributes = new KeyAttributes
                    {
                        Enabled = true,
                        Expires = DateTime.Parse(certificate.GetExpirationDateString())
                    };

                    Dictionary <string, object> body = new Dictionary <string, object>();
                    body.Add("attributes", attributes);
                    body.Add("key", bundle.Key);

                    JObject obj = JObject.FromObject(body);
                    return(obj.ToString());
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Private certificate set as non-exportable : " + ex.Message);
            }
        }
        public RemoveKeyVaultKeyTests()
        {
            base.SetupTest();

            cmdlet = new RemoveAzureKeyVaultKey()
            {
                CommandRuntime    = commandRuntimeMock.Object,
                DataServiceClient = keyVaultClientMock.Object,
                VaultName         = VaultName
            };

            keyAttributes = new KeyAttributes(true, DateTime.Now, DateTime.Now, "HSM", new string[] { "All" }, null);
            webKey        = new WebKey.JsonWebKey();
            keyBundle     = new KeyBundle()
            {
                Attributes = keyAttributes, Key = webKey, Name = KeyName, VaultName = VaultName
            };
        }
Example #12
0
        public KeyVaultTestFixture()
        {
            Initialize(string.Empty);

            if (vaultAddress != null && HttpMockServer.Mode == HttpRecorderMode.Record)
            {
                //Create one key to use for testing. Key creation is expensive.
                var myClient = new KeyVaultClient(new TestKeyVaultCredential(GetAccessToken), GetHandlers());
                keyName = "sdktestkey";
                var attributes = new KeyAttributes();
                var createdKey = myClient.CreateKeyAsync(vaultAddress, keyName, JsonWebKeyType.Rsa, 2048,
                                                         JsonWebKeyOperation.AllOperations, attributes).GetAwaiter().GetResult();
                keyIdentifier = new KeyIdentifier(createdKey.Key.Kid);
                keyName       = keyIdentifier.Name;
                keyVersion    = keyIdentifier.Version;
                tokenCache    = new TokenCache();
            }
        }
Example #13
0
        public override void ExecuteCmdlet()
        {
            try
            {
                KeyAttributes attributes = new KeyAttributes
                {
                    Enabled   = this.Enable,
                    Expires   = this.Expires,
                    NotBefore = this.NotBefore,
                    KeyOps    = this.KeyOps
                };

                WriteObject(DataServiceClient.SetKey(VaultName, Name, attributes));
            }
            catch (Exception ex)
            {
                this.WriteErrorDetails(ex);
            }
        }
Example #14
0
        public void KeyVaultUpdateKeyAttributesWithNoChangeTest()
        {
            using (var undoContext = UndoContext.Current)
            {
                undoContext.Start();
                var client = GetKeyVaultClient();

                var keyName = "UpdateKeyAttributesWithNoChangeTest";
                try
                {
                    var enabledState = false;
                    var attributes   = new KeyAttributes()
                    {
                        Enabled   = enabledState,
                        Expires   = new DateTime(2030, 1, 1).ToUniversalTime(),
                        NotBefore = new DateTime(2010, 1, 1).ToUniversalTime()
                    };
                    var createdKey =
                        client.CreateKeyAsync(_vaultAddress, keyName, JsonWebKeyType.Rsa, 2048,
                                              JsonWebKeyOperation.AllOperations, attributes).GetAwaiter().GetResult();

                    var attributes2 = new KeyAttributes()
                    {
                        Enabled   = null, //when attributes are null there should not be any change
                        NotBefore = null,
                        Expires   = null
                    };

                    // You cannot update a specific version of a key, only the current version
                    var updatedKey =
                        client.UpdateKeyAsync(_vaultAddress, keyName, null, attributes).GetAwaiter().GetResult();

                    VerifyKeyAttributesAreEqual(updatedKey.Attributes, createdKey.Attributes);
                    VerifyKeyOperationsAreEqual(updatedKey.Key.KeyOps, createdKey.Key.KeyOps);
                    VerifyWebKeysAreEqual(updatedKey.Key, createdKey.Key);
                }
                finally
                {
                    client.DeleteKeyAsync(_vaultAddress, keyName).Wait();
                }
            }
        }
Example #15
0
        internal KeyBundle(Microsoft.Azure.KeyVault.KeyBundle keyBundle, VaultUriHelper vaultUriHelper)
        {
            if (keyBundle == null)
                throw new ArgumentNullException("keyBundle");
            if (keyBundle.Key == null || keyBundle.Attributes == null)
                throw new ArgumentException(KeyVaultProperties.Resources.InvalidKeyBundle);
           
            SetObjectIdentifier(vaultUriHelper,keyBundle.KeyIdentifier);

            Key = keyBundle.Key;
            Attributes = new KeyAttributes(
                keyBundle.Attributes.Enabled,
                keyBundle.Attributes.Expires, 
                keyBundle.Attributes.NotBefore, 
                keyBundle.Key.Kty, 
                keyBundle.Key.KeyOps,
                keyBundle.Attributes.Created,
                keyBundle.Attributes.Updated,
                keyBundle.Tags);            
        }        
Example #16
0
        public void KeyVaultBackupRestoreTest()
        {
            using (var undoContext = UndoContext.Current)
            {
                undoContext.Start();
                var client = GetKeyVaultClient();

                var keyName = "BackupRestoreTest";

                var attribute = new KeyAttributes()
                {
                    Enabled   = false,
                    Expires   = new DateTime(2030, 1, 1).ToUniversalTime(),
                    NotBefore = new DateTime(2010, 1, 1).ToUniversalTime()
                };

                var createdKey = client.CreateKeyAsync(_vaultAddress, keyName, JsonWebKeyType.Rsa, 2048,
                                                       JsonWebKeyOperation.AllOperations, attribute).GetAwaiter().GetResult();

                try
                {
                    // Restore a deleted key
                    var backupResponse = client.BackupKeyAsync(_vaultAddress, keyName).GetAwaiter().GetResult();

                    client.DeleteKeyAsync(_vaultAddress, keyName).Wait();

                    var restoredDeletedKey =
                        client.RestoreKeyAsync(_vaultAddress, backupResponse).GetAwaiter().GetResult();

                    VerifyKeyAttributesAreEqual(restoredDeletedKey.Attributes, createdKey.Attributes);
                    Assert.Equal(restoredDeletedKey.Key.Kty, createdKey.Key.Kty);
                    Assert.Equal(createdKey.Key.Kid, restoredDeletedKey.Key.Kid);
                }
                finally
                {
                    client.DeleteKeyAsync(_vaultAddress, keyName).Wait();
                }
            }
        }
        public SetKeyVaultKeyTests()
        {
            base.SetupTest();

            keyAttributes = new KeyAttributes(true, DateTime.Now, DateTime.Now, null, null);
            webKey        = new WebKey.JsonWebKey();
            keyBundle     = new KeyBundle()
            {
                Attributes = keyAttributes, Key = webKey, Name = KeyName, VaultName = VaultName, Version = KeyVersion
            };

            cmdlet = new SetAzureKeyVaultKey()
            {
                CommandRuntime    = commandRuntimeMock.Object,
                DataServiceClient = keyVaultClientMock.Object,
                VaultName         = VaultName,
                Enable            = (bool)keyAttributes.Enabled,
                Expires           = keyAttributes.Expires,
                NotBefore         = keyAttributes.NotBefore,
                Name = KeyName
            };
        }
        internal KeyBundle(Client.KeyBundle clientKeyBundle, VaultUriHelper vaultUriHelper)
        {
            if (clientKeyBundle == null)
            {
                throw new ArgumentNullException("clientKeyBundle");
            }            
            if (clientKeyBundle.Key == null || clientKeyBundle.Attributes == null)
            {
                throw new ArgumentException(Resources.InvalidKeyBundle);
            }

            SetObjectIdentifier(vaultUriHelper, new Client.KeyIdentifier(clientKeyBundle.Key.Kid));

            Key = clientKeyBundle.Key;
            Attributes = new KeyAttributes(
                clientKeyBundle.Attributes.Enabled,
                clientKeyBundle.Attributes.Expires, 
                clientKeyBundle.Attributes.NotBefore, 
                clientKeyBundle.Key.Kty, 
                clientKeyBundle.Key.KeyOps);

            Id = clientKeyBundle.Key.Kid;
        }
        internal KeyIdentityItem(Client.KeyItem clientKeyItem, VaultUriHelper vaultUriHelper)
        {
            if (clientKeyItem == null)
            {
                throw new ArgumentNullException("clientKeyItem");
            }
            if (String.IsNullOrEmpty(clientKeyItem.Kid) || clientKeyItem.Attributes == null)
            {
                throw new ArgumentException(Resources.InvalidKeyBundle);
            }

            SetObjectIdentifier(vaultUriHelper, new Client.KeyIdentifier(clientKeyItem.Kid));

            var attribute = new KeyAttributes(
                clientKeyItem.Attributes.Enabled,
                clientKeyItem.Attributes.Expires,
                clientKeyItem.Attributes.NotBefore);

            Enabled = attribute.Enabled;
            Expires = attribute.Expires;
            NotBefore = attribute.NotBefore;
            Id = clientKeyItem.Kid;
        }
        public KeyVaultTestFixture()
        {
            Initialize(string.Empty);

            if (vaultAddress != null && HttpMockServer.Mode == HttpRecorderMode.Record)
            {
                //Create one key to use for testing. Key creation is expensive.
                var myClient = new KeyVaultClient(new TestKeyVaultCredential(GetAccessToken), GetHandlers());
                keyName = "sdktestkey";
                var attributes = new KeyAttributes();
                var createdKey = myClient.CreateKeyAsync(vaultAddress, keyName, JsonWebKeyType.Rsa, 2048,
                                                         JsonWebKeyOperation.AllOperations, attributes).GetAwaiter().GetResult();
                keyIdentifier = new KeyIdentifier(createdKey.Key.Kid);
                keyName       = keyIdentifier.Name;
                keyVersion    = keyIdentifier.Version;
                tokenCache    = new TokenCache();
                _deviceCodeForStorageTests = null;
                retryExecutor = new RetryPolicy <SoftDeleteErrorDetectionStrategy>(new ExponentialBackoffRetryStrategy(8, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(60), TimeSpan.FromSeconds(5)));
            }
            else
            {
                retryExecutor = new RetryPolicy <SoftDeleteErrorDetectionStrategy>(new FixedIntervalRetryStrategy(5, TimeSpan.FromSeconds(5.0)));
            }
        }
        public void PerformTrustedGUIAuthorization(int key_handle, ref byte[] authorization, ref bool tga)
        {
            KeyProtectionInfo kpi = getKeyProtectionInfo(key_handle);

            if ((kpi.ProtectionStatus & KeyProtectionInfo.PROTSTAT_PIN_PROTECTED) != 0)
            {
                if (kpi.InputMethod == InputMethod.TRUSTED_GUI)
                {
                    if (authorization != null)
                    {
                        throw new System.ArgumentException("Redundant \"Authorization\"");
                    }
                }
                else if (kpi.InputMethod == InputMethod.PROGRAMMATIC || authorization != null)
                {
                    tga = false;
                    return;
                }
                if ((kpi.ProtectionStatus & KeyProtectionInfo.PROTSTAT_PIN_BLOCKED) != 0)
                {
                    MessageBox.Show("Key #" + key_handle + " is blocked due to previous PIN errors",
                                    "Authorization Error",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Exclamation);
                    throw new SKSException("Key locked, user message", SKSException.ERROR_USER_ABORT);
                }
                KeyAttributes ka = getKeyAttributes(key_handle);
                if (kpi.EnablePinCaching)
                {
                    if (tga)
                    {
                        // Failed to authenticate - Clear cache
                        pin_cache.Remove(key_handle);
                    }
                    else if (pin_cache.ContainsKey(key_handle))
                    {
                        // First try and we do have a cache - Use it
                        tga           = true;
                        authorization = GetEncryptedAuthorization(pin_cache[key_handle]);
                        return;
                    }
                }
                SKSAuthorizationDialog authorization_form = new SKSAuthorizationDialog(key_handle,
                                                                                       (PassphraseFormat)kpi.Format,
                                                                                       (Grouping)kpi.Grouping,
                                                                                       (AppUsage)ka.AppUsage,
                                                                                       kpi.PinErrorCount == 0 ? 0 : kpi.RetryLimit - kpi.PinErrorCount);
                if (authorization_form.ShowDialog() == DialogResult.OK)
                {
                    authorization =
                        ((PassphraseFormat)kpi.Format == PassphraseFormat.BINARY) ?
                        Hex.Decode(authorization_form.password)
                                                                                     :
                        System.Text.Encoding.UTF8.GetBytes(authorization_form.password);
                    if (kpi.EnablePinCaching)
                    {
                        // Although the authorization may be incorrect we will just be
                        // prompted again so we can save it in the cache anyway
                        pin_cache[key_handle] = authorization;
                    }
                    authorization = GetEncryptedAuthorization(authorization);
                    tga           = true;
                }
                else
                {
                    throw new SKSException("Canceled by user", SKSException.ERROR_USER_ABORT);
                }
            }
            else
            {
                tga = false;
            }
        }
        internal static KeyData DeserializeKeyData(JsonElement element)
        {
            Optional <string> location = default;
            Optional <IReadOnlyDictionary <string, string> > tags = default;
            ResourceIdentifier        id                   = default;
            string                    name                 = default;
            ResourceType              type                 = default;
            SystemData                systemData           = default;
            Optional <KeyAttributes>  attributes           = default;
            Optional <JsonWebKeyType> kty                  = default;
            Optional <IList <JsonWebKeyOperation> > keyOps = default;
            Optional <int> keySize = default;
            Optional <JsonWebKeyCurveName> curveName = default;
            Optional <Uri>    keyUri            = default;
            Optional <string> keyUriWithVersion = default;

            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("location"))
                {
                    location = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("tags"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    Dictionary <string, string> dictionary = new Dictionary <string, string>();
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        dictionary.Add(property0.Name, property0.Value.GetString());
                    }
                    tags = dictionary;
                    continue;
                }
                if (property.NameEquals("id"))
                {
                    id = new ResourceIdentifier(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("name"))
                {
                    name = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("type"))
                {
                    type = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("systemData"))
                {
                    systemData = JsonSerializer.Deserialize <SystemData>(property.Value.ToString());
                    continue;
                }
                if (property.NameEquals("properties"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        if (property0.NameEquals("attributes"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            attributes = KeyAttributes.DeserializeKeyAttributes(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("kty"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            kty = new JsonWebKeyType(property0.Value.GetString());
                            continue;
                        }
                        if (property0.NameEquals("keyOps"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            List <JsonWebKeyOperation> array = new List <JsonWebKeyOperation>();
                            foreach (var item in property0.Value.EnumerateArray())
                            {
                                array.Add(new JsonWebKeyOperation(item.GetString()));
                            }
                            keyOps = array;
                            continue;
                        }
                        if (property0.NameEquals("keySize"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            keySize = property0.Value.GetInt32();
                            continue;
                        }
                        if (property0.NameEquals("curveName"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            curveName = new JsonWebKeyCurveName(property0.Value.GetString());
                            continue;
                        }
                        if (property0.NameEquals("keyUri"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                keyUri = null;
                                continue;
                            }
                            keyUri = new Uri(property0.Value.GetString());
                            continue;
                        }
                        if (property0.NameEquals("keyUriWithVersion"))
                        {
                            keyUriWithVersion = property0.Value.GetString();
                            continue;
                        }
                    }
                    continue;
                }
            }
            return(new KeyData(id, name, type, systemData, location.Value, Optional.ToDictionary(tags), attributes.Value, Optional.ToNullable(kty), Optional.ToList(keyOps), Optional.ToNullable(keySize), Optional.ToNullable(curveName), keyUri.Value, keyUriWithVersion.Value));
        }
Example #23
0
 public Task <KeyBundle> UpdateKeyAsync(string keyName, string[] keyOps = null, KeyAttributes attributes = null, Dictionary <string, string> tags = null, CancellationToken cancellationToken = default(CancellationToken))
 {
     return(this.keyVaultClient.UpdateKeyAsync(
                this.vaultUri,
                keyName,
                keyOps,
                attributes,
                tags,
                cancellationToken));
 }
Example #24
0
 public async Task <KeyBundle> UpdateKey(string keyName, KeyAttributes keyAttributes)
 {
     return(await keyVaultClient.UpdateKeyAsync(keyVaultUri, keyName, attributes : keyAttributes));
 }
        public async Task <KeyVaultKey> CreateKey(string keyName, KeyAccessPolicy operations, KeyAttributes attributes = null)
        {
            var key = await Client.CreateKeyAsync(Vault.Properties.VaultUri, keyName, JsonWebKeyType.Rsa, key_ops : operations.AccessPermissionString, keyAttributes : attributes);

            return(new KeyVaultKey(Client, key, true));
        }
        public KeyBundle ImportKey(string vaultName, string keyName, KeyAttributes keyAttributes, JsonWebKey webKey, bool? importToHsm)
        {
            if (string.IsNullOrEmpty(vaultName))
                throw new ArgumentNullException("vaultName");
            if (string.IsNullOrEmpty(keyName))
                throw new ArgumentNullException("keyName");
            if (keyAttributes == null)
                throw new ArgumentNullException("keyAttributes");
            if (webKey == null)
                throw new ArgumentNullException("webKey");
            if (webKey.Kty == JsonWebKeyType.RsaHsm && (importToHsm.HasValue && !importToHsm.Value))
                throw new ArgumentException(KeyVaultProperties.Resources.ImportByokAsSoftkeyError);

            string vaultAddress = this.vaultUriHelper.CreateVaultAddress(vaultName);
            
            webKey.KeyOps = keyAttributes.KeyOps;            
            var keyBundle = new Azure.KeyVault.Models.KeyBundle()
            {
                Attributes = (Azure.KeyVault.Models.KeyAttributes)keyAttributes,
                Key = webKey,
                Tags = keyAttributes.TagsDirectionary
            };

            try
            {
                keyBundle = this.keyVaultClient.ImportKeyAsync(vaultAddress, keyName, keyBundle, importToHsm).GetAwaiter().GetResult();
            }
            catch (Exception ex)
            {
                throw GetInnerException(ex);
            }

            return new KeyBundle(keyBundle, this.vaultUriHelper);
        }
        public KeyBundle UpdateKey(string vaultName, string keyName, string keyVersion, KeyAttributes keyAttributes)
        {
            if (string.IsNullOrEmpty(vaultName))
                throw new ArgumentNullException("vaultName");
            if (string.IsNullOrEmpty(keyName))
                throw new ArgumentNullException("keyName");
            if (keyAttributes == null)
                throw new ArgumentNullException("keyAttributes");
            
            var attributes = (Azure.KeyVault.Models.KeyAttributes)keyAttributes;
            var keyIdentifier = new KeyIdentifier(this.vaultUriHelper.CreateVaultAddress(vaultName), keyName, keyVersion);

            Azure.KeyVault.Models.KeyBundle keyBundle;
            try
            {
                keyBundle = this.keyVaultClient.UpdateKeyAsync(
                    keyIdentifier.Identifier, keyAttributes.KeyOps, attributes: attributes, tags: keyAttributes.TagsDirectionary).GetAwaiter().GetResult();
            }
            catch (Exception ex)
            {
                throw GetInnerException(ex);
            }

            return new KeyBundle(keyBundle, this.vaultUriHelper);
        }
 public EntityReference(string logicalName, string keyAttributeName, object value) : this(logicalName)
 {
     KeyAttributes.Add(keyAttributeName, value);
 }
Example #29
0
 private void VerifyKeyAttributesAreEqual(KeyAttributes keyAttribute1, KeyAttributes keyAttribute2)
 {
     Assert.Equal <DateTime?>(keyAttribute1.Expires, keyAttribute2.Expires);
     Assert.Equal <DateTime?>(keyAttribute1.NotBefore, keyAttribute2.NotBefore);
     Assert.Equal <bool?>(keyAttribute1.Enabled ?? true, keyAttribute2.Enabled ?? true);
 }
Example #30
0
 /// <summary>
 /// Initializes a new instance of the Entity class.
 /// </summary>
 /// <param name="logicalName">Entity LogicalName</param>
 /// <param name="keyName">Alternate Key name</param>
 /// <param name="keyValue">Alternate Key value</param>
 public Entity(string logicalName, string keyName, object keyValue) : this()
 {
     LogicalName = logicalName;
     KeyAttributes.Add(keyName, keyValue);
 }