/// <summary>
        /// Gets the hash code
        /// </summary>
        /// <returns>Hash code</returns>
        public override int GetHashCode()
        {
            unchecked // Overflow is fine, just wrap
            {
                var hashCode = 41;
                // Suitable nullity checks etc, of course :)
                if (Uuid != null)
                {
                    hashCode = hashCode * 59 + Uuid.GetHashCode();
                }
                if (Username != null)
                {
                    hashCode = hashCode * 59 + Username.GetHashCode();
                }
                if (Name != null)
                {
                    hashCode = hashCode * 59 + Name.GetHashCode();
                }
                if (Surname != null)
                {
                    hashCode = hashCode * 59 + Surname.GetHashCode();
                }
                if (Email != null)
                {
                    hashCode = hashCode * 59 + Email.GetHashCode();
                }
                if (PhoneNumber != null)
                {
                    hashCode = hashCode * 59 + PhoneNumber.GetHashCode();
                }
                if (Password != null)
                {
                    hashCode = hashCode * 59 + Password.GetHashCode();
                }
                if (HashedPassword != null)
                {
                    hashCode = hashCode * 59 + HashedPassword.GetHashCode();
                }

                hashCode = hashCode * 59 + IsDeleted.GetHashCode();
                if (DeletedTime != null)
                {
                    hashCode = hashCode * 59 + DeletedTime.GetHashCode();
                }
                if (Avatar != null)
                {
                    hashCode = hashCode * 59 + Avatar.GetHashCode();
                }
                if (LdapAuthenticationMode != null)
                {
                    hashCode = hashCode * 59 + LdapAuthenticationMode.GetHashCode();
                }
                if (Roles != null)
                {
                    hashCode = hashCode * 59 + Roles.GetHashCode();
                }
                return(hashCode);
            }
        }
 public CustomIdentityUser(string email, string username, string passwordHash, int age)
 {
     Email              = email;
     UserName           = username;
     PasswordHash       = passwordHash;
     PasswordHashEntity = new HashedPassword(PasswordHash);
     Age = age;
 }
Esempio n. 3
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
Esempio n. 4
0
File: User.cs Progetto: joaofx/Miru
        public void ChangePassword(PasswordEdit.Command request)
        {
            if (HashedPassword.NotEqual(Hash.Create(request.CurrentPassword)))
            {
                throw new DomainException("Current password does not match");
            }

            HashedPassword = Hash.Create(request.Password);
        }
Esempio n. 5
0
        public void UpdatePassword(User user, HashedPassword hashedPassword)
        {
            var conn = _mySqlProvider.GetMySqlConnection();

            conn.Query <dynamic>("update users set password = @Password where `uuid` = @Uuid",
                                 new { Password = hashedPassword.Value, Uuid = user.UserUuid.Value });

            DispatchEvents(user);
        }
Esempio n. 6
0
 public bool AreMatching(
     HashedPassword hashedPassword,
     UnhashedPassword unhashedPassword)
 {
     return(BCrypt.Net.BCrypt
            .Verify(
                unhashedPassword.Value,
                hashedPassword.Value));
 }
        public void WhenTextProvided_ThenSetProperties()
        {
            var sut = new HashedPassword(ClearText);

            Assert.That(sut.ClearPassword, Is.EqualTo(ClearText));
            Assert.That(sut.Hash, Is.EqualTo(Sha1Text));
            Assert.That(sut.HashPrefix, Is.EqualTo("8CB22"));
            Assert.That(sut.HashSuffix, Is.EqualTo("37D0679CA88DB6464EAC60DA96345513964"));
        }
Esempio n. 8
0
        public void MatchWith_ReturnsCorrectResult(bool areMatching)
        {
            HashedPassword hashedPassword = CreateHashedPassword();

            Assert.AreEqual(
                areMatching,
                hashedPassword.MatchWith(
                    new UnhashedPassword("password"),
                    CreateStubPasswordHashComparerReturning(areMatching)));
        }
Esempio n. 9
0
        public bool DoesPasswordMatch(string trialPassword)
        {
            if (Salt == string.Empty)
            {
                return(HashedPassword.Equals(trialPassword, StringComparison.InvariantCulture));
            }
            var hashedTrial = EncryptPassword(trialPassword);

            return(HashedPassword.Equals(hashedTrial, StringComparison.InvariantCulture));
        }
Esempio n. 10
0
        public void IsPasswordMatch_MatchingPasswords_Returns()
        {
            string expectedPassword = "******";

            PasswordHelper passwordManager = new PasswordHelper();

            HashedPassword actualHashedPassword = passwordManager.GeneratePasswordHash(expectedPassword);

            Assert.IsTrue(passwordManager.IsPasswordMatch(expectedPassword, actualHashedPassword));
        }
        // Consider password transformation (if available in plain text, we can import it).

        public static ImportResult Import(IDbConnection c, string inputFile, long idCreator)
        {
            var result = new ImportResult();

            // TODO:
            // - remove this, support upload.
            // - support the case of empty fields. So far, height and weight cannot be empty, check with other numbers as well.
            inputFile = @"C:\users\dsuar\Desktop\user sample data.csv";

            using (var r = File.OpenText(inputFile))
            {
                var csv = new CsvReader(r, new Configuration {
                    //HeaderValidated = (isValid, headerNames, headerNameIndex, context) => { },
                    HeaderValidated          = null,
                    MissingFieldFound        = null,
                    ReadingExceptionOccurred = (ex) =>
                    {
                        result.Errors.Add(new ImportError
                        {
                            Line       = ex.ReadingContext.RawRecord,
                            Error      = ex.Message,
                            LineNumber = ex.ReadingContext.RawRow,
                            Column     = ex.ReadingContext.CurrentIndex
                        });
                        result.NumRecordsWithError++;
                    }
                });

                var records = csv.GetRecords <Player>();

                var t = c.BeginTransaction();

                try
                {
                    foreach (var player in records)
                    {
                        var p = player.UserData.Password;

                        HashedPassword hashPass = (p != null) ? AuthTokenManager.HashPassword(p) : null;

                        // TODO: validate email / mobile doesn't exist already

                        PlayersController.InsertPlayer(c, t, player, player.UserData.Id, idCreator, true, hashPass, UserEventType.PlayerImported);
                    }

                    t.Commit();
                }
                catch
                {
                    t.Rollback();
                }
            }

            return(result);
        }
Esempio n. 12
0
        public void Handler_ThrowsArgumentNullException_WhenPasswordIsNull()
        {
            var userStore = new Mock<IUserStore<User, int>>(MockBehavior.Strict);
            var userManager = new UserManager<User, int>(userStore.Object);
            var handler = new HandleHashedPasswordQuery(userManager);
            var query = new HashedPassword(null);

            var exception = Assert.Throws<ArgumentNullException>(() => handler.Handle(query).Result);

            exception.ShouldNotBeNull();
        }
Esempio n. 13
0
        private User CrearUser(User usuarionuevo)
        {
            HashedPassword Password = HashHelper.Hash(usuarionuevo.Clave);
            User           user     = new User();

            user.Usuario = usuarionuevo.Usuario;
            user.Clave   = Password.Password;
            user.Sal     = Password.Salt;
            CapaLogica.CrearUsuario(user);
            return(user);
        }
Esempio n. 14
0
        public void Handler_ReturnsResult_FromUserManager_PasswordHasher(string password)
        {
            var userStore = new Mock<IUserStore<User, int>>(MockBehavior.Strict);
            var userManager = new UserManager<User, int>(userStore.Object);
            var handler = new HandleHashedPasswordQuery(userManager);
            var query = new HashedPassword(password);

            string result = handler.Handle(query).Result;

            result.ShouldNotBeNull();
        }
Esempio n. 15
0
        public void MaximumComplexityPasswordTest()
        {
            int    expected = 16777216;
            string password = "******";

            PasswordHashing provider = new PasswordHashing(complexity: 24);

            string         hash   = provider.Compute(password);
            HashedPassword hashed = (HashedPassword)hash;

            Assert.AreEqual(expected, hashed.Iterations);
        }
Esempio n. 16
0
        public async Task AccountService_CreateAccount_GeneratesPassword()
        {
            var repositoryMock = new EntityRepositoryMock();
            var sut            = new AccountService(repositoryMock, repositoryMock);

            await sut.CreateAccount("*****@*****.**", "testpassword");

            var account        = repositoryMock.GetEntities <Account>().Single();
            var hashedPassword = new HashedPassword(account.PasswordHash, account.PasswordSalt);

            Assert.IsTrue(hashedPassword.EqualsPlainPassword("testpassword"), "Password not set correctly.");
        }
Esempio n. 17
0
        public IActionResult CreateUserForm(User user)
        {
            HashProvider   hashProvider = new HashProvider();
            HashedPassword newPasscode  = hashProvider.HashPassword(user.Password);

            user.Salt     = newPasscode.Salt;
            user.Password = newPasscode.Password;

            userDAL.CreateUser(user);

            return(RedirectToAction("Index", "Home"));
        }
Esempio n. 18
0
 public SpBrokerUpdatePassword(
     int brokerID,
     HashedPassword password,
     AConnection oDB,
     ASafeLog oLog
     ) : base(oDB, oLog)
 {
     BrokerID    = brokerID;
     NewPassword = password.Password;
     Salt        = password.Salt;
     CycleCount  = password.CycleCount;
 }             // constructor
        public async Task <bool> PasswordEqualsHashAsync(string password, byte[] hash, byte[] salt)
        {
            HashedPassword hashedPassword = await EncryptAsync(
                Encoding.UTF8.GetBytes(password), salt);

            if (Enumerable.SequenceEqual(hash, hashedPassword.Hash))
            {
                return(true);
            }

            return(false);
        }
Esempio n. 20
0
        public void CustomLengths()
        {
            var hashLength = 100;
            var saltLength = 8;

            var hash = HashedPassword.New("foo", hashLength, saltLength);

            Assert.IsTrue(hash.Check("foo"));
            Assert.IsFalse(hash.Check("bar"));

            Assert.AreEqual(hashLength, hash.Hash.Length);
            Assert.AreEqual(saltLength, hash.Salt.Length);
        }
        public long GetCount(HashedPassword hashedPassword)
        {
            foreach (var line in RawContentLines)
            {
                if (line.StartsWith(hashedPassword.HashSuffix))
                {
                    var value = line.Substring(hashedPassword.HashSuffix.Length + 1);
                    return(Convert.ToInt64(value));
                }
            }

            return(0);
        }
Esempio n. 22
0
        public void IsPasswordMatch_UnmatchingPasswords_ReturnsFalse()
        {
            string expectedPassword = "******";

            PasswordHelper passwordManager = new PasswordHelper();

            HashedPassword actualHashedPassword = new HashedPassword();

            actualHashedPassword = passwordManager.GeneratePasswordHash(expectedPassword);

            expectedPassword = "******";
            Assert.IsFalse(passwordManager.IsPasswordMatch(expectedPassword, actualHashedPassword));
        }
Esempio n. 23
0
        /// <summary>
        /// Changes the password of the specified account.
        /// </summary>
        /// <param name="email">E-Mail Address of the account of which to change the password.</param>
        /// <param name="newPassword">Password that should be used for the account.</param>
        /// <returns>A Task that will complete when the password has been changed.</returns>
        public async Task ChangePassword(int accountId, string newPassword)
        {
            var account = await _entityQuerySource.GetById <Account>(accountId);

            var hashedPassword = HashedPassword.CreateFromPlainPassword(newPassword);

            await _entityRepositoryFactory.Use(repository =>
            {
                repository.Change <Account>(account.Id, a =>
                {
                    a.PasswordHash = hashedPassword.Hash;
                    a.PasswordSalt = hashedPassword.Salt;
                });
            });
        }
Esempio n. 24
0
        /// <summary>
        /// Checks a password for the specified account.
        /// </summary>
        /// <param name="email">E-Mail Address of the account to check the password for.</param>
        /// <param name="password">Password that should match the password of the account.</param>
        /// <returns>True, if the password matches the password of the account; otherwise false.</returns>
        public async Task <bool> CheckAccountPassword(string email, string password)
        {
            // A non-existing account for the email will be treated as a normal
            // failed password check to not disclose the information about the existence.
            var account = await GetAccountByEmail(email, suppressException : true);

            if (account == null)
            {
                return(false);
            }

            var hashedPassword = new HashedPassword(account.PasswordHash, account.PasswordSalt);

            return(hashedPassword.EqualsPlainPassword(password));
        }
Esempio n. 25
0
        public async ValueTask <bool> SignInAsync(RmanagerUser user, HttpContext httpContext, bool rememberMe = true, bool validPassword = true)
        {
            var u = await GetUserByEmailAsync(user.Email);

            if (u == null)
            {
                throw new _400Exception("Cannot find the Email!");
            }
            bool auth = true;

            if (validPassword)
            {
                var hash = u.PassWordHash.Substring(0, 32);
                var salt = u.PassWordHash.Substring(32);
                var h    = new HashedPassword(hash, salt);
                auth = h.Check(user.PassWordHash);
            }
            if (auth)
            {
                var authProperties = new AuthenticationProperties
                {
                    //there are many properties in class AuthenticationProperties
                    IsPersistent = rememberMe
                };

                //这一块是干嘛的??
                var claims = new List <Claim>()
                {
                    new Claim(ClaimTypes.Email, u.Email),
                    new Claim(ClaimTypes.Name, u.Id.ToString()),
                };
                for (int i = 0; i < u.Roles.Count; i++)
                {
                    claims.Add(new Claim(ClaimTypes.Role, u.Roles[i]));
                }
                var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                var c = new ClaimsPrincipal();

                await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                                              new ClaimsPrincipal(claimsIdentity), authProperties);

                return(true);
            }
            else
            {
                throw new _401Exception("Password and email do not match!");
            }
        }
Esempio n. 26
0
        public async ValueTask <bool> ChallengeAsync(string email, string password)
        {
            try
            {
                var pwdhash = await FindFirstAsync(u => u.Email == email, u => u.PassWordHash);

                var hash = pwdhash.Substring(0, 32);
                var salt = pwdhash.Substring(32);
                var h    = new HashedPassword(hash, salt);
                return(h.Check(password));
            }
            catch (Exception)
            {
                return(false);
            }
        }
Esempio n. 27
0
        public User Login(string userNameOrEmail, string password)
        {
            var user = _unitOfWork.Users.GetByUsernameOrEmail(userNameOrEmail);

            if (user == null)
            {
                return(new InvalidUser());
            }

            var passwordHelper = new PasswordHelper();
            var hashedPassword = new HashedPassword {
                PasswordHash = user.UserLogin.PasswordHash, Salt = user.UserLogin.Salt
            };

            return(passwordHelper.IsPasswordMatch(password, hashedPassword) ? user : new InvalidUser());
        }
Esempio n. 28
0
        public void Value_PasswordIsHashedUsingHashGenerator()
        {
            var stubHashGenerator = Substitute.For <IPasswordHashGenerator>();

            stubHashGenerator
            .Generate(Arg.Any <UnhashedPassword>())
            .Returns("HashedPassword");

            var hashedPassword = new HashedPassword(
                CreateStubUnhashedPassword(),
                stubHashGenerator);

            Assert.AreEqual(
                "HashedPassword",
                hashedPassword.Value);
        }
        /// <summary>
        /// Hashes the password and returns an object with the hashed password and salt.
        /// Both the hashed password and salt must be stored in order to verify it at a later stage.
        /// Reference: https://www.ktlsolutions.com/how-tos/effective-password-hashing/
        /// </summary>
        /// <param name="password">The password.</param>
        /// <returns></returns>
        public HashedPassword HashPassword(string password)
        {
            var hashedPassword = new HashedPassword();

            var saltBytes = new byte[64];
            var provider  = new RNGCryptoServiceProvider();

            provider.GetNonZeroBytes(saltBytes);
            hashedPassword.Salt = Convert.ToBase64String(saltBytes);

            var rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, saltBytes, 10000);

            hashedPassword.Password = Convert.ToBase64String(rfc2898DeriveBytes.GetBytes(256));

            return(hashedPassword);
        }
Esempio n. 30
0
        public void Compute_Verify_Pass()
        {
            var  buf = IDPasswordCredentials.PlainPasswordToSecureBuffer("qwerty");
            var  hash = Manager.ComputeHash(PasswordFamily.Text, buf);
            bool rehash, check;

            check = Manager.Verify(buf, hash, out rehash);
            Aver.IsTrue(check);

            buf   = IDPasswordCredentials.PlainPasswordToSecureBuffer("@8luE+5ky=");
            hash  = Manager.ComputeHash(PasswordFamily.Text, buf);
            check = Manager.Verify(buf, hash, out rehash);
            Aver.IsTrue(check);

            check = Manager.Verify(buf, HashedPassword.FromString(hash.ToJSON()), out rehash);
            Aver.IsTrue(check);
        }
        public void BytesLong(int cnt)
        {
            var a = new byte[cnt];
            var b = new byte[cnt];

            for (var i = 0; i < cnt; i++)
            {
                a[i] = (byte)i;
                b[i] = (byte)i;
            }

            Aver.IsTrue(HashedPassword.AreStringsEqualInLengthConstantTime(a, b));

            a = ((byte)1).ConcatArray(Ambient.Random.NextRandomBytes(cnt - 1));
            b = ((byte)2).ConcatArray(Ambient.Random.NextRandomBytes(cnt - 1));
            Aver.IsFalse(HashedPassword.AreStringsEqualInLengthConstantTime(a, b));
        }
        public void StringLong(int cnt)
        {
            var a = "";
            var b = "";

            for (var i = 0; i < cnt; i++)
            {
                a += i.ToString();
                b += i.ToString();
            }

            Aver.IsTrue(HashedPassword.AreStringsEqualInLengthConstantTime(a, b));

            a = "1" + Ambient.Random.NextRandomWebSafeString(cnt - 1);
            b = "2" + Ambient.Random.NextRandomWebSafeString(cnt - 1);
            Aver.IsFalse(HashedPassword.AreStringsEqualInLengthConstantTime(a, b));
        }
Esempio n. 33
0
 public void Query_Ctor_SetsPasswordProperty()
 {
     var password = FakeData.String();
     var query = new HashedPassword(password);
     query.Password.ShouldEqual(password);
 }
Esempio n. 34
0
 public bool Equals(Password password, HashedPassword hashedPassword)
 {
     string salt = hashedPassword.Salt;
     return string.Equals(Hash(password + salt), hashedPassword.ToString());
 }