示例#1
0
        static void EncryptOrDecrypt(string str, bool encrypt, bool verbose)
        {
            SimpleEncryptDecrypt sed = new SimpleEncryptDecrypt();

            ConsoleLogger   logger = null;
            Action <string> output = null;

            if (verbose)
            {
                logger = new ConsoleLogger(typeof(Program), LogManager.LogLevel.Debug);
                output = (x) => logger.Debug(x);
            }

            string s = null;

            if (encrypt)
            {
                s = sed.Encrypt(str, output);
            }
            else
            {
                s = sed.Decrypt(str, output);
            }

            Console.WriteLine(str + " -> " + s);
        }
示例#2
0
        public void Decrypt()
        {
            IEncryptDecrypt encrypter = new SimpleEncryptDecrypt();

            // keys to make test reproduceable
            byte[] key  = GetConstantKey(32);
            byte[] iv   = GetConstantKey(16);
            var    data = new Tuple <byte[], byte[]>(key, iv);

            mocks.HttpContext.Object.Session.Add(SimpleEncryptDecrypt.EncryptFieldData, data);

            var randomName   = Guid.NewGuid().ToString();
            var randomValue  = Guid.NewGuid().ToString();
            var encryptValue = encrypter.Encrypt(mocks.HttpContext.Object.Session, randomName, randomValue);

            var collection = new NameValueCollection {
                { encryptValue.Item1, encryptValue.Item2 }
            };

            Assert.IsFalse(collection.AllKeys.Contains(randomName));
            Assert.IsTrue(collection.AllKeys.Contains(encryptValue.Item1));
            Assert.AreEqual(encryptValue.Item2, collection[encryptValue.Item1]);

            encrypter.Decrypt(mocks.HttpContext.Object.Session, collection);

            Assert.IsTrue(collection.AllKeys.Contains(randomName));
            Assert.AreEqual(randomValue, collection[randomName]);
            Assert.IsTrue(collection.AllKeys.Contains(encryptValue.Item1));
            Assert.AreEqual(encryptValue.Item2, collection[encryptValue.Item1]);
        }
示例#3
0
        public override string GetValue(SQLiteConnection conn)
        {
            string value             = base.GetValue(conn);
            SimpleEncryptDecrypt sed = new SimpleEncryptDecrypt();

            return(sed.Decrypt(value));
        }
示例#4
0
        public override void SetValue(string value, DateTimeOffset timestamp, SQLiteConnection conn)
        {
            SimpleEncryptDecrypt sed = new SimpleEncryptDecrypt();
            string enc_value         = sed.Encrypt(value);

            Configuration.SetValue(Path, enc_value, false, timestamp, conn);
        }
示例#5
0
        /// <summary>
        /// Used when a new device is being added to the system
        /// </summary>
        /// <param name="di">The device being added</param>
        /// <param name="conn">The DB connection to use</param>
        private static void AddDevice(DeviceInfo di, DateTimeOffset timestamp, SQLiteConnection conn)
        {
            Inserter inserter = new Inserter("Devices", conn);

            if (di.id >= 0)
            {
                inserter.Set("DeviceID", di.id);
            }
            inserter.Set("Name", di.name, true);
            inserter.Set("Type", (int)di.type);
            inserter.Set("IPAddress", di.ipAddress, true);
            inserter.Set("Username", di.username, true);
            SimpleEncryptDecrypt sed = new SimpleEncryptDecrypt();

            inserter.Set("Password", sed.Encrypt(di.password), true);
            inserter.Set("DateActivated", timestamp);
            if (di.groupID < 0)
            {
                inserter.SetNull("GroupID");
            }
            else
            {
                inserter.Set("GroupID", di.groupID);
            }

            inserter.Execute();

            long device_id = conn.LastInsertRowId;

            Database.AddCollectors(di, device_id, timestamp, conn);
        }
示例#6
0
        private static void Obfuscate(SystemConfiguration config)
        {
            SimpleEncryptDecrypt sed = new SimpleEncryptDecrypt();

            // Before we write the configuration data to the database, let's make sure we obfuscate
            // the appropriate things. That would be the database connection strings, and the
            // device's passwords.
            foreach (ConfigurationData cd in config.configuration.Values)
            {
                try
                {
                    if (cd.path.EndsWith("connection_string", StringComparison.InvariantCultureIgnoreCase))
                    {
                        cd.value = sed.Encrypt(cd.value);
                    }
                }
                catch (Exception)
                {
                }
            }
            foreach (DeviceInfo di in config.devices)
            {
                try
                {
                    di.password = sed.Encrypt(di.password);
                }
                catch (Exception)
                {
                }
            }
        }
        public void NotEncryptEmptyStrings()
        {
            SimpleEncryptDecrypt sed = new SimpleEncryptDecrypt();
            string t1        = "";
            string t1_cypher = sed.Encrypt(t1);

            Assert.Equal(t1, t1_cypher);
        }
        public void ProperlyEncryptAndDecryptStringsOfDifferentSizes(string plain)
        {
            SimpleEncryptDecrypt sed = new SimpleEncryptDecrypt();
            string e = sed.Encrypt(plain);

            Assert.NotEqual(plain, e);
            string d = sed.Decrypt(e);

            Assert.Equal(plain, d);
        }
        public void ProperlyEncryptThenDecryptToTheSameString()
        {
            SimpleEncryptDecrypt sed = new SimpleEncryptDecrypt();

            string t1        = "abcd1234";
            string t1_cypher = sed.Encrypt(t1);

            Assert.NotEqual(t1, t1_cypher);
            string t1_plain = sed.Decrypt(t1_cypher);

            Assert.Equal(t1, t1_plain);
        }
        public void ProperlyEncryptThenDecryptGUIDs()
        {
            SimpleEncryptDecrypt sed = new SimpleEncryptDecrypt();

            for (int i = 0; i < 100; ++i)
            {
                string guid   = Guid.NewGuid().ToString();
                string guid_e = sed.Encrypt(guid);
                Assert.NotEqual(guid, guid_e);
                string guid_d = sed.Decrypt(guid_e);
                Assert.Equal(guid, guid_d);
            }
        }
        public void ReturnTheUnencryptedStringWhenDecryptingAnUnencryptedString()
        {
            SimpleEncryptDecrypt sed = new SimpleEncryptDecrypt();

            // Invalid base64 string--it should just return the original
            string unencrypted = "abc1234";
            string d           = sed.Decrypt(unencrypted);

            Assert.Equal(unencrypted, d);

            unencrypted = "ChangeMe";
            d           = sed.Decrypt(unencrypted);
            Assert.Equal(unencrypted, d);
        }
示例#12
0
        private static void HandleConfiguration(Dictionary <string, ConfigurationData> configuration, DateTimeOffset timestamp, SQLiteConnection conn)
        {
            SimpleEncryptDecrypt sed = new SimpleEncryptDecrypt();

            foreach (KeyValuePair <string, ConfigurationData> kvp in configuration)
            {
                ConfigurationData config_data = kvp.Value;

                if (config_data.path.EndsWith("connection_string", StringComparison.InvariantCultureIgnoreCase))
                {
                    config_data.value = sed.Encrypt(config_data.value);
                }

                Configuration.SetValue(config_data.path, config_data.value, true, timestamp, conn);
            }
        }
示例#13
0
        private static void UpdateConfiguration(ConfigurationData config_data, DateTimeOffset timestamp, SQLiteConnection conn)
        {
            if (config_data.deleted)
            {
                Configuration.Clear(config_data.path, conn);
            }
            else
            {
                if (config_data.path.EndsWith("connection_string", StringComparison.InvariantCultureIgnoreCase))
                {
                    SimpleEncryptDecrypt sed = new SimpleEncryptDecrypt();
                    config_data.value = sed.Encrypt(config_data.value);
                }

                Configuration.SetValue(config_data.path, config_data.value, true, timestamp, conn);
            }
        }
示例#14
0
        private static void UpdateDevice(DeviceInfo device, DateTimeOffset timestamp, SQLiteConnection conn)
        {
            if (device.deleted)
            {
                RemoveDevice(device, conn);
            }
            else
            {
                // Grab the original device name
                string original_device_name = string.Empty;
                string original_ip_address  = string.Empty;
                bool   do_insert            = false;
                string sql = string.Format("SELECT Name, IPAddress FROM Devices WHERE DeviceID = {0}", device.id);
                using (SQLiteCommand command = new SQLiteCommand(sql, conn))
                    using (SQLiteDataReader reader = command.ExecuteReader())
                    {
                        if (reader.Read())
                        {
                            if (reader.IsDBNull(0) == false)
                            {
                                original_device_name = reader.GetString(0);
                            }

                            if (reader.IsDBNull(1) == false)
                            {
                                original_ip_address = reader.GetString(1);

                                // If the IP address hasn't changed, no need to remove it from the NetworkStatus
                                if (original_ip_address == device.ipAddress)
                                {
                                    original_ip_address = string.Empty;
                                }
                            }
                        }
                        else
                        {
                            do_insert = true;
                        }
                    }

                if (do_insert == false)
                {
                    // Just update everything
                    SimpleEncryptDecrypt sed = new SimpleEncryptDecrypt();
                    Updater update           = new Updater("Devices", string.Format("DeviceID = {0}", device.id), conn);
                    update.Set("Name", device.name, true);
                    update.Set("IPAddress", device.ipAddress, true);
                    update.Set("Username", device.username, true);
                    update.Set("Password", sed.Encrypt(device.password), false);
                    if (device.groupID < 0)
                    {
                        update.SetNull("GroupID");
                    }
                    else
                    {
                        update.Set("GroupID", device.groupID);
                    }
                    update.Execute();

                    Database.UpdateCollectors(device.id, device.name, original_device_name, device.collectors, timestamp, conn);
                }
                else
                {
                    // The device didn't exist, so just add it.
                    AddDevice(device, timestamp, conn);
                }

                if (string.IsNullOrEmpty(original_device_name) == false)
                {
                    // Make sure if the name changed that the NetworkStatus table is updated properly
                    Updater network_updater = new Updater("NetworkStatus", string.Format("Name = '{0}'", original_device_name), conn);
                    network_updater.Set("Name", device.name, false);
                    network_updater.Execute();
                }

                if (string.IsNullOrEmpty(original_ip_address) == false)
                {
                    // In case the IP address was changed, delete the original IP address and let the new one fill it in.
                    Deleter deleter = new Deleter("NetworkStatus", string.Format("IPAddress = '{0}'", original_ip_address), conn);
                    deleter.Execute();
                }
            }
        }
示例#15
0
        public static SystemConfiguration Get(bool obfuscate, SQLiteConnection conn)
        {
            SystemConfiguration config = new SystemConfiguration();
            string sql = string.Empty;
            ILog   log = LogManager.GetLogger(typeof(SystemConfigurationStore));

            try
            {
                Dictionary <string, string> monitoredDrives = null;
                SimpleEncryptDecrypt        sed             = new SimpleEncryptDecrypt();

                sql = "SELECT ConfigurationID, Path, Value FROM Configuration WHERE IsValid = 1;";
                using (SQLiteCommand command = new SQLiteCommand(sql, conn))
                    using (SQLiteDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            string path  = reader.GetString(1);
                            string value = reader.IsDBNull(2) ? "" : reader.GetString(2);
                            if (path.EndsWith("connection_string", StringComparison.InvariantCultureIgnoreCase))
                            {
                                if (obfuscate)
                                {
                                    value = "*****";
                                }
                                else
                                {
                                    value = sed.Decrypt(value);
                                }
                            }

                            config.configuration[path] = new ConfigurationData()
                            {
                                configID = reader.GetInt32(0),
                                path     = path,
                                value    = value
                            };

                            if (string.Compare(path, "languages", true) == 0)
                            {
                                Languages lang = new Languages();
                                lang.EnableFromDelimitedString(value);
                                foreach (Language l in lang.All)
                                {
                                    config.languages.Add(new LanguageConfiguration()
                                    {
                                        languageCode = l.GetDescription(), language = l.ToString(), isEnabled = lang.IsEnabled(l)
                                    });
                                }
                            }
                        }
                    }

                Attribute attr = new Attribute();
                config.softwareVersion = attr.Get("software.version", conn);
                if (config.softwareVersion == null)
                {
                    config.softwareVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString();
                }
                monitoredDrives = attr.GetMultiple("all.drives.descriptions", conn);
                List <string> device_names = monitoredDrives.Keys.ToList();
                foreach (string name in device_names)
                {
                    string[] n = name.Split('.');
                    if (n.Length > 0)
                    {
                        monitoredDrives.ChangeKey(name, n[0]);
                    }
                }

                sql = "SELECT GroupID, Name FROM DeviceGroups";
                using (SQLiteCommand command = new SQLiteCommand(sql, conn))
                    using (SQLiteDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            Group g = new Group()
                            {
                                id = reader.GetInt32(0), name = reader.GetString(1)
                            };
                            config.groups.Add(g);
                        }
                    }

                config.devices = new Database().GetDevices(conn);

                if (monitoredDrives != null)
                {
                    foreach (DeviceInfo dev in config.devices)
                    {
                        string drive_info;
                        if (monitoredDrives.TryGetValue(dev.name, out drive_info))
                        {
                            try
                            {
                                dev.driveNames = JsonConvert.DeserializeObject <Dictionary <string, string> >(drive_info);
                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                }

                LoadMonitoredDrives(config.devices, conn);

                // Get the most recent data that has been recorded
                sql = "SELECT Timestamp FROM Data ORDER BY Timestamp DESC LIMIT 1;";
                using (SQLiteCommand command = new SQLiteCommand(sql, conn))
                    using (SQLiteDataReader reader = command.ExecuteReader())
                    {
                        if (reader.Read())
                        {
                            try
                            {
                                DateTimeOffset ts = DateTimeOffset.Parse(reader.GetString(0));
                                config.mostRecentData = ts;
                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
            }
            catch (Exception ex)
            {
                log.Error("GetSystemConfiguration: " + sql);
                log.Error(ex);
            }

            log.Debug("Configuration: \n" + JsonConvert.SerializeObject(config.devices, Formatting.Indented));

            return(config);
        }