예제 #1
0
        public static void OpenDbConnection(bool isEncrypted)
        {
            string password = string.Empty;

            if (isEncrypted)
            {
                string username;
                byte[] ciphertext;
                byte[] entropy;

                if (PasswordUtility.RetrievePasswordFromRegistry(out username, out ciphertext, out entropy))
                {
                    password = PasswordUtility.Decrypt(ciphertext, entropy);
                }
            }

            SqliteCon = new SQLiteConnection(DbConnectionString);

            if (isEncrypted)
            {
                SqliteCon.SetPassword(password);
            }

            SqliteCon.Open();
        }
예제 #2
0
        public void WrongPasswordThrowsException()
        {
            string testPassword  = "******";
            string wrongPassword = "******";

            Assert.ThrowsException <UnauthorizedAccessException>(() => { PasswordUtility.CompareStoredPassword(testPassword, PasswordUtility.EncryptyPassword(wrongPassword)); });
        }
예제 #3
0
        public async Task <IActionResult> ChangePassword(string password, string newPassword, string confirmPassword)
        {
            if (string.IsNullOrEmpty(password) ||
                string.IsNullOrEmpty(newPassword) ||
                newPassword.Length < 8 ||
                newPassword != confirmPassword)
            {
                ModelState.AddModelError("Message", "Invalid Password");
                return(View());
            }

            UserBasicData basicData = new UserBasicData();

            if (await basicData.FromDBAsync(UserId) == false)
            {
                ModelState.AddModelError("Message", "Invalid Session");
                return(View());
            }

            if (PasswordUtility.VerifyPassword(password, basicData.Password) == false)
            {
                ModelState.AddModelError("Message", "Invalid Password");
                return(View());
            }

            var query = new DBQuery_User_Update_Password();

            query.IN.UserId   = UserId;
            query.IN.Password = PasswordUtility.HashPassword(newPassword);

            await DBThread.Instance.ReqQueryAsync(query);

            return(RedirectToAction("Index", "Dashboard"));
        }
        private void btnConfirmTutor_Click(object sender, RoutedEventArgs e)
        {
            // General input handling
            Dictionary <String, String> inputValues = new Dictionary <string, string>();

            inputValues.Add("Social security number", tbxSsn.Text);
            inputValues.Add("First name", tbxFirstName.Text);
            inputValues.Add("Last Name", tbxLastName.Text);
            inputValues.Add("Email", tbxEmail.Text);
            inputValues.Add("Password", tbxRePassword.Password);

            String message;

            if (!InputHandler.IsFieldsFilledOut(out message, inputValues))
            {
                tvm.Status = message;
            }
            else if (!tbxPassword.Password.Equals(tbxRePassword.Password))
            {
                tvm.Status = "Passwords does not match!";
            }
            else
            {
                String hashedPassword = PasswordUtility.HashPassword(tbxPassword.Password);
                tvm.AddTutor(tbxSsn.Text, tbxFirstName.Text, tbxLastName.Text, tbxEmail.Text, hashedPassword);
                ((Panel)this.Parent).Children.Remove(this);
            }
        }
예제 #5
0
        public override void Execute()
        {
            this.Forum.CurrentQuestion = null;

            var    users    = this.Forum.Users;
            string username = this.Data[1];
            string password = this.Data[2];

            if (this.Forum.IsLogged)
            {
                this.Forum.Output.AppendLine(string.Format(Messages.AlreadyLoggedIn));
            }
            else
            {
                var foundUser = false;
                foreach (var user in users)
                {
                    if (user.Username == username &&
                        user.Password == PasswordUtility.Hash(password))
                    {
                        this.Forum.CurrentUser = user;
                        this.Forum.Output.AppendLine(string.Format(Messages.LoginSuccess, username));
                        foundUser = true;
                    }
                }

                if (!foundUser)
                {
                    throw new CommandException(Messages.InvalidLoginDetails);
                }
            }
        }
        public void SaltPasswordTest()
        {
            string salt     = PasswordUtility.GenerateSalt(32);
            string password = "******";

            Assert.That(PasswordUtility.SaltPassword(password, salt), Is.EqualTo(string.Concat(password, salt)));
        }
예제 #7
0
        public async Task <string> RegisterAsync(Account account)
        {
            string response = string.Empty;

            if (await _dbContext.Accounts.AnyAsync(a => a.Email == account.Email))
            {
                response = "Email is already in use";
            }
            else
            {
                if (await _dbContext.Accounts.AnyAsync(a => a.Username == account.Username))
                {
                    response = "Username is already in use";
                }
                else
                {
                    account.Created = DateTime.UtcNow;

                    byte[] salt = PasswordUtility.GenerateSalt();

                    account.PasswordSalt = salt;

                    account.PasswordHash = PasswordUtility.HashPassword(account.Password, account.PasswordSalt);

                    await _dbContext.Accounts.AddAsync(account);

                    await _dbContext.SaveChangesAsync();
                }
            }

            return(response);
        }
예제 #8
0
            }             // MatchesEnteredEmail

            public bool IsPasswordValid(string sPassword)
            {
                var pu = new PasswordUtility(CurrentValues.Instance.PasswordHashCycleCount);

                if (IsOldPasswordStyle)
                {
                    bool success =
                        (Password == HashPassword(sPassword, Email, CreationDate)) ||
                        (Password == HashPassword(sPassword));

                    if (success)
                    {
                        RenewStoredPassword = pu.Generate(Email, sPassword);
                    }

                    return(success);
                }                 // if

                var storedPassword = new HashedPassword(Email, CycleCount, EzPassword, Salt);

                PasswordValidationResult validateResult = pu.Validate(sPassword, storedPassword);

                RenewStoredPassword = validateResult.NewPassword;

                return(validateResult.Match);
            }             // IsPasswordValid
예제 #9
0
 public RemoteLabService(RemoteLabContext Db, IComputerManagement CompMgmt, SmtpEmail Smtp, PasswordUtility Pw)
 {
     this.Db       = Db;
     this.CompMgmt = CompMgmt;
     this.Smtp     = Smtp;
     this.Pw       = Pw;
 }
예제 #10
0
        private void ChangePassword(object parameter)
        {
            string currentPassword    = changePasswordWindow.CurrentPasswordTextBox.Password;
            string newPassword        = changePasswordWindow.NewPasswordTextBox.Password;
            string confirmNewPassword = changePasswordWindow.ConfirmNewPasswordTextBox.Password;

            if (!string.IsNullOrEmpty(currentPassword) && !string.IsNullOrEmpty(newPassword) && !string.IsNullOrEmpty(confirmNewPassword))
            {
                if (user != null)
                {
                    if (!PasswordUtility.CheckPassword(currentPassword, user.Password))
                    {
                        MessageBox.Show("Incorrect old password.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                        return;
                    }
                    if (newPassword != confirmNewPassword)
                    {
                        MessageBox.Show("Password and Confirm Password doesn't match!.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                        return;
                    }

                    //var newPasswordHash = PasswordUtility.GeneratePasswordHash(newPassword);
                    //user.Password = newPasswordHash;

                    dataAccessor.ChangePassword(user, currentPassword, newPassword);
                    MessageBox.Show("Password changed successfully!!", "Success", MessageBoxButton.OK, MessageBoxImage.Information);
                    ClearAllValues();
                    changePasswordWindow.Hide();
                }
            }
            else
            {
                MessageBox.Show("Fields cannot be empty!.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
예제 #11
0
        public void InsertUser()
        {
            var userRepo = new UsersRepo();

            const string user     = "";
            const string password = "";
            const string email    = "";

            var hash = PasswordUtility.HashPassword(password);

            var userObject = new User
            {
                UserName        = user,
                Email           = email,
                PasswordHash    = hash,
                IsTempPassword  = false,
                LockoutEnabled  = false,
                LockoutEndDate  = DateTime.MaxValue,
                AccessFailCount = 0,
                CreatedBy       = "",
                ModifiedBy      = "",
                CreatedDate     = DateTime.Now,
                ModifiedDate    = DateTime.Now
            };

            var result = userRepo.InsertUser(userObject);

            Assert.IsFalse(string.IsNullOrEmpty(result.UserId));
        }
예제 #12
0
        public override void Execute()
        {
            if (this.Forum.CurrentUser != null)
            {
                this.Forum.Output.AppendLine(
                    string.Format(Messages.AlreadyLoggedIn));
                return;
            }

            var    users    = this.Forum.Users.ToList();
            string username = this.Data[1];
            string password = PasswordUtility.Hash(this.Data[2]);
            var    user     = users.Single(u => u.Username == username);

            if (user == null || user.Password != password)
            {
                this.Forum.Output.AppendLine(
                    string.Format(Messages.InvalidLoginDetails));
                return;
            }

            this.Forum.CurrentUser = user;
            this.Forum.Output.AppendLine(
                string.Format(Messages.LoginSuccess, username));
        }
예제 #13
0
        public async Task <ActionResult <string> > Update(UserDataForUpdate userDataForUpdate, CancellationToken cancellationToken = default)
        {
            return(await _exceptionHandler.HandleExceptionAsync <ActionResult <string> >(async c =>
            {
                var nameIdentifierClaim = _user.Claims.SingleOrDefault(x => x.Type == ClaimTypes.NameIdentifier);
                var userId = Convert.ToInt32(nameIdentifierClaim.Value);
                if (userDataForUpdate.Id != userId)
                {
                    return BadRequest("User can update only his or her data and not anyone else's data");
                }
                var user = await _userQueryableDomainService.Get().FirstOrDefaultAsync(x => x.Id == userId);

                if (userDataForUpdate.Password.IsNotNullOrEmpty())
                {
                    byte[] passwordHash = null;
                    byte[] passwordSalt = null;
                    PasswordUtility.CreatePasswordHash(userDataForUpdate.Password, out passwordHash, out passwordSalt);
                    user.PasswordHash = passwordHash;
                    user.PasswordSalt = passwordSalt;
                }
                user.Name = userDataForUpdate.Name;
                user.Address = userDataForUpdate.Address;
                user.State = userDataForUpdate.State;
                user.Country = userDataForUpdate.Country;
                user.Email = userDataForUpdate.Email;
                user.PAN = userDataForUpdate.PAN;
                user.ContactNumber = userDataForUpdate.ContactNumber;

                await _userCommandDomainServiceAsync.UpdateAsync(user, c).ConfigureAwait(false);
                return Ok("User data updated successfully");
            }, cancellationToken));
        }
예제 #14
0
        public void ChangePassword(User user, string oldPassword, string newPassword)
        {
            if (PasswordUtility.CheckPassword(oldPassword, user.Password))
            {
                PasswordHash newPasswordHash = PasswordUtility.GeneratePasswordHash(newPassword);
                user.Password = newPasswordHash;

                using SqlConnection connection = new SqlConnection(connectionString);
                connection.Open();

                using SqlCommand command = connection.CreateCommand();

                command.CommandText =
                    "UPDATE dbo.Users "
                    + "set PasswordSalt= @PasswordSalt, PasswordHash=@PasswordHash, DateModified=@DateModified "
                    + "Where Id=@Id";

                user.DateCreated = (DateTime)(user.DateModified = DateTime.UtcNow);

                command.Parameters.Add("@Id", SqlDbType.Int).Value = user.Id;
                command.Parameters.Add("@PasswordSalt", SqlDbType.VarBinary).Value = user.Password.Salt;
                command.Parameters.Add("@PasswordHash", SqlDbType.VarBinary).Value = user.Password.Hash;
                command.Parameters.Add("@DateModified", SqlDbType.DateTime2).Value = user.DateModified;
                command.ExecuteScalar();
            }
        }
예제 #15
0
        public async Task <string> LoginWatchAsync(Account account)
        {
            string token = string.Empty;

            Account entity = await _dbContext.Accounts.SingleOrDefaultAsync(acc => acc.Username == account.Username);

            if (entity != null)
            {
                byte[] passHash = PasswordUtility.HashPassword(account.Password, entity.PasswordSalt);

                if (Enumerable.SequenceEqual(entity.PasswordHash, passHash))
                {
                    var secretKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.GetValue <string>("JwtSecretKey")));
                    var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);

                    var claims = new List <Claim>();
                    claims.Add(new Claim("uid", entity.AccountID.ToString()));

                    var tokenOptions = new JwtSecurityToken(
                        issuer: _config.GetValue <string>("ServerAdress"),
                        claims: claims,
                        expires: DateTime.Now.AddYears(1),
                        signingCredentials: signinCredentials
                        );

                    token = new JwtSecurityTokenHandler().WriteToken(tokenOptions);
                }
            }
            return(token);
        }
예제 #16
0
        }                                                 // Success

        public override void Execute()
        {
            Success = false;

            SafeReader sr = DB.GetFirst(
                "LoadUserDetails",
                CommandSpecies.StoredProcedure,
                new QueryParameter("@UserID", this.userID)
                );

            if (sr.IsEmpty)
            {
                Log.Alert("User not found by id {0}.", this.userID);
                return;
            }             // if

            var pu = new PasswordUtility(CurrentValues.Instance.PasswordHashCycleCount);

            HashedPassword hashed = pu.Generate(sr["Email"], Password.Data);

            var sp = new SpUserResetPassword(DB, Log)
            {
                UserID     = this.userID,
                EzPassword = hashed.Password,
                Salt       = hashed.Salt,
                CycleCount = hashed.CycleCount,
            };

            Success = 0 < sp.ExecuteScalar <int>();
        }         // Execute
예제 #17
0
        public override void Execute()
        {
            ICollection <IUser> users = this.Forum.Users;

            string username = this.Data[1];
            string password = PasswordUtility.Hash(this.Data[2]);

            if (this.Forum.IsLogged)
            {
                throw new CommandException(Messages.AlreadyLoggedIn);
            }

            IUser user = (User)users.First(u => u.Username == username && u.Password == password);

            if (user == null)
            {
                throw new CommandException(Messages.InvalidLoginDetails);
            }

            this.Forum.CurrentUser = user;

            StringBuilder loginResult = new StringBuilder();

            loginResult.AppendFormat(Messages.LoginSuccess, username);
            this.Forum.Output.AppendLine(loginResult.ToString());
        }
예제 #18
0
 public async Task <bool> UpdateUser(User user)
 {
     if (!string.IsNullOrEmpty(user.Password))
     {
         user.PasswordHash = PasswordUtility.EncryptPassword(user.Password, _appSettings.HashIterations);
     }
     return(await _userRepo.UpdateUser(user));
 }
예제 #19
0
 /// <summary>
 /// ساخت و قراردادن متغیر های کاربر در قالب مورد استفاده
 /// </summary>
 /// <param name="template">قالب</param>
 /// <param name="user">کاربر</param>
 /// <returns>قالب که با متغیر های مورد نظر پر شده است</returns>
 public static void Manipulate(ref string template, User user)
 {
     template = template.Replace(BaseInformationKey.UserVariable_FullName, GetSexText(user.SexId));
     template = template.Replace(BaseInformationKey.UserVariable_FullName, user.FullName);
     template = template.Replace(BaseInformationKey.UserVariable_Mobile, user.MobileNumber);
     template = template.Replace(BaseInformationKey.UserVariable_Email, user.Email);
     template = template.Replace(BaseInformationKey.UserVariable_Password, PasswordUtility.Decrypt(user.Password));
 }
예제 #20
0
        }         // Name

        public override void Execute()
        {
            bool emptyPassword =
                string.IsNullOrWhiteSpace(this.oldPassword) ||
                string.IsNullOrWhiteSpace(this.newPassword) ||
                string.IsNullOrWhiteSpace(this.newPasswordAgain);

            if (emptyPassword)
            {
                throw new StrategyWarning(this, "Password not specified for broker '" + this.spLoad.ContactEmail + "'.");
            }

            if (this.oldPassword == this.newPassword)
            {
                throw new StrategyWarning(
                          this,
                          "New and old passwords are the same for broker '" + this.spLoad.ContactEmail + "'."
                          );
            }             // if

            if (this.newPassword != this.newPasswordAgain)
            {
                throw new StrategyWarning(
                          this,
                          "New password and its confirmation are not the same for broker '" + this.spLoad.ContactEmail + "'."
                          );
            }             // if

            this.spLoad.ExecuteNonQuery();

            if (BrokerID < 1)
            {
                throw new StrategyWarning(this, "Failed to find broker by email '" + this.spLoad.ContactEmail + "'.");
            }

            var pu = new PasswordUtility(CurrentValues.Instance.PasswordHashCycleCount);

            var currentHashed = new HashedPassword(
                this.spLoad.ContactEmail,
                this.spLoad.CycleCount,
                this.spLoad.EzPassword,
                this.spLoad.Salt
                );

            if (!pu.Validate(this.oldPassword, currentHashed))
            {
                throw new StrategyWarning(
                          this,
                          "Current password does not match for broker by email '" + this.spLoad.ContactEmail + "'."
                          );
            }             // if

            var hashed = pu.Generate(this.spLoad.ContactEmail, this.newPassword);

            new SpBrokerUpdatePassword(BrokerID, hashed, DB, Log).ExecuteNonQuery();

            FireToBackground(new BrokerPasswordChanged(BrokerID, this.newPassword));
        }         // Execute
예제 #21
0
        public async Task <IActionResult> Join([FromBody] RequestUserJoinModel model)
        {
            // check format
            if (model.Username.IsValidUsername() == false)
            {
                return(Responsed(ErrorCode.InvalidUserName));
            }

            if (model.EMail.IsValidEmailAddress() == false)
            {
                return(Responsed(ErrorCode.InvalidEMail));
            }

            // check account
            AccountBasicData basicData = new AccountBasicData();

            if (await basicData.FromDBByUserNameAsync(model.Username))
            {
                return(Responsed(ErrorCode.ExistUserName));
            }

            if (await basicData.FromDBByEmailAsync(model.EMail))
            {
                return(Responsed(ErrorCode.ExistEMail));
            }

            // check verify code
            ErrorCode emailVerifyResult = CheckEMailVerifyCode(model.EMail, model.VerifyCode, false);

            if (emailVerifyResult != ErrorCode.Success)
            {
                return(Responsed(emailVerifyResult));
            }

            // insert database
            DBQuery_Account_Insert query = new DBQuery_Account_Insert();

            basicData = query.IN.BasicData;
            basicData.AccountDBKey = DBKeyGenerator.NewAccountDBKey;
            basicData.EMail        = model.EMail;
            basicData.CreateTime   = DateTime.UtcNow;
            basicData.Username     = model.Username;
            basicData.Password     = PasswordUtility.HashPassword(model.Password);

            if (await DBThread.Instance.ReqQueryAsync(query) == false)
            {
                return(Responsed(ErrorCode.DatabaseError));
            }

            // response
            ResponseUserJoinModel responseData = new ResponseUserJoinModel();

            responseData.EMail      = model.EMail;
            responseData.CreateTime = basicData.CreateTime;
            responseData.Username   = model.Username;

            return(Success(responseData));
        }
예제 #22
0
        public void ClearTextPasswordMatchesStoredWhenHashed()
        {
            string testPassword = "******";

            if (!PasswordUtility.CompareStoredPassword(testPassword, PasswordUtility.EncryptyPassword(testPassword)))
            {
                Assert.Fail();
            }
        }
예제 #23
0
        /// <summary>
        /// 取得 系統管理員 資訊
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public tblAdmin CheckUser(string Account, string Password)
        {
            LoginData data = new LoginData();

            Password = PasswordUtility.SHA512Encryptor(Password);
            tblAdmin admin = this.Get(x => x.PersonalID.Equals(Account) && x.Password.Equals(Password) && x.UseStatus == true);

            return(admin);
        }
예제 #24
0
        public void EncryptPassword()
        {
            var pw = "Testing12";

            var hash      = PasswordUtility.EncryptPassword(pw, 10000);
            var hashParts = hash.Split('.');

            Assert.Equal(3, hashParts.Length);
        }
        public async ValueTask <OperationResult <IIdentityTicket> > VerifyAsync(string key, Ticket data, string scenario, CancellationToken cancellation = default)
        {
            if (string.IsNullOrWhiteSpace(data.Identity))
            {
                if (string.IsNullOrEmpty(key))
                {
                    return(OperationResult.Fail(SecurityReasons.InvalidIdentity, "Missing identity."));
                }

                data.Identity = key;
            }

            //获取验证失败的解决器
            var attempter = this.Attempter;

            //确认验证失败是否超出限制数,如果超出则返回账号被禁用
            if (attempter != null && !attempter.Verify(data.Identity, data.Namespace))
            {
                return(OperationResult.Fail(SecurityReasons.AccountSuspended));
            }

            //获取当前用户的密码及密码盐
            var userId = this.GetPassword(data.Identity, data.Namespace, out var storedPassword, out var storedPasswordSalt, out var status, out _);

            //如果帐户不存在则返回无效账户
            if (userId == 0)
            {
                return(OperationResult.Fail(SecurityReasons.InvalidIdentity));
            }

            //如果账户状态异常则返回账户状态异常
            if (status != UserStatus.Active)
            {
                return(OperationResult.Fail(SecurityReasons.AccountDisabled));
            }

            //密码校验失败则返回密码验证失败
            if (!PasswordUtility.VerifyPassword(data.Password, storedPassword, storedPasswordSalt, "SHA1"))
            {
                //通知验证尝试失败
                if (attempter != null)
                {
                    attempter.Fail(data.Identity, data.Namespace);
                }

                return(OperationResult.Fail(SecurityReasons.InvalidPassword));
            }

            //通知验证尝试成功,即清空验证失败记录
            if (attempter != null)
            {
                attempter.Done(data.Identity, data.Namespace);
            }

            return(OperationResult.Success <IIdentityTicket>(new Ticket(data.Namespace, data.Identity)));
        }
예제 #26
0
        public void CheckPassword_KnownValues_Validates()
        {
            var pw   = "T3stP@ssw0rd";
            var hash = "10000.ZXhKk+k7lZ1xdHxnYO6TFA==.WPbmVg9TvVtjHub4l3e4Lb0N9PTRCSmOr81pTJOF72U=";
            //var hash = PasswordUtility.EncryptPassword(pw, 10000);

            var valid = PasswordUtility.CheckPassword(hash, pw);

            Assert.True(valid);
        }
예제 #27
0
            }                                                  // CycleCount

            private void SetPassword()
            {
                var pu = new PasswordUtility(CurrentValues.Instance.PasswordHashCycleCount);

                var pass = pu.Generate(ContactEmail, this.rawPassword);

                Password   = pass.Password;
                CycleCount = pass.CycleCount;
                Salt       = pass.Salt;
            }             // SetPassword
        public void VerifyPasswordTest()
        {
            string password     = "******";
            string salt         = PasswordUtility.GenerateSalt(password.Length);
            string hashPassword = PasswordUtility.HashPassword(PasswordUtility.SaltPassword(password, salt));

            Assert.That(PasswordUtility.VerifyPassword(hashPassword, password, salt), Is.True);

            Assert.That(PasswordUtility.VerifyPassword(hashPassword, "notmypassword", salt), Is.False);
        }
예제 #29
0
        //AES
        public ActionResult DemoAES()
        {
            AesCryptoServiceProvider aes = new AesCryptoServiceProvider();

            ViewBag.result1 = PasswordUtility.AESEncryptor("ASP.NET MVC 5", aes.Key, aes.IV);

            ViewBag.result2 = PasswordUtility.AESEncryptor(ViewBag.result1.ToString(), aes.Key, aes.IV);

            return(View());
        }
        public void HashPassword()
        {
            var originalPassword = "******";
            var hash             = PasswordUtility.HashPassword(originalPassword);

            Assert.IsTrue(PasswordUtility.VerifyHashedPassword(originalPassword, hash));

            var badHash = new StringBuilder(hash);

            badHash[8] = 'A';
            Assert.IsFalse(PasswordUtility.VerifyHashedPassword(originalPassword, badHash.ToString()));
        }
        public static IQueryable<Identity> FilterByEmailAndPassword(this IQueryable<Identity> query, string email, string password)
        {
            var passwordUtility = new PasswordUtility();

            // Get the hashed version of the password
            var hashedPassword = passwordUtility.HashPassword (password);

            var result =
                (from identity in query
                 where identity.Email == email
                 where identity.Password == hashedPassword
                 select identity);

            return result;
        }