Exemple #1
0
        public void DefaultPassword_Verfiy()
        {
            var hashProvider = new HashProvider();
            var hash         = hashProvider.Hash("P@55word");

            Assert.AreEqual(SystemAccountHelper.DefaultPassword, hash);
        }
Exemple #2
0
        protected void AddAliases(string name, int count)
        {
            List <long> aliasList;

            if (!AliasLookup.TryGetValue(name, out aliasList))
            {
                aliasList         = new List <long>(count);
                AliasLookup[name] = aliasList;
            }

            var total = aliasList.Count;

            lock (Lock)
                for (int i = total; i <= total + count; i++)
                {
                    try
                    {
                        var alias = HashProvider.Hash("{0}_{1}".AsFormat(name, i));
                        aliasList.Add(alias);
                        Map.Add(alias, name);
                    }
                    finally
                    {
                    }
                }
        }
Exemple #3
0
        public async Task RegisterUser(UserDto userDto)
        {
            userDto.Password = HashProvider.Hash(userDto.Password);
            var regUser = Mapper.Map <User>(userDto);
            await _uow.Repository <User>().Create(regUser);

            await _uow.Commit();
        }
 internal static Password Create(string plainText)
 {
     return(new Password()
     {
         // do not do this, this is just an example
         HashValue = HashProvider.Hash(plainText)
     });
 }
Exemple #5
0
        internal static LoginUser CreateObj(string pid, string pwd)
        {
            var user = new LoginUser();

            user.PID = pid;

            //加盐方式 str1=pid+pwd str2=pwd+pid
            string str1    = pid + pwd;
            string str2    = pwd + pid;
            var    hashobj = new HashProvider();
            string hstr1   = hashobj.Hash(str1);
            string hstr2   = hashobj.Hash(str2);

            user.PWD_hash = hstr1 + hstr2;

            return(user);
        }
Exemple #6
0
        private static void TestHMAC()
        {
            ILog log = LogManager.GetLogger("TestHMAC");

            HashProvider hash = new HashProvider();

            byte[] h1 = hash.Hash(
                new HashPrimitiveDataProvider((uint)0x3c),
                new HashPrimitiveDataProvider((ushort)0x00),
                new HashEnumDataProvider(testenum.test),
                new HashByteDataProvider(new byte[] { 0xb3, 0xd5, 0xcb, 0x12, 0x73,
                                                      0x8b, 0xb6, 0xf9, 0x21, 0xa3,
                                                      0xda, 0x42, 0xe0, 0x18, 0xd1,
                                                      0x43, 0xfa, 0x29, 0x7c, 0xa6 }));


            HMACProvider hmac = new HMACProvider(
                new byte[] { 0x75, 0xf0, 0x86, 0x84, 0x78,
                             0x24, 0xf8, 0x79, 0x39, 0x5a,
                             0x18, 0x14, 0x1d, 0x19, 0x0c,
                             0x2f, 0x01, 0x29, 0x0b, 0x05 });

            byte[] h2 = new byte[20];
            for (int i = 0; i < 20; i++)
            {
                h2[i] = 0xa5;
            }

            byte[] h3 = new byte[] {
                0xb9, 0x73, 0x05, 0xfa, 0xdb,
                0xe3, 0x4d, 0xc5, 0x46, 0x65,
                0x10, 0x00, 0x0a, 0x55, 0x04,
                0x2e, 0x3f, 0xea, 0xbf, 0x27
            };

            byte[] result = hmac.Hash(new HashByteDataProvider(h1),
                                      new HashByteDataProvider(h2),
                                      new HashByteDataProvider(h3),
                                      new HashPrimitiveDataProvider(true));

            byte[] expected = new byte[] {
                0x26, 0x7e, 0xca, 0x16, 0xa1,
                0x4d, 0x36, 0xe6, 0x72, 0x2e,
                0xaa, 0x7f, 0x7b, 0x53, 0x4a,
                0xb3, 0xce, 0x8b, 0x2a, 0xaa
            };

            for (int i = 0; i < 20; i++)
            {
                if (result[i] != expected[i])
                {
                    Console.WriteLine("FAILED");
                }
            }

            Console.WriteLine("SUCCESS");
        }
Exemple #7
0
 public void RegisterUser(UserDTO userDto)
 {
     try
     {
         userDto.Password = HashProvider.Hash(userDto.Password);
         var regUser = Mapper.Map <User>(userDto);
         _unitOfWork.Repository <User>().Create(regUser);
         _unitOfWork.Commit();
     }
     catch (Exception e)
     {
         Log.Error(e, "Exception thrown when trying to register new user", e);
     }
 }
Exemple #8
0
        public string CalculatePasswordHash(Membership membership, string password)
        {
            if (string.IsNullOrEmpty(password))
            {
                return(password);
            }

            var hashProvider = new HashProvider();
            var algorithm    = membership.GetHashAlgorithm();
            var encoding     = membership.GetEncoding();
            var passwordHash = hashProvider.Hash(password, algorithm, encoding);

            return(passwordHash);
        }
Exemple #9
0
        /// <summary>
        /// Retrieves the node value through key space collision by hashing
        /// TKey to some value and mapping that to the underlying virtual key space
        /// </summary>
        public TNode GetNode <TKey>(TKey key)
        {
            var    hashKey = HashProvider.Hash(key);
            string nodeKey = "";

            try
            {
                lock (Lock)
                    nodeKey = Map.GetNearest(hashKey);
            }
            finally
            {
            }
            return(Nodes[nodeKey]);
        }
        public Elastic3D DefineCoordinates(Address address)
        {
            if (Mul() <= 0)
            {
                throw new Exception("Invalid layout");
            }

            byte[] hash = HashProvider.Hash(address.Bytes);

            uint x = 1 + (BitConverter.ToUInt32(hash, 0) % X);
            uint y = 1 + (BitConverter.ToUInt32(hash, 2) % Y);
            uint z = 1 + (BitConverter.ToUInt32(hash, 4) % Z);

            return(new Elastic3D((byte)x, (byte)y, (byte)z));
        }
Exemple #11
0
        public void EditUser(UserDto userDto)
        {
            var user = _uow.Repository <User>().GetAll(u => u.Login == userDto.Login).FirstOrDefault();

            if (user != null)
            {
                user.FirstName = userDto.FirstName;
                user.LastName  = userDto.LastName;
                user.Password  = HashProvider.Hash(userDto.Password);
                user.Email     = userDto.Email;

                _uow.Repository <User>().UpdateAsync(user);
            }

            _uow.Commit();
        }
Exemple #12
0
        public void EditUser(UserDTO userDto)
        {
            try
            {
                var user = _unitOfWork.Repository <User>().Find(u => u.Login == userDto.Login).FirstOrDefault();

                user.FirstName = userDto.FirstName;
                user.LastName  = userDto.LastName;
                user.Password  = HashProvider.Hash(userDto.Password);
                user.Email     = userDto.Email;

                _unitOfWork.Repository <User>().Update(user);
                _unitOfWork.Commit();
            }
            catch (Exception e)
            {
                Log.Error(e, "Exception thrown when trying to edit user", e);
            }
        }
Exemple #13
0
        /// <summary>
        /// Registers a new user.  The PasswordHash property should be the actual password.
        /// </summary>
        /// <param name="user">A user with a raw password which is turned into a password hash as part of registration.</param>
        /// <param name="duration">The amount of time that the initial session will be valid.</param>
        /// <param name="ipAddress">The internet address where the user is connecting from.</param>
        /// <param name="result">A ExecutionResults instance to add applicable
        /// warning and error messages to.</param>
        /// <returns>A boolean indicating success (true) or failure (false).</returns>
        public override UserIdentity RegisterUser(User user, UserSessionDurationType duration, String ipAddress, ExecutionResults result)
        {
            string password = user.PasswordHash;

            if (!ValidateName(user.Name, result) || !ValidatePassword(password, result))
            {
                return(new cs.UserIdentity());
            }

            var existing = GetUserByName(user.Name);

            if (existing != null)
            {   //seed user table with deleted users with names you don't want users to have
                result.AppendError("The name you specified cannot be used.");
                return(new cs.UserIdentity());
            }
            if (user.UserID.Equals(Guid.Empty))
            {
                user.UserID = Guid.NewGuid();
            }

            HashProvider hasher = HashManager.SelectProvider();
            var          salt   = new UserSalt
            {
                PasswordSalt = hasher.GetSalt(),
                UserID       = user.UserID,
                HashGroup    = new Random(DateTime.Now.Second).Next(HashGroupMinimum, HashGroupMaximum),
                HashName     = hasher.Name
            };

            user.PasswordHash = hasher.Hash(salt.PasswordSalt, password,
                                            salt.HashGroup + BaseHashIterations);
            using (var scope = new System.Transactions.TransactionScope())
            {
                //starts as a lightweight transaction
                SaveUser(user);
                //enlists in a full distributed transaction if users and salts have different connection strings
                SaveUserSalt(salt);
            }
            return(AuthenticateUser(name: user.Name, password: password, duration: duration,
                                    ipAddress: ipAddress, checkHistory: false, allowUpdateHash: false, result: result));
        }
Exemple #14
0
        private bool IsUserValid(User user, string password)
        {
            var hashedPassword = HashProvider.Hash(password);

            return(user?.Password == hashedPassword);
        }
Exemple #15
0
        /// <summary>
        /// updates a user's name and/or password.
        /// </summary>
        /// <param name="item">The user details to be saved.  If Password is empty is it not changed.  If specified it should be the new raw password (not a hash).</param>
        /// <param name="currentPassword">The current raw password for the user used to authenticate that the change can be made, or the current resetcode last sent to this user.</param>
        /// <param name="ipAddress">The internet address where the user is connecting from.</param>
        /// <param name="result">A ExecutionResults instance to add applicable
        /// warning and error messages to.</param>
        /// <returns>A boolean indicating success (true) or failure (false).</returns>
        public override bool UpdateUser(User item, String currentPassword, String ipAddress, ExecutionResults result)
        {
            if (item.UserID.Equals(Guid.Empty))
            {
                throw new ArgumentException("The user identity must be specified.");
            }
            var user = GetUserByID(item.UserID);
            var salt = GetUserSalt(item.UserID);

            if (user == null || salt == null)
            {
                result.AppendError("The specified user identity does not exist.");
                return(false);
            }
            if (salt.ResetCode == currentPassword)
            {
                if (salt.ResetCodeExpiration < DateTime.UtcNow)
                {
                    result.AppendError(
                        "Your password reset code has expired.  Request a new one to be sent to you, and then use it immediately.");
                    return(false);
                }
                salt.ResetCode           = null;
                salt.ResetCodeExpiration = DateTime.UtcNow;
            }
            else
            {
                var rememberMe = !cs.SecurityContextManager.IsAnonymous &&
                                 cs.SecurityContextManager.CurrentUser.Identity.Ticket.UserSession.ExpirationDate >
                                 DateTime.UtcNow.AddMinutes(PublicSessionDuration);
                if (!AuthenticateUser(name: item.Name, password: currentPassword, ipAddress: ipAddress,
                                      duration: rememberMe ? UserSessionDurationType.Extended : UserSessionDurationType.PublicComputer,
                                      allowUpdateHash: false, checkHistory: false, result: result).IsAuthenticated)
                {
                    result.AppendError("Cannot change password due to authentication error with current password.");
                    return(false);
                }
            }
            if (user.Name != item.Name)
            {   //user is changing their sign in name.  Make sure the new name is available.
                var nameExisting = GetUserByName(item.Name);
                if (nameExisting != null)
                {
                    result.AppendError("The name you specified cannot be used.");
                    return(false);
                }
                user.Name = item.Name;
            }
            if (!String.IsNullOrEmpty(item.PasswordHash))
            {
                var password = item.PasswordHash;
                //update hashes on regular basis, keeps the iterations in latest range for current users, and with a 'current' hash provider.
                HashProvider hasher = HashManager.SelectProvider();
                salt.PasswordSalt        = hasher.GetSalt();
                salt.HashGroup           = new Random(DateTime.Now.Second).Next(HashGroupMinimum, HashGroupMaximum);
                salt.HashName            = hasher.Name;
                user.PasswordHash        = hasher.Hash(salt.PasswordSalt, password, salt.HashGroup + BaseHashIterations);
                user.PasswordUpdatedDate = DateTime.UtcNow;
            }
            using (var scope = new System.Transactions.TransactionScope())
            {
                //starts as a lightweight transaction
                SaveUser(user);
                //enlists in a full distributed transaction if users and salts have different connection strings
                SaveUserSalt(salt);
            }
            return(true);
        }
Exemple #16
0
        private cs.UserIdentity AuthenticateUser(string name, string password,
                                                 UserSessionDurationType duration, string ipAddress, bool checkHistory,
                                                 bool allowUpdateHash, ExecutionResults result)
        {
            if (checkHistory)
            {
                var recentFailures = GetRecentFailedUserNameAuthenticationCount(name);
                if (recentFailures > AllowedFailuresPerPeriod)
                {
                    return(FailAuthenticateUser(name, ipAddress, result));
                }
            }
            User user = GetUserByName(name);

            if (user == null)
            {
                return(FailAuthenticateUser(name, ipAddress, result));
            }
            UserSalt salt = GetUserSalt(user.UserID);

            if (salt == null)
            {
                return(FailAuthenticateUser(name, ipAddress, result));
            }

            //this should get a named hashProvider used to originally hash the password...
            //  fallback to 'default' provider in legacy case when we didn't store the name.
            HashProvider hasher       = !string.IsNullOrEmpty(salt.HashName) ? HashManager.Providers[salt.HashName] : HashManager.DefaultProvider;
            var          passwordHash = hasher.Hash(salt.PasswordSalt, password, salt.HashGroup + BaseHashIterations);

            if (user.PasswordHash != passwordHash)
            {
                return(FailAuthenticateUser(name, ipAddress, result));
            }
            var session = new UserSession
            {
                CreatedDate    = DateTime.UtcNow,
                ExpirationDate = DateTime.UtcNow.AddMinutes(duration == UserSessionDurationType.PublicComputer ? PublicSessionDuration : ExtendedSessionDuration),
                UserID         = user.UserID,
                RenewalToken   = Guid.NewGuid()
            };
            var history = new AuthenticationHistory
            {
                IPAddress       = ipAddress,
                IsAuthenticated = true,
                UserName        = name,
                UserSession     = session
            };

            using (var scope = new System.Transactions.TransactionScope())
            {
                if (allowUpdateHash && (hasher.IsObsolete || user.PasswordHashUpdatedDate < DateTime.UtcNow.AddMonths(-1)))
                {
                    //update hashes on regular basis, keeps the iterations in latest range for current users, and with a 'current' hash provider.
                    hasher                       = HashManager.SelectProvider();
                    salt.PasswordSalt            = hasher.GetSalt();
                    salt.HashGroup               = new Random(DateTime.Now.Second).Next(HashGroupMinimum, HashGroupMaximum);
                    salt.HashName                = hasher.Name;
                    user.PasswordHash            = hasher.Hash(salt.PasswordSalt, password, salt.HashGroup + BaseHashIterations);
                    user.PasswordHashUpdatedDate = DateTime.UtcNow;
                    //starts as a lightweight transaction
                    SaveUser(user);
                    //enlists in a full distributed transaction if users and salts have different connection strings
                    SaveUserSalt(salt);
                }
                //either continues distributed transaction if applicable,
                //  or creates a new lightweight transaction for these two commands
                SaveUserSession(session);
                InsertUserHistory(history);
            }
            return(new cs.UserIdentity(history, this.Name));
        }