Beispiel #1
0
        public void TestArgon2RoundTrip()
        {
            var password = "******";

            byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
            byte[] salt          = new byte[16];
            Rng.GetBytes(salt);
            var config = new Argon2Config
            {
                Type       = Argon2Type.DataIndependentAddressing,
                Version    = Argon2Version.Nineteen,
                Password   = passwordBytes,
                Salt       = salt,
                TimeCost   = 3,
                MemoryCost = 65536,
                Lanes      = 4,
                Threads    = 2,
            };
            var argon2 = new Argon2(config);
            SecureArray <byte> hash = argon2.Hash();
            var passwordHash        = config.EncodeString(hash.Buffer);

            this.output.WriteLine($"Argon2 of {password} --> {passwordHash}");
            Assert.True(
                Argon2.Verify(passwordHash, passwordBytes, SecureArray.DefaultCall),
                $"expected verify to work for {passwordHash} (Argon2 hash of {password}");
        }
Beispiel #2
0
        /// <summary>
        /// Test <see cref="Argon2"/>.
        /// </summary>
        /// <returns>
        /// Result text.
        /// </returns>
        public static string TestArgon2RoundTrip2()
        {
            var password      = "******";
            var secret        = "secret1";
            var passedResults = new List <string>();
            var failedResults = new List <string>();

            foreach (var argon2Type in new[]
                     { Argon2Type.DataIndependentAddressing, Argon2Type.DataDependentAddressing, Argon2Type.HybridAddressing })
            {
                var argon2Name = argon2Type == Argon2Type.DataIndependentAddressing ? "Argon2i" :
                                 argon2Type == Argon2Type.DataDependentAddressing ? "Argon2d" : "Argon2id";

                var passwordHash = Argon2.Hash(password, secret, type: argon2Type);
                Console.WriteLine($"{argon2Name} of {password} --> {passwordHash}");

                if (Argon2.Verify(passwordHash, password, secret))
                {
                    passedResults.Add(argon2Name);
                    Console.WriteLine($"RoundTrip2 {argon2Name} Passed");
                }
                else
                {
                    failedResults.Add(argon2Name);
                    Console.WriteLine($"RoundTrip2 {argon2Name} FAILED");
                    Console.WriteLine($"    expected verify to work for {passwordHash} ({argon2Name} hash of {password})");
                }
            }

            return(failedResults.Any() ? $"RoundTrip2 FAILED: [{string.Join(", ", failedResults)}] (passed: [{string.Join(", ", passedResults)}])"
                : "RoundTrip2 Passed");
        }
Beispiel #3
0
        public (bool isSuccess, string msg, UserEntity user) Login(UserEntity user)
        {
            var dbUser = context.Users.Find(user.Id);

            if (dbUser == null)
            {
                return(false, "לא קיים משתמש ברשות שנבחרה", null);
            }
            if (!dbUser.UserIsActive)
            {
                return(false, "היוזר אינו פעיל", null);
            }
            if (dbUser.UserIsActive)
            {
                var password = Encoding.UTF8.GetString(Convert.FromBase64String(user.Password));
                var verified = Argon2.Verify(dbUser.UserPassword, password);
                return(verified, verified ? "ההתחברות בוצעה בהצלחה" : "פרטי המשתמש אינם תקינים", new UserEntity
                {
                    Id = dbUser.UserId,
                    FirstName = dbUser.UserFirstName,
                    Email = dbUser.UserEmail,
                    LastName = dbUser.UserLastName,
                    IsActive = true,
                    IsSuperAdmin = dbUser.UserIsSuperAdmin,
                    CustomerId = dbUser.CustomerId
                });
            }
            return(false, "היוזר אינו פעיל", null);
        }
        /// <inheritdoc />
        public bool ValidatePassword(string password, string passwordHash)
        {
            password.ThrowIfNull(nameof(password));
            passwordHash.ThrowIfNull(nameof(passwordHash));

            return(Argon2.Verify(passwordHash, password));
        }
        public bool Verify(string username, string password)
        {
            string       usernamePassword = $"{username}:{password}";
            Argon2Config config           = GetArgon2Config(usernamePassword);
            bool         verified         = Argon2.Verify(Configuration.AuthToken, config);

            return(verified);
        }
Beispiel #6
0
        private UserModel AuthenticateUser(UserModel loginCredentials)
        {
            var user = _repository.GetAllUsersOnlyWithRoles()
                       .SingleOrDefault(x => x.Login == loginCredentials.Login &&
                                        Argon2.Verify(x.Password, loginCredentials.Password));

            return(user);
        }
Beispiel #7
0
        public bool VerifyPassword(string password)
        {
            if (Argon2.Verify(Password, password))
            {
                return(true);
            }

            return(false);
        }
Beispiel #8
0
        public bool VerifyPassword(string password, string hash)
        {
            if (string.IsNullOrEmpty(password) || string.IsNullOrEmpty(hash))
            {
                throw new ArgumentNullException(password ?? hash);
            }

            return(Argon2.Verify(hash, Encoding.UTF8.GetBytes(password)));
        }
Beispiel #9
0
        /// <summary>
        /// Verify if the password is a hash.
        /// </summary>
        /// <param name="password">The password to be verified.</param>
        /// <param name="hash">The hash against wich vto verify.</param>
        /// <returns>True if the password is valid.</returns>
        public static bool VerifyPassword(string password, string hash)
        {
            if (password == null || hash == null)
            {
                return(false);
            }

            return(Argon2.Verify(hash, password));
        }
Beispiel #10
0
        public void TestArgon2RoundTrip2()
        {
            var password     = "******";
            var passwordHash = Argon2.Hash(password);

            this.output.WriteLine($"Argon2 of {password} --> {passwordHash}");
            Assert.True(
                Argon2.Verify(passwordHash, password, SecureArray.DefaultCall),
                $"expected verify to work for {passwordHash} (Argon2 hash of {password}");
        }
Beispiel #11
0
 /// <summary> Creates an Argon2 <see cref="VerifyFn"/></summary>
 /// <param name="secret"> Optional secret to use </param>
 /// <param name="threads"> Threads to use </param>
 /// <returns></returns>
 public static VerifyFn Argon2Verify(int threads = 8, string secret = null)
 {
     return((hash, pass) => {
         DateTime start = DateTime.UtcNow;
         var result = Argon2.Verify(hash, pass, threads);
         DateTime end = DateTime.UtcNow;
         Log.Debug($"Argon2.Verify({threads}) completed in {(end - start).TotalMilliseconds}ms");
         return result;
     });
 }
Beispiel #12
0
        private bool CheckPasswordCorectness(string password, string hashPasswordFromDb)
        {
            var passwordBytes = Encoding.UTF8.GetBytes(password);

            if (Argon2.Verify(hashPasswordFromDb, passwordBytes))
            {
                return(true);
            }

            return(false);
        }
Beispiel #13
0
        // Returns true or false based on database entries, only true if a phone number and password match
        public bool LogIn(Account account)
        {
            bool login = false;

            using (WhatsUpDbContext db = new WhatsUpDbContext())
            {
                var acc = db.Accounts.SingleOrDefault(x => x.PhoneNumber == account.PhoneNumber);
                login = acc != null && Argon2.Verify(acc.Password, account.Password);
            }
            return(login);
        }
Beispiel #14
0
        public async Task <AuthResult> Authenticate(string login, string password)
        {
            var credentials = await _credentialsRepository.GetCredentialsAsync(login);

            var authSucceed = Argon2.Verify(credentials.Password, password);

            return(new AuthResult
            {
                Succeed = authSucceed,
                Credentials = authSucceed ? null : credentials
            });
        }
        public PasswordVerificationResult VerifyHashedPassword(
            AppUser user,
            string hashedPassword,
            string providedPassword)
        {
            if (Argon2.Verify(hashedPassword, providedPassword))
            {
                return(PasswordVerificationResult.Success);
            }

            return(PasswordVerificationResult.Failed);
        }
        public async Task InvokeAsync(HttpContext httpContext, Context dbContext)
        {
            if (httpContext.Request.Path == "/api/register")
            {
                await next.Invoke(httpContext);
            }
            else
            {
                string[] values = httpContext.Request.Headers["Authorization"]
                                  .ToString()
                                  .Split(' ');

                if (values[0] == "Basic")
                {
                    byte[] bytes = Convert.FromBase64String(values[1]);

                    string login_password = Encoding.UTF8.GetString(bytes);

                    int divider = login_password.IndexOf(':');

                    string login    = login_password.Substring(0, divider);
                    string password = login_password.Substring(divider + 1);

                    var user = await dbContext.User.FirstOrDefaultAsync(
                        u => u.Login == login);


                    if (user == null ||
                        !Argon2.Verify(user.Password, password))
                    {
                        httpContext.Response.StatusCode = 401;

                        /*await httpContext.Response
                         *  .WriteAsync("Uncorrect password or login");*/
                    }
                    else if (httpContext.Request.Path == "/api/login")
                    {
                        httpContext.Response.StatusCode = 200;
                        await httpContext.Response.WriteAsync("{" +
                                                              "\"status\" : \"ok\"}");
                    }
                    else
                    {
                        await next.Invoke(httpContext);
                    }
                }
                else
                {
                    await httpContext.Response.WriteAsync("Only basic auth is supported");
                }
            }
        }
Beispiel #17
0
        public async Task <bool> LoginAsync([DisallowNull] AuthData loginData)
        {
            var login   = loginData.Login;
            var courier = await Couriers.FirstOrDefaultAsync(l => l.Login == login);

            if (courier == null)
            {
                _logger.LogError($"Cannot find courier by login = {login}");
                return(false);
            }

            return(Argon2.Verify(courier.Password, loginData.Password));
        }
        public Account Login(AccountLogin account)
        {
            Account temp = _unitOfWork.Account.GetByEmail(account.Email);

            if (temp != null)
            {
                if (Argon2.Verify(temp.Password, account.Password))
                {
                    return(temp);
                }
            }

            return(null);
        }
Beispiel #19
0
        /// <summary>
        /// Test <see cref="Argon2"/>.
        /// </summary>
        /// <returns>
        /// The result text.
        /// </returns>
        public static string TestArgon2RoundTrip()
        {
            var password = "******";

            byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
            byte[] salt          = new byte[16];
            Rng.GetBytes(salt);
            var secret = "secret1";

            byte[] secretBytes   = Encoding.UTF8.GetBytes(secret);
            var    failedResults = new List <string>();
            var    passedResults = new List <string>();

            foreach (var argon2Type in new[] { Argon2Type.DataIndependentAddressing, Argon2Type.DataDependentAddressing, Argon2Type.HybridAddressing })
            {
                var argon2Name = argon2Type == Argon2Type.DataIndependentAddressing ? "Argon2i" :
                                 argon2Type == Argon2Type.DataDependentAddressing ? "Argon2d" : "Argon2id";
                var config = new Argon2Config
                {
                    Type       = argon2Type,
                    Version    = Argon2Version.Nineteen,
                    Password   = passwordBytes,
                    Salt       = salt,
                    Secret     = secretBytes,
                    TimeCost   = 3,
                    MemoryCost = 65536,
                    Lanes      = 4,
                    Threads    = 2,
                };
                var argon2 = new Argon2(config);
                SecureArray <byte> hash = argon2.Hash();
                var passwordHash        = config.EncodeString(hash.Buffer);
                Console.WriteLine($"{argon2Name} of {password} --> {passwordHash}");
                if (Argon2.Verify(passwordHash, passwordBytes, secretBytes, SecureArray.DefaultCall))
                {
                    passedResults.Add(argon2Name);
                    Console.WriteLine($"Round Trip {argon2Name} Passed");
                }
                else
                {
                    failedResults.Add(argon2Name);
                    Console.WriteLine($"Round Trip {argon2Name} FAILED");
                    Console.WriteLine($"    expected verify to work for {passwordHash} (Argon2 hash of {password})");
                }
            }

            return(failedResults.Any() ? $"RoundTrip FAILED: [{string.Join(", ", failedResults)}] (passed: [{string.Join(", ", passedResults)}])"
                : "RoundTrip Passed");
        }
Beispiel #20
0
        public async Task <IActionResult> Login(LoginModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            Person person = context.People.SingleOrDefault(usr => usr.Login == model.Username);

            if (person == null || !Argon2.Verify(person.PasswordHash, model.Password))
            {
                ModelState.AddModelError("Username", "Неверное имя пользователя или пароль");
                return(View(model));
            }
            await Authenticate(person.Login, person.Role);

            return(Redirect("/Home/Index"));
        }
        public IActionResult Login(AuthForm login)
        {
            _logger.LogInformation("Login initiated");
            IActionResult response = Unauthorized();

            var user = _userService.Get(login.UserName);

            if (user == null)
            {
                _logger.LogWarning("User {User} not found", login.UserName);
                return(response);
            }

            var argon2Config = new Argon2Config
            {
                Threads    = Environment.ProcessorCount,
                Password   = Encoding.UTF8.GetBytes(login.Password),
                Salt       = user.Salt,
                HashLength = 128
            };

            if (Argon2.Verify(user.Password, argon2Config))
            {
                _logger.LogInformation("User {User} logged in", login.UserName);
                var accessToken  = Auth.GenerateJWToken(_config, user.UserName);
                var refreshToken = Auth.GenerateRefreshToken(_config, user.UserName);

                user.AccessToken  = accessToken.Token;
                user.RefreshToken = refreshToken.Token;
                user.AccessExpiry = accessToken.Expiry;

                _userService.Update(user.Id, user);

                return(Ok(new
                {
                    accessToken = accessToken.Token,
                    refreshToken = refreshToken.Token
                }));
            }

            _logger.LogWarning("User {User} provided wrong password", login.UserName);
            return(response);
        }
Beispiel #22
0
        private ClaimsIdentity GetIdentity(string username, string password)
        {
            Person person = context.People.SingleOrDefault(x => x.Login == username);

            if (person != null && Argon2.Verify(person.PasswordHash, password))
            {
                var claims = new List <Claim>
                {
                    new Claim(ClaimsIdentity.DefaultNameClaimType, person.Login),
                    new Claim(ClaimsIdentity.DefaultRoleClaimType, Enum.GetName(person.Role))
                };
                ClaimsIdentity claimsIdentity =
                    new ClaimsIdentity(claims, "Token", ClaimsIdentity.DefaultNameClaimType,
                                       ClaimsIdentity.DefaultRoleClaimType);
                return(claimsIdentity);
            }

            // если пользователя не найдено
            return(null);
        }
Beispiel #23
0
        public async Task <AuthenticateResponse> Authenticate(AuthenticateRequest authenticate)
        {
            try
            {
                Admin admin = await applicationDb.Admins.FirstOrDefaultAsync(a => a.Email.Equals(authenticate.Email));

                if (admin is null)
                {
                    return(null);
                }
                if (!Argon2.Verify(admin.Password, authenticate.Password))
                {
                    return(null);
                }
                string token = GenerateJwtToken(admin);
                return(new AuthenticateResponse(admin, token));
            }catch (Exception e)
            {
                throw e;
            }
        }
Beispiel #24
0
        public dynamic Login(LoginRequest request)
        {
            //ISession session = _httpContextAccessor.HttpContext.Session;

            if (string.IsNullOrEmpty(request.username) || string.IsNullOrEmpty(request.password))
            {
                throw new Exception("Username or Password cannot be empty");
            }

            //search from db if any user with the given username exist or not
            Userdetail user = _dbContext.Userdetails.Where(x => x.Username == request.username).Include(x => x.Timezone).FirstOrDefault();

            if (user != null)
            {
                if (!Argon2.Verify(user.Userpassword, request.password))
                {
                    throw new Exception("The password is incorrect");
                }
                else
                {
                    AuthenticationResponse response = new AuthenticationResponse();
                    response.data    = CreateToken(user: user);
                    response.success = true;

                    //byte[] userId = Encoding.ASCII.GetBytes(user.Userdetailid.ToString());

                    //session.Set("UserdetailId",userId);

                    return(response);
                }
            }

            else
            {
                throw new Exception("This user does not exist");
            }
        }
 public override bool Verify(string plainSecret, string hashedSecret) =>
 Argon2.Verify(hashedSecret, plainSecret, _parallelism);
 public static bool VerifyPassword(string password, string salt, string hashPassword)
 {
     byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
     byte[] saltBytes     = Encoding.UTF8.GetBytes(salt);
     return(Argon2.Verify(hashPassword, passwordBytes, saltBytes));
 }
 private static bool CheckValidAuthorizedUser(string user, string password, string userHash)
 {
     return(Argon2.Verify(userHash, user + password));
 }
Beispiel #28
0
        public OutputSocketMessageWithUsers Execute(object val, string myLogin, Guid actId)
        {
            #region Тестовые данные

            /* {
             *      "execFun": "ChangeUserInfo",
             *      "data": {
             *          "name":"String",
             *                                  "photo":"String",
             *                                  "about":"String",
             *                                  "changePass":"******",
             *                                  "oldPass":"******",
             *                                  "newPass":"******"
             *      }
             *  }
             */
            #endregion

            OutputSocketMessage          output         = new OutputSocketMessage("changeUserInfo", actId, true, "", new { });
            OutputSocketMessage          outputForOther = new OutputSocketMessage("changeUserInfo", Guid.Empty, true, "", new { });
            OutputSocketMessageWithUsers rez            = new OutputSocketMessageWithUsers();

            DTO.ChangeUserInfo info = DeserializeObject.ParseJSON <DTO.ChangeUserInfo>(val, output, out rez);
            if (info == null)
            {
                return(rez);
            }

            using (var db = new RaidaContext())
            {
                Members owner = db.Members.Include(m => m.MemberInGroup).FirstOrDefault(it => it.login.Equals(myLogin));

                owner.nick_name            = info.Name;
                owner.photo_fragment       = info.Photo;
                owner.description_fragment = info.About;
                if (info.ChangePass)
                {
                    if (Argon2.Verify(owner.pass, info.OldPass, null))
                    {
                        if (info.NewPass.Trim().Length > 5)
                        {
                            owner.pass = Argon2.Hash(info.NewPass, 1, 512, 8);
                        }
                        else
                        {
                            output.success  = false;
                            output.msgError = "Minimum length of password is 6 chars";
                        }
                    }
                    else
                    {
                        output.success  = false;
                        output.msgError = "Current password is not valid";
                    }
                }

                db.SaveChanges();

                var user = new UserInfo(owner.login, owner.nick_name, owner.photo_fragment, owner.online);

                output.data = new
                {
                    itself = true,
                    user
                };

                outputForOther.data = new
                {
                    itself = false,
                    user
                };

                rez.forUserLogin = DeserializeObject.GetMyReferenceUser(db, owner);
            }

            rez.msgForOwner = output;
            rez.msgForOther = outputForOther;
            return(rez);
        }
Beispiel #29
0
 /// <summary>
 /// Validates the specified hash.
 /// </summary>
 /// <param name="hash">The hash.</param>
 /// <param name="text">The text.</param>
 /// <returns></returns>
 public static bool Validate(string hash, string text)
 {
     return(Argon2.Verify(hash, text));
 }
Beispiel #30
0
 public static bool VerifyPassword(string hash, string raw)
 {
     return(Argon2.Verify(hash, raw));
 }