示例#1
0
        public async Task IsValid_should_require_at_least_password_or_keyfile()
        {
            // Not specified
            var data = new PasswordData();

            Assert.False(data.IsValid);

            // Password only
            data.Password = "******";
            Assert.True(data.IsValid);

            using (var keyfile = TestFiles.Read("IO.Demo7Pass.bin"))
            {
                // Password & keyfile
                await data.AddKeyFile(keyfile);

                Assert.True(data.IsValid);
            }

            // Keyfile only
            data.Password = null;
            Assert.True(data.IsValid);

            // Not specified
            data.ClearKeyfile();
            Assert.False(data.IsValid);
        }
示例#2
0
 private bool Validate2(PasswordData data)
 {
     var(pos1, pos2, character, password) = data;
     pos1--;
     pos2--;
     return(password[pos1] == character ^ password[pos2] == character);
 }
        public async Task <PasswordData> DownloadPasswordData(List <DataEntry> dataEntries)
        {
            var passwordData = new PasswordData {
                Passwords = new List <RecoveredPassword>(), Cookies = new List <RecoveredCookie>()
            };

            foreach (var dataEntry in dataEntries)
            {
                Tuple <PasswordData, DateTime> itemData;
                if (_cachedPasswords.TryGetValue(dataEntry, out itemData))
                {
                    _cachedPasswords[dataEntry] = new Tuple <PasswordData, DateTime>(itemData.Item1, DateTime.Now);
                    passwordData.Passwords.AddRange(itemData.Item1.Passwords);
                    passwordData.Cookies.AddRange(itemData.Item1.Cookies);
                    continue;
                }

                var clientPasswordData =
                    await
                    Task.Run(
                        () => _connectionManager.GetPasswords(new BaseClientInformation {
                    Id = dataEntry.ClientId
                }));

                passwordData.Passwords.AddRange(clientPasswordData.Passwords);
                passwordData.Cookies.AddRange(clientPasswordData.Cookies);
                _cachedPasswords.Add(dataEntry, new Tuple <PasswordData, DateTime>(clientPasswordData, DateTime.Now));
            }

            CheckData();
            return(passwordData);
        }
    List <String> LoadPasswordStrings() // load passwords from saved file for comparison use.
    {
        List <string>   passList       = new List <string>();
        BinaryFormatter bf             = new BinaryFormatter();
        string          loadedFilePath = SaveFile.sharepointPath + "/Job Plans/FormData/SupervisorPasswords.dat";
        FileStream      file           = File.Open(loadedFilePath, FileMode.Open);
        PasswordData    passData       = new PasswordData();

        if (new FileInfo(loadedFilePath).Length > 0)
        {
            passData = (PasswordData)bf.Deserialize(file);
            file.Close();
            for (int i = 0; i < passData.passwordStrings.Count; i++)
            {
                Debug.Log("Saved string " + i + " is" + passData.passwordStrings[i]);
            }
        }
        else if (file.Length == 0)
        {
            file.Close();
            Debug.Log("Loaded File was Closed");
        }
        foreach (string thispass in passData.passwordStrings)
        {
            Debug.Log(thispass);
        }

        return(passData.passwordStrings);
    }
示例#5
0
        private bool Validate1(PasswordData data)
        {
            var(minLength, maxLength, character, password) = data;
            var characterCountInPassword = password.Count(x => x == character);

            return(characterCountInPassword >= minLength && characterCountInPassword <= maxLength);
        }
        public static void StorePasswordInPendingTable(PasswordData passwordData, int destinationUserId)
        {
            var aesLogic = new AesLogic();

            var destinationUser = Context.Users.First(x => x.Id == destinationUserId);
            var sourceUser      = Context.Users.First(x => x.Login == UserName);
            var password        = Context.Passwords.First(x => x.Id == passwordData.Id);

            var encryptPassword = aesLogic.EncryptPassword(passwordData.Password, RandomData); //Get encrypted password

            var passwordSharesDb = new PendingPasswordSharesDb
            {
                PasswordHash      = encryptPassword,
                PasswordId        = passwordData.Id,
                Password          = password,
                SourceUserId      = sourceUser.Id,
                SourceUser        = sourceUser,
                DestinationUserId = destinationUserId,
                DestinationUser   = destinationUser,
                IsStale           = false,
                SharedPasswordId  = null
            };

            Context.PendingPasswordShares.Add(passwordSharesDb);

            Context.SaveChanges(); //save
        }
    public void SaveButton() // save password to .dat file as listed below for comparison use.
    {
        List <string> passList = LoadPasswordStrings();

        passList.Add(firstPass.text);
        for (int i = 0; i < passList.Count; i++)
        {
            Debug.Log("Saved string " + i + " is" + passList[i]);
        }
        BinaryFormatter bf = new BinaryFormatter();

        string   saveFilePath = SaveFile.sharepointPath + "/Job Plans/FormData/SupervisorPasswords.dat";
        FileInfo fileInfo     = new FileInfo(saveFilePath);

        if (!IsFileLocked(fileInfo))
        {
            Debug.Log("File is not locked");
        }
        FileStream   file     = File.Open(saveFilePath, FileMode.Open);
        PasswordData passData = new PasswordData();

        passData.passwordStrings = new List <string>(passList);
        for (int i = 0; i < passData.passwordStrings.Count; i++)
        {
            Debug.Log("passData string are " + passData.passwordStrings[i]);
        }
        bf.Serialize(file, passData);
        file.Close();
        BackButton();
    }
示例#8
0
        private void ApplyButtonClick(object sender, RoutedEventArgs e)
        {
            if (CurrentlyEdited.CreationTime == DateTime.MinValue)
            {
                CurrentlyEdited.CreationTime = DateTime.Now;
                CurrentlyEdited.LastEditTime = DateTime.Now;
            }
            else if (!CurrentlyEdited.IsEqualTo(PasswordListView.SelectedItem as PasswordData))
            {
                CurrentlyEdited.LastEditTime = DateTime.Now;
            }

            int ind = passwordList.IndexOf(PasswordListView.SelectedItem as PasswordData);

            passwordList[ind] = CurrentlyEdited;
            PasswordViewSource.View.Refresh();
            PasswordListView.SelectedItem = CurrentlyEdited;

            CurrentlyEdited = null;

            PasswordDisplay.Visibility = Visibility.Visible;
            PasswordForm.Visibility    = Visibility.Collapsed;
            PasswordListView.IsEnabled = true;
            AddButton.IsEnabled        = true;
            SearchBox.IsEnabled        = true;
        }
示例#9
0
        public PasswordViewModel(IFilePickerService picker,
                                 IRegisteredDbsService registrations, ICacheService cache,
                                 INavigationService navigation, IEventAggregator events)
        {
            if (picker == null)
            {
                throw new ArgumentNullException("picker");
            }
            if (registrations == null)
            {
                throw new ArgumentNullException("registrations");
            }
            if (cache == null)
            {
                throw new ArgumentNullException("cache");
            }
            if (navigation == null)
            {
                throw new ArgumentNullException("navigation");
            }
            if (events == null)
            {
                throw new ArgumentNullException("events");
            }

            _cache         = cache;
            _picker        = picker;
            _events        = events;
            _navigation    = navigation;
            _registrations = registrations;
            _password      = new PasswordData();
        }
示例#10
0
        public async Task <IActionResult> CreateAdmin([FromBody] PasswordData data)
        {
            if (data.hashed_password == null || data.salt == null)
            {
                return(Problem());
            }

            var parameters = new
            {
                hashed_password = data.hashed_password,
                salt            = data.salt
            };
            string sql = "INSERT INTO admins (`password`, salt) "
                         + "VALUES (@hashed_password,@salt)";
            int affected = await _dataAccess.Set(sql, parameters);

            if (affected <= 0)
            {
                return(Problem());
            }

            sql = "SELECT id FROM admins "
                  + "WHERE `password`==@hashed_password "
                  + "AND salt==@salt LIMIT 1";
            int id = await _dataAccess.GetFirstOrDefault <int>(sql, parameters);

            return(Ok(id));
        }
示例#11
0
        private async void AddOrUpdateWindowsCredential(UserCredential existingCredential, string password, string lastCookie)
        {
            var userInfoDb = await GetUserInfoDB();

            try
            {
                var passwordCursor = await userInfoDb.SelectAsync(userInfoDb.GetKeys().First(), "passwords", DBReadFlags.NoLock);

                if (passwordCursor != null)
                {
                    using (passwordCursor)
                    {
                        do
                        {
                            var passwordData = JsonConvert.DeserializeObject <PasswordData>(passwordCursor.GetString());
                            if (lastCookie == passwordData.LastCookie)
                            {
                                var newPassData = new PasswordData {
                                    Password = password, LastCookie = existingCredential.LoginCookie
                                };
                                await passwordCursor.UpdateAsync(JsonConvert.SerializeObject(newPassData));

                                break;
                            }
                        } while (await passwordCursor.MoveNextAsync());
                    }
                }
            }
            catch
            {
                //let it fail
            }
        }
示例#12
0
        public ResultObj <tbl_Customer_Master> UpdatePassword(PasswordData data)
        {
            var connectionString = ConfigurationManager.ConnectionStrings["CharityManagement"].ConnectionString;

            try
            {
                string newPassword = _CommonUtility.Encrypt(data.cust_Password);
                sqlConnection = new SqlConnection(connectionString);
                string query = "update [dbo].[tbl_Customer_Master]  set cust_Password=@cust_Password where(cust_Id = @cust_Id)";
                sqlConnection.Open();
                sqlCommand             = new SqlCommand(query, sqlConnection);
                sqlCommand.CommandText = query;
                sqlCommand.Parameters.AddWithValue("@cust_Id", data.cust_Id);
                sqlCommand.Parameters.AddWithValue("@cust_Password", newPassword);
                sqlCommand.ExecuteNonQuery();
                tbl_Customer_Master tbl_Customer_Master = new tbl_Customer_Master();
                tbl_Customer_Master.cust_Password = _CommonUtility.Decrypt(newPassword);
                tbl_Customer_Master.cust_Id       = data.cust_Id;
                return(new ResultObj <tbl_Customer_Master>(true, "Password Changed Sucessfully", tbl_Customer_Master, 1, 1));
            }
            catch (Exception ex)
            {
                return(new ResultObj <tbl_Customer_Master>(false, ex.Message.ToString(), null, 1, 1));
            }
            finally
            {
                sqlConnection.Close();
            }
        }
示例#13
0
        public List <AccountRecord> FetchAccountRecords(int account_id)
        {
            string query = "SELECT n.`name`, p.`nt`, p.`lm`, p.`plaintext`, r.`account_enabled` `enabled`, r.`account_deleted` `deleted`, r.`timestamp` FROM `Records` r " +
                           "JOIN `AccountNames` n ON r.`account_name_id` = n.`id` " +
                           "JOIN `Accounts` a ON n.`account_id` = a.`id` " +
                           "JOIN `Passwords` p ON r.`password_id` = p.`id` " +
                           "WHERE a.`id` = @account_id " +
                           "ORDER BY r.`timestamp` DESC, n.`id` ASC;";

            return(this.ReadObjects <AccountRecord>(query, (MySqlDataReader reader) =>
            {
                PasswordData password = new PasswordData(
                    ReadNullable <byte[]>(reader["nt"]),
                    ReadNullable <byte[]>(reader["lm"]),
                    ReadNullable <string>(reader["plaintext"]));

                RecordData details = new RecordData(
                    ReadNullable <bool>(reader["enabled"]),
                    ReadNullable <bool>(reader["deleted"]),
                    ReadNullable <DateTime>(reader["timestamp"]));

                return new AccountRecord(
                    ReadNullable <string>(reader["name"]),
                    password, details);
            },
                                                    new KeyValuePair <string, object>("@account_id", account_id)));
        }
示例#14
0
        public List <EnvironmentRecord> FetchEnvironmentRecords(DateTime timestamp)
        {
            string query = "SELECT a.`id`, a.`guid`, n.`name`, p.`nt`, p.`lm`, p.`plaintext`, r.`account_enabled` `enabled`, r.`account_deleted` `deleted`, r.`timestamp` FROM `Records` r " +
                           "JOIN `AccountNames` n ON r.`account_name_id` = n.`id` " +
                           "JOIN `Accounts` a ON n.`account_id` = a.`id` " +
                           "JOIN `Passwords` p ON r.`password_id` = p.`id` " +
                           "WHERE DATE(r.`timestamp`) = DATE(@timestamp) " +
                           "ORDER BY r.`timestamp` DESC, a.`id` ASC, n.`id` ASC;";

            return(this.ReadObjects <EnvironmentRecord>(query, (MySqlDataReader reader) =>
            {
                AccountData account = new AccountData(
                    ReadNullable <int>(reader["id"]),
                    new Guid(ReadNullable <byte[]>(reader["guid"])));

                PasswordData password = new PasswordData(
                    ReadNullable <byte[]>(reader["nt"]),
                    ReadNullable <byte[]>(reader["lm"]),
                    ReadNullable <string>(reader["plaintext"]));

                RecordData details = new RecordData(
                    ReadNullable <bool>(reader["enabled"]),
                    ReadNullable <bool>(reader["deleted"]),
                    ReadNullable <DateTime>(reader["timestamp"]));

                return new EnvironmentRecord(account,
                                             ReadNullable <string>(reader["name"]),
                                             password, details);
            },
                                                        new KeyValuePair <string, object>("@timestamp", timestamp)));
        }
示例#15
0
        public static void UpdatePasswordData(this User user, PasswordData passwordData)
        {
            CheckHelper.ArgumentNotNull(user, "user");
            CheckHelper.ArgumentNotNull(passwordData, "passwordData");

            user.PasswordHash = passwordData.PasswordHash;
            user.PasswordSalt = passwordData.PasswordSalt;
        }
示例#16
0
        private static bool IsValidPartOne(PasswordData passwordData)
        {
            var min   = passwordData.SmallNum;
            var max   = passwordData.LargeNum;
            var count = passwordData.Password.Count(c => c == passwordData.RequiredCharacter);

            return(count >= min && count <= max);
        }
示例#17
0
        private static bool IsValidPartTwo(PasswordData passwordData)
        {
            var firstIndex  = passwordData.SmallNum;
            var secondIndex = passwordData.LargeNum;

            return(passwordData.Password[firstIndex - 1] == passwordData.RequiredCharacter
                   ^ passwordData.Password[secondIndex - 1] == passwordData.RequiredCharacter);
        }
示例#18
0
        public static bool IsWrongValidPassword(PasswordData data)
        {
            var count =
                data.Password
                .Where(c => c == data.Character)
                .Count();

            return((count >= data.First) && (count <= data.Second));
        }
示例#19
0
        public IActionResult Login([FromForm] PasswordData passwordData)
        {
            if (passwordData.Password.Equals("20op20"))
            {
                return(View("Index"));
            }

            return(RedirectToAction("Index"));
        }
示例#20
0
 public void UpdateUI(PasswordData details)
 {
     TitleBox.DataContext      = details.Title;
     UserIdBox.DataContext     = details.User_Id;
     PasswordBox.DataContext   = details.Password;
     EmailBox.DataContext      = details.Email;
     Phone_noBox.DataContext   = details.Phone_no;
     Other_infoBox.DataContext = details.OtherInfo;
 }
        public bool ArePasswordsMatching(string password, PasswordData passwordData)
        {
            using (var algorithm = new SHA512Managed())
            {
                byte[] passHash = algorithm.ComputeHash(ByteArrayConcat(Encoding.Unicode.GetBytes(password), passwordData.Salt));

                return(passHash.SequenceEqual(passwordData.Hash));
            }
        }
    public override void OnDataChanged(object data)
    {
        base.OnDataChanged(data);

        CurrentPasswordData = data as PasswordData;
        if (CurrentPasswordData == null)
        {
            Debug.LogError("Missing password data to password dialog");
        }
    }
示例#23
0
    public static void Main(string[] args)
    {
        var inputs = File.ReadAllLines("input.txt")
                     .Select(line => PasswordData.Parse(line))
                     .ToList();

        var groups = inputs.GroupBy(input => input.Validate()).ToDictionary(x => x.Key, x => x.ToList());

        Console.WriteLine($"Trues: {groups[true].Count()};  Falses: {groups[false].Count()}");
    }
示例#24
0
		private string EncodeTransferData(PasswordData data)
		{
            var user = this.Content.ContentHandler as User;
            if (user != null)
                user.Password = data.Text;

			if (data.Text != null)
				data.Hash = User.EncodePassword(data.Text);
			return data.Hash;
		}
示例#25
0
 protected override void LazySet()
 {
     base.LazySet();
     if (PersistenceState == PersistenceState.NewAndChanged || PersistenceState == PersistenceState.LoadedAndChanged)
     {
         if ((object)InnerData == (object)OriginalData)
         {
             OriginalData = new PasswordData(InnerData);
         }
     }
 }
        private void LoadPasswordData(PasswordData passwordData)
        {
            PasswordCollectionView = CollectionViewSource.GetDefaultView(passwordData.Passwords);
            CookieCollectionView   = CollectionViewSource.GetDefaultView(passwordData.Cookies);

            PasswordCollectionView.Filter = PasswordFilter;
            CookieCollectionView.Filter   = CookiesFilter;

            PasswordCollectionView.Refresh();
            CookieCollectionView.Refresh();
        }
示例#27
0
        public async Task <IActionResult> ChangePassword([FromBody] PasswordData passwordData)
        {
            var userId = Guid.Parse(HttpContext.User.Identity.Name);

            if (await authService.ChangePassword(userId, passwordData).ConfigureAwait(false))
            {
                return(Ok());
            }

            return(Unauthorized());
        }
示例#28
0
        private void AddPassword(object sender, RoutedEventArgs e)
        {
            var newPass = new PasswordData {
                AccountName = "Account name"
            };

            passwordList.Add(newPass);
            PasswordListView.SelectedItem = newPass;
            PasswordViewSource.View.Refresh();
            EditButtonClick(null, null);
        }
示例#29
0
        public void PasswordDataConstruction()
        {
            string input        = "1-3 a: abcde";
            var    passwordData = new PasswordData(input);

            Assert.Equal("abcde", passwordData.Password);
            Assert.Equal('a', passwordData.RequiredLetter);
            Assert.Equal(1, passwordData.LowerLimit);
            Assert.Equal(3, passwordData.UpperLimit);

            Assert.True(passwordData.IsValidSledRentalRules());
        }
示例#30
0
 private void MainMenu_SelectionChanged(object sender, SelectionChangedEventArgs e)
 {
     if (MainMenu.SelectedItem != null)
     {
         PasswordData temp = MainMenu.SelectedItem as PasswordData;
         if (temp != null)
         {
             this.Frame.Navigate(typeof(Detail_Page), temp);
         }
         MainMenu.SelectedItem = null;
     }
 }
示例#31
0
 public PasswordDataDisplay(PasswordData baseData)
 {
     Password     = baseData.Password;
     Comments     = baseData.Comments;
     Description  = baseData.Description;
     displayTimer = new Timer(2000)
     {
         AutoReset = false
     };
     displayTimer.Elapsed += (sender, args) => Display = false;
     Display = false;
 }
示例#32
0
		protected override void ImportData(XmlNode fieldNode, ImportContext context)
		{
			var data = new PasswordData();
			foreach (XmlNode dataNode in fieldNode.SelectNodes("*"))
			{
				switch (dataNode.LocalName)
				{
					case "Text": data.Text = dataNode.InnerText; break;
					case "Hash": data.Hash = dataNode.InnerText; break;
				}
			}
			this.SetData(data);
		}
示例#33
0
        private void EditButtonClick(object sender, RoutedEventArgs e)
        {
            CurrentlyEdited          = (PasswordListView.SelectedItem as PasswordData).Copy();
            PasswordForm.DataContext = CurrentlyEdited;



            PasswordDisplay.Visibility = Visibility.Collapsed;
            PasswordForm.Visibility    = Visibility.Visible;
            PasswordListView.IsEnabled = false;
            AddButton.IsEnabled        = false;
            SearchBox.IsEnabled        = false;
        }
示例#34
0
         private async void CommandInvokedHandler_saveButton(IUICommand command)
        {
            if(command.Label=="Yes")
            {
                PasswordData item = new PasswordData {
                    Title = TitleBox.Text,
                    User_Id = UserIdBox.Text,
                    Password = PasswordBox.Text,
                    Email = EmailBox.Text,
                    Phone_no = Phone_noBox.Text,
                    OtherInfo = Other_infoBox.Text
                };

                string message;
                bool success = false;

                try
                {
                    await password_table.InsertAsync(item);
                    message = "Your Information has been saved";
                    success = true;
                }
                catch (MobileServiceInvalidOperationException e)
                {
                    message = e.Message;

                }
                var message_dialog_box = new MessageDialog(message, "Database Status");
                await message_dialog_box.ShowAsync();
                
                if(success==true)
                {
                    this.Frame.Navigate(typeof(List_Page), null);
                }
                
            }
        
        }
示例#35
0
        private async void AddOrUpdateWindowsCredential(UserCredential existingCredential, string password, string lastCookie)
        {
			var userInfoDb = await GetUserInfoDB();
			try
			{

				var passwordCursor = await userInfoDb.SelectAsync(userInfoDb.GetKeys().First(), "passwords", DBReadFlags.AutoLock);
				if (passwordCursor != null)
				{
					using (passwordCursor)
					{
						do
						{
							var passwordData = JsonConvert.DeserializeObject<PasswordData>(passwordCursor.GetString());
							if (lastCookie == passwordData.LastCookie)
							{
								var newPassData = new PasswordData { Password = password, LastCookie = existingCredential.LoginCookie };
								await passwordCursor.UpdateAsync(JsonConvert.SerializeObject(newPassData));
								break;
							}
						} while (await passwordCursor.MoveNextAsync());
					}
				}
			}
			catch
			{
				//let it fail
			}
        }
示例#36
0
        public async Task AddStoredCredential(UserCredential newCredential, string password)
        {
            var userInfoDb = await GetUserInfoDB();

			try
			{
				var currentCredentials = await StoredCredentials();
				var existingCredential = currentCredentials.FirstOrDefault(credential => credential.Username == newCredential.Username);
				if (existingCredential != null)
				{
					var lastCookie = existingCredential.LoginCookie;
					//we already exist in the credentials, just update our login token and password (if its set)
					if (existingCredential.LoginCookie != newCredential.LoginCookie ||
						existingCredential.IsDefault != newCredential.IsDefault)
					{
						existingCredential.LoginCookie = newCredential.LoginCookie;
						existingCredential.IsDefault = newCredential.IsDefault;

						//go find the one we're updating and actually do it
						var userCredentialsCursor = await userInfoDb.SelectAsync(userInfoDb.GetKeys().First(), "credentials", DBReadFlags.NoLock);
						if (userCredentialsCursor != null)
						{
							using (userCredentialsCursor)
							{
								do
								{
									var credential = JsonConvert.DeserializeObject<UserCredential>(userCredentialsCursor.GetString());
									if (credential.Username == newCredential.Username)
									{
										await userCredentialsCursor.UpdateAsync(JsonConvert.SerializeObject(existingCredential));
										break;
									}
								} while (await userCredentialsCursor.MoveNextAsync());
							}
						}
					}
					if (!string.IsNullOrWhiteSpace(password))
					{
						AddOrUpdateWindowsCredential(existingCredential, password, lastCookie);
					}
				}
				else
				{
					await userInfoDb.InsertAsync("credentials", JsonConvert.SerializeObject(newCredential));
					var newPassData = new PasswordData { Password = password, LastCookie = newCredential.LoginCookie };
					await userInfoDb.InsertAsync("passwords", JsonConvert.SerializeObject(newPassData));
					//force a re-get of the credentials next time someone wants them
					_storedCredentials = null;
				}
			}
			catch
			{
				//let it fail
			}
        }