Example #1
0
        public unsafe void AddOrUpdate(string key, ICredential credential)
        {
            GHashTable * attributes  = null;
            SecretValue *secretValue = null;
            GError *     error       = null;

            try
            {
                SecretService *service = GetSecretService();

                // Create attributes for the key and user
                attributes = g_hash_table_new_full(g_str_hash, g_str_equal,
                                                   Marshal.FreeHGlobal, Marshal.FreeHGlobal);

                IntPtr keyKeyPtr   = Marshal.StringToHGlobalAnsi(KeyAttributeName);
                IntPtr keyValuePtr = Marshal.StringToHGlobalAnsi(key);
                g_hash_table_insert(attributes, keyKeyPtr, keyValuePtr);

                IntPtr userKeyPtr   = Marshal.StringToHGlobalAnsi(UserAttributeName);
                IntPtr userValuePtr = Marshal.StringToHGlobalAnsi(credential.UserName);
                g_hash_table_insert(attributes, userKeyPtr, userValuePtr);

                // Create the secret value from the password
                byte[] passwordBytes = Encoding.UTF8.GetBytes(credential.Password);
                secretValue = secret_value_new(passwordBytes, passwordBytes.Length, PlainTextContentType);

                SecretSchema schema = GetSchema();

                // Store the secret with the associated attributes
                bool result = secret_service_store_sync(
                    service,
                    ref schema,
                    attributes,
                    null,
                    key, // Use the key also as the label
                    secretValue,
                    IntPtr.Zero,
                    out error);

                if (error != null)
                {
                    int    code    = error->code;
                    string message = Marshal.PtrToStringAuto(error->message) !;
                    throw new InteropException("Failed to store credentials", code, new Exception(message));
                }

                if (!result)
                {
                    throw new InteropException("Failed to store credentials", -1);
                }
            }
            finally
            {
                if (attributes != null)
                {
                    g_hash_table_destroy(attributes);
                }
                if (secretValue != null)
                {
                    secret_value_unref(secretValue);
                }
                if (error != null)
                {
                    g_error_free(error);
                }
            }
        }