Exemplo n.º 1
0
        /// <summary>
        /// Build a merged list of safes.
        /// </summary>
        /// <param name="leftItems">List of safes from the left repository, whose order has precedence.</param>
        /// <param name="rightItems">List of safes from the right side repository.</param>
        /// <returns>List of safes for the new merged repository.</returns>
        private static SafeListModel BuildMergedListOfSafes(SafeListModel leftItems, SafeListModel rightItems)
        {
            SafeListModel result = new SafeListModel();

            var map = OuterJoin(leftItems, rightItems, item => item.Id);

            foreach (Tuple <SafeModel, SafeModel> pair in map)
            {
                if (pair.Item1 == null)
                {
                    // Only available on the right side
                    result.Add(pair.Item2.Clone());
                }
                else if (pair.Item2 == null)
                {
                    // Only available on the left side
                    result.Add(pair.Item1.Clone());
                }
                else
                {
                    // Take the more recent
                    SafeModel lastModifiedItem = ChooseLastModified(
                        pair.Item1, pair.Item2, item => item.ModifiedAt, null);
                    result.Add(lastModifiedItem.Clone());
                }
            }
            return(result);
        }
Exemplo n.º 2
0
        private void Ok()
        {
            List <SafeInfo> matchingSafes = TryPasswordOnSafes(OldPassword);

            InvalidOldPasswordError          = matchingSafes.Count == 0;
            InvalidPasswordError             = !ValidatePassword(Password);
            InvalidPasswordConfirmationError = !ValidatePasswordConfirmation(Password, PasswordConfirmation);
            if (InvalidOldPasswordError || InvalidPasswordError || InvalidPasswordConfirmationError)
            {
                return;
            }

            // Change the encrypted key of each safe which could have been opened with the password.
            string algorithm = _settingsService.LoadSettingsOrDefault().SelectedEncryptionAlgorithm;

            foreach (SafeInfo safeInfo in matchingSafes)
            {
                // No need to open or close the safe, just replace the encrypted key.
                safeInfo.Safe.SerializeableKey = SafeModel.EncryptKey(safeInfo.Key, Password, _randomService, algorithm);
                safeInfo.Safe.RefreshModifiedAt();
            }

            Modified = true;
            _navigationService.Navigate(new Navigation(ControllerNames.NoteRepository));
        }
Exemplo n.º 3
0
        /// <summary>
        /// Tries the password on all safes and returns a list of decrypted safes/keys.
        /// The function does not change the open/close state of the safe.
        /// </summary>
        /// <param name="password">Password to test with.</param>
        /// <returns>List of safes where the password matches.</returns>
        private List <SafeInfo> TryPasswordOnSafes(SecureString password)
        {
            List <SafeInfo> result = new List <SafeInfo>();

            foreach (SafeModel safe in Model.Safes)
            {
                if (SafeModel.TryDecryptKey(safe.SerializeableKey, password, out byte[] key))
Exemplo n.º 4
0
        public IActionResult Delete(String id)
        {
            var model = new SafeModel();

            model.DisableLogin(id);

            return(RedirectToAction("Index"));
        }
Exemplo n.º 5
0
        private void CreateNewSafe(SecureString password)
        {
            SafeModel safe      = new SafeModel();
            string    algorithm = _settingsService.LoadSettingsOrDefault().SelectedEncryptionAlgorithm;

            safe.GenerateNewKey(password, _randomService, algorithm);
            Model.Safes.Add(safe);
        }
Exemplo n.º 6
0
        public IActionResult LogOff()
        {
            var model = new SafeModel();

            model.LogOff();

            return(RedirectToAction("Index", "Users"));
        }
Exemplo n.º 7
0
        /// <summary>
        /// Encrpyts the unlocked content with the key of the assigned safe.
        /// </summary>
        /// <param name="unlockedContent">Content to encrypt.</param>
        /// <returns>Encrypted content.</returns>
        public string Lock(string unlockedContent)
        {
            string    encryptionAlgorithm = _settingsService.LoadSettingsOrDefault().SelectedEncryptionAlgorithm;
            SafeModel safe = _safes.FindById(Model.SafeId);

            byte[] binaryContent = CryptoUtils.StringToBytes(unlockedContent);
            byte[] lockedContent = _cryptor.Encrypt(binaryContent, safe.Key, encryptionAlgorithm, null);
            return(CryptoUtils.BytesToBase64String(lockedContent));
        }
Exemplo n.º 8
0
        public void MergeSafes()
        {
            Guid     safe1Id    = new Guid("10000000000000000000000000000000");
            Guid     safe2Id    = new Guid("20000000000000000000000000000000");
            Guid     safe3Id    = new Guid("30000000000000000000000000000000");
            Guid     safe4Id    = new Guid("40000000000000000000000000000000");
            Guid     safe5Id    = new Guid("50000000000000000000000000000000");
            Guid     safe6Id    = new Guid("60000000000000000000000000000000");
            DateTime newerDate  = new DateTime(2008, 08, 08);
            DateTime middleDate = new DateTime(2006, 06, 06);

            NoteRepositoryModel serverRepo = new NoteRepositoryModel();
            SafeModel           safeS1     = new SafeModel {
                Id = safe2Id, SerializeableKey = "s1", ModifiedAt = newerDate
            };
            SafeModel safeS2 = new SafeModel {
                Id = safe4Id, SerializeableKey = "s2", ModifiedAt = middleDate
            };
            SafeModel safeS3 = new SafeModel {
                Id = safe6Id, SerializeableKey = "s3", ModifiedAt = middleDate
            };

            serverRepo.Safes.AddRange(new[] { safeS1, safeS2, safeS3 });
            AddNotesWithSafeIds(serverRepo, new[] { safe2Id, safe4Id, safe6Id });

            NoteRepositoryModel clientRepo = new NoteRepositoryModel();
            SafeModel           safeC1     = new SafeModel {
                Id = safe5Id, SerializeableKey = "c1", ModifiedAt = middleDate
            };
            SafeModel safeC2 = new SafeModel {
                Id = safe4Id, SerializeableKey = "c2", ModifiedAt = newerDate
            };
            SafeModel safeC3 = new SafeModel {
                Id = safe2Id, SerializeableKey = "c3", ModifiedAt = middleDate
            };
            SafeModel safeC4 = new SafeModel {
                Id = safe1Id, SerializeableKey = "c4", ModifiedAt = middleDate
            };
            SafeModel safeC5 = new SafeModel {
                Id = safe3Id, SerializeableKey = "c5", ModifiedAt = middleDate
            };

            clientRepo.Safes.AddRange(new[] { safeC1, safeC2, safeC3, safeC4, safeC5 });
            AddNotesWithSafeIds(clientRepo, new[] { safe5Id, safe4Id, safe2Id, safe1Id, safe3Id });

            NoteRepositoryMerger merger = new NoteRepositoryMerger();
            NoteRepositoryModel  result = merger.Merge(clientRepo, serverRepo);
            SafeListModel        safes  = result.Safes;

            Assert.AreEqual(6, safes.Count);
            Assert.AreEqual(safe5Id, safes[0].Id); Assert.AreEqual("c1", safes[0].SerializeableKey);
            Assert.AreEqual(safe2Id, safes[1].Id); Assert.AreEqual("s1", safes[1].SerializeableKey);
            Assert.AreEqual(safe1Id, safes[2].Id); Assert.AreEqual("c4", safes[2].SerializeableKey);
            Assert.AreEqual(safe3Id, safes[3].Id); Assert.AreEqual("c5", safes[3].SerializeableKey);
            Assert.AreEqual(safe4Id, safes[4].Id); Assert.AreEqual("c2", safes[4].SerializeableKey);
            Assert.AreEqual(safe6Id, safes[5].Id); Assert.AreEqual("s3", safes[5].SerializeableKey);
        }
Exemplo n.º 9
0
        public void EnsureBackwardsCompatibilityDecryption()
        {
            string       encryptedKey = "U2lsZW50U2FmZSB2PTIkYWVzX2djbSQ2ZXVQN3NSQ2dHQStadTJGeE80QkJRPT0kcGJrZGYyJEs0TjY5dmllRTBvaEg1UlVvVDUydGc9PSQxMDAwMCQkT1cFrC+EM9E5PlM4uPGUv0HsOQ==";
            SecureString password     = CryptoUtils.StringToSecureString("testpassword");
            bool         res          = SafeModel.TryDecryptKey(encryptedKey, password, out byte[] decryptedKey);

            byte[] originalKey = new byte[] { 88, 99, 11 };
            Assert.IsTrue(res);
            Assert.IsTrue(originalKey.SequenceEqual(decryptedKey));
        }
Exemplo n.º 10
0
        public void EncryptedKeyCanBeDecrypted()
        {
            byte[]              key          = new byte[] { 88, 99, 11 };
            SecureString        password     = CryptoUtils.StringToSecureString("testpassword");
            ICryptoRandomSource randomSource = CommonMocksAndStubs.CryptoRandomService();

            string encryptedKey = SafeModel.EncryptKey(key, password, randomSource, BouncyCastleAesGcm.CryptoAlgorithmName);
            bool   res          = SafeModel.TryDecryptKey(encryptedKey, password, out byte[] decryptedKey);

            Assert.IsTrue(res);
            Assert.IsTrue(key.SequenceEqual(decryptedKey));
        }
Exemplo n.º 11
0
        /// <summary>
        /// Decrypts the note, if the belonging safe is open.
        /// </summary>
        /// <returns>Decrypted note content, or null if the safe is closed.</returns>
        private string UnlockIfSafeOpen(string lockedContent)
        {
            SafeModel safe = _safes.FindById(Model.SafeId);

            if ((safe != null) && safe.IsOpen)
            {
                byte[] binaryContent   = CryptoUtils.Base64StringToBytes(lockedContent);
                byte[] unlockedContent = _cryptor.Decrypt(binaryContent, safe.Key);
                return(CryptoUtils.BytesToString(unlockedContent));
            }
            return(null);
        }
        public void AddNoteToSafe(Guid noteId)
        {
            NoteViewModel note           = AllNotes.Find(item => item.Id == noteId);
            SafeModel     oldestOpenSafe = Model.Safes.FindOldestOpenSafe();

            if ((note != null) && (oldestOpenSafe != null))
            {
                note.Model.SafeId      = oldestOpenSafe.Id;
                note.Model.HtmlContent = note.Lock(note.UnlockedHtmlContent);
                note.Model.RefreshModifiedAt();
                Modified = true;
            }
        }
        private static void AddSafeToOtherRepositoryIfMissing(NoteRepositoryModel myRepository, NoteRepositoryModel otherRepository, Guid?safeId)
        {
            bool isMissingInOtherRepository = (safeId != null) && (otherRepository.Safes.FindById(safeId) == null);

            if (isMissingInOtherRepository)
            {
                SafeModel mySafe = myRepository.Safes.FindById(safeId);
                if (mySafe != null)
                {
                    otherRepository.Safes.Add(mySafe.Clone());
                }
            }
        }
        // Kasa
        public ActionResult Index(SafeModel model)
        {
            var aaax = db.SRFs.Where(w => w.Active == true && w.SFRState == EnumProductState.SFRWasDelivered).ToList();

            foreach (var item in aaax)
            {
                var y = db.Customers.Where(w => w.Id == item.CustomerId).FirstOrDefault();
                if (y != null)
                {
                    item.customer.UserName = y.UserName;
                }
                var z = db.Products.Where(w => w.Id == item.ProductId).FirstOrDefault();
                if (z != null)
                {
                    item.product.PBrand = z.PBrand;
                    item.product.PModel = z.PModel;
                }
            }
            var datetime1 = new DateTime(0001, 01, 01);

            if (model.Start == datetime1)
            {
                model.Start = new DateTime(2018, 01, 01);
            }

            SafeModel Safe = new SafeModel()
            {
                Start = model.Start,
                End   = model.End,
            };

            if (Safe.End.Hour < 24)
            {
                int x = 23 - Safe.End.Hour;
                Safe.End = Safe.End.AddHours(x);
            }
            if (Safe.Start.Hour > 0)
            {
                int y = Safe.Start.Hour - 0;
                Safe.Start = Safe.Start.AddHours(-y);
            }
            //var Bank = db.Banks.Where(w => w.BankTime >= Safe.Start && w.BankTime <= Safe.End).ToList();
            //foreach (var item in Bank)
            //{
            //    Safe.TotalGain = item.Payment + Safe.TotalGain;
            //}

            Safe.ServiceRegistrationForms = aaax.Where(w => w.SRFDatetime >= model.Start && w.SRFDatetime <= model.End).ToList();
            Safe.Total = Safe.ServiceRegistrationForms.Sum(s => s.Price);
            return(View(Safe));
        }
Exemplo n.º 15
0
        public void ClosingTheSafeWillRemoveKeyFromMemory()
        {
            byte[]    key  = new byte[] { 88, 99, 11 };
            SafeModel safe = new SafeModel
            {
                SerializeableKey = "sugus",
                Key = key,
            };

            safe.Close();

            bool hasUncleanedBytes = key.Any(item => item != 0);

            Assert.IsNull(safe.Key);
            Assert.IsFalse(hasUncleanedBytes);
        }
Exemplo n.º 16
0
        /// <inheritdoc/>
        public override bool NeedsNavigationRedirect(Navigation original, out Navigation redirectTo)
        {
            if (original.Variables.TryGetValue(ControllerParameters.NoteId, out string noteId))
            {
                // Get the note from the repository
                _repositoryService.LoadRepositoryOrDefault(out NoteRepositoryModel noteRepository);
                NoteModel note = noteRepository.Notes.FindById(new Guid(noteId));

                // Find its safe and check if it needs to be opened
                SafeModel safe = noteRepository.Safes.FindById(note?.SafeId);
                if ((safe != null) && (!safe.IsOpen))
                {
                    redirectTo = new Navigation(ControllerNames.OpenSafe, ControllerParameters.NoteId, noteId);
                    return(true);
                }
            }
            redirectTo = null;
            return(false);
        }
Exemplo n.º 17
0
        public void CloneCopiesAllProperties()
        {
            SafeModel note1 = new SafeModel
            {
                Id               = Guid.NewGuid(),
                CreatedAt        = new DateTime(2000, 10, 22, 18, 55, 30),
                ModifiedAt       = new DateTime(2001, 10, 22, 18, 55, 30),
                MaintainedAt     = new DateTime(2002, 10, 22, 18, 55, 30),
                SerializeableKey = "sugus",
                Key              = new byte[] { 88 },
            };
            SafeModel note2 = note1.Clone();

            Assert.AreEqual(note1.Id, note2.Id);
            Assert.AreEqual(note1.CreatedAt, note2.CreatedAt);
            Assert.AreEqual(note1.ModifiedAt, note2.ModifiedAt);
            Assert.AreEqual(note1.MaintainedAt, note2.MaintainedAt);
            Assert.AreEqual(note1.SerializeableKey, note2.SerializeableKey);
            Assert.IsNull(note2.Key); // The unprotected key won't be cloned, the safe is closed.
        }
Exemplo n.º 18
0
        public void FindOldestOpenSafeWorksCorrectly()
        {
            SafeListModel list = new SafeListModel();

            byte[] testKey = new byte[0];

            // Search in empty list
            Assert.IsNull(list.FindOldestOpenSafe());

            // Search with only one element
            SafeModel safe2002 = new SafeModel {
                CreatedAt = new DateTime(2002, 02, 02), Key = testKey
            };

            list.Add(safe2002);
            Assert.AreSame(safe2002, list.FindOldestOpenSafe());

            // Add newer element
            SafeModel safe2003 = new SafeModel {
                CreatedAt = new DateTime(2003, 03, 03), Key = testKey
            };

            list.Add(safe2003);
            Assert.AreSame(safe2002, list.FindOldestOpenSafe());

            // Add closed safe
            SafeModel safe2000 = new SafeModel {
                CreatedAt = new DateTime(2000, 01, 01), Key = null
            };

            list.Add(safe2000);
            Assert.AreSame(safe2002, list.FindOldestOpenSafe());

            // Add older element
            SafeModel safe2001 = new SafeModel {
                CreatedAt = new DateTime(2001, 01, 01), Key = testKey
            };

            list.Add(safe2001);
            Assert.AreSame(safe2001, list.FindOldestOpenSafe());
        }
Exemplo n.º 19
0
        public void RemoveUnusedSafesWorksCorrectly()
        {
            Guid safe1Id = new Guid("10000000000000000000000000000000");
            Guid safe2Id = new Guid("20000000000000000000000000000000");

            NoteRepositoryModel repository = new NoteRepositoryModel();
            SafeModel           safeS1     = new SafeModel {
                Id = safe1Id
            };
            SafeModel safeS2 = new SafeModel {
                Id = safe2Id
            };

            repository.Safes.AddRange(new[] { safeS1, safeS2 });
            NoteModel noteN2 = new NoteModel {
                SafeId = safe2Id
            };

            repository.Notes.Add(noteN2);

            repository.RemoveUnusedSafes();
            Assert.AreEqual(1, repository.Safes.Count);
            Assert.AreEqual(safe2Id, repository.Safes[0].Id);
        }
 public ActionResult SafePost(SafeModel safe)
 {
     return(RedirectToAction("Index", safe));
 }