public void Pbkdf2PasswordHasherFailsToRoundTripWhenSaltsDontMatch() { var hashsize = 32; var saltsize = hashsize * 2; var generator = new CsprngSaltGenerator(); var salt1 = generator.Generate(saltsize); salt1.Length.ShouldEqual(saltsize); byte[] salt2; do { salt2 = generator.Generate(saltsize); } while (salt2.SequenceEqual(salt1)); var hasher = new Pbkdf2PasswordHasher(hashsize); var hashed = hasher.Hash(salt1, Password); hashed.Length.ShouldEqual(hashsize); hasher.Compare(salt2, Password, hashed).ShouldBeFalse(); }
private static async Task Main(string[] args) { var cs = "Data Source=localhost\\SQLExpress; Integrated Security=SSPI; Initial Catalog=PLAYGROUND;"; var usersRepository = new SQLServerUsersRepository(cs); var hasher = new Pbkdf2PasswordHasher(); var users = new Users(usersRepository, hasher); try { await users.CreateUser( username : "******", plainTextPassword : "******", firstName : "admin's name", lastName : "admin's surname", userType : UserTypes.Administrator); await users.CreateUser( username : "******", plainTextPassword : "******", firstName : "user's name", lastName : "user's surname", userType : UserTypes.SimpleUser); var loggedUser = users.Login("user", "wrongPassword"); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.WriteLine("done"); Console.Read(); }
public void TestPasswordHashers() { Startup.BooksApp.LogTestStart(); //run it only for MS SQL, to avoid slowing down console run for all servers if (Startup.ServerType != DbServerType.MsSql) { return; } IPasswordHasher hasher; var salt = Guid.NewGuid().ToByteArray(); var pwd = "MyPassword_*&^"; long start, timeMs; bool match; string hash; // You can use this test to approximate the 'difficulty' of hashing algorithm for your computer. // It prints the time it took to hash the pasword. This time should not be too low, desirably no less than 100 ms. hasher = new BCryptPasswordHasher(workFactor: 10); //each +1 doubles the effort; on my machine: 10 -> 125ms, 11->242ms start = Util.GetPreciseMilliseconds(); hash = hasher.HashPassword(pwd, salt); timeMs = Util.GetPreciseMilliseconds() - start; match = hasher.VerifyPassword(pwd, salt, hasher.WorkFactor, hash); Assert.IsTrue(match, "BCrypt hasher failed."); Debug.WriteLine("BCrypt hasher time, ms: " + timeMs); hasher = new Pbkdf2PasswordHasher(iterationCount: 2000); // on my machine: 2000-> 13ms, 5000->32ms start = Util.GetPreciseMilliseconds(); hash = hasher.HashPassword(pwd, salt); timeMs = Util.GetPreciseMilliseconds() - start; match = hasher.VerifyPassword(pwd, salt, hasher.WorkFactor, hash); Assert.IsTrue(match, "Pbkdf hasher failed."); Debug.WriteLine("Pbkdf hasher time, ms: " + timeMs); }
public void CheckHashTest() { Pbkdf2PasswordHasher hasher = new Pbkdf2PasswordHasher(); var result = hasher.VerifyHashedPassword("vGawPyJwb3h4gpYiyxptJdUS31lLLiVhJk2yzlsskx0=:doTdEmoK8ACsuIrLrp4riGYCqi6DEn4CyitpOqoVrFA=", "abcd123"); Assert.AreEqual(PasswordVerificationResult.Success, result); }
public void HashTest() { Pbkdf2PasswordHasher hasher = new Pbkdf2PasswordHasher(); string hash = hasher.HashPassword("abcd123"); Assert.AreEqual(89, hash.Length); }
public void Pbkdf2() { var hasher = new Pbkdf2PasswordHasher(); var hashedPassword = hasher.HashPassword(TestPassword, new SecureRandomGenerator()); Assert.IsNotNull(hashedPassword); var flag = hasher.VerifyHashedPassword(hashedPassword, TestPassword); Assert.IsTrue(flag); }
public async Task <UserDto> LogIn(CredentialsViewModel viewModel) { var user = _unitOfWork.Users.All(nameof(User.Entitlements), nameof(User.Memberships), nameof(User.Preferences)) .SingleOrDefault(u => u.Email == viewModel.Email) ?? throw new Exception(Constants.InvalidCredentialsExceptionMessage); var hasher = new Pbkdf2PasswordHasher(); if (hasher.VerifyHashedPassword(user, user.Password, viewModel.Password) == PasswordVerificationResult.Failed) { throw new Exception(Constants.InvalidCredentialsExceptionMessage); } return(await _userToUserDtoConverter.Convert(user)); }
public void Pbkdf2PasswordHasherFailsToRoundTripWhenPasswordsDontMatch() { var hashsize = 32; var saltsize = hashsize * 2; var salt = new CsprngSaltGenerator().Generate(saltsize); salt.Length.ShouldEqual(saltsize); var hasher = new Pbkdf2PasswordHasher(hashsize); var hashed = hasher.Hash(salt, Password); hashed.Length.ShouldEqual(hashsize); hasher.Compare(salt, "Goodbye, World!", hashed).ShouldBeFalse(); }
public void Pbkdf2PasswordHasherCanRoundTrip() { var hashsize = 32; var saltsize = hashsize * 2; var salt = new CsprngSaltGenerator().Generate(saltsize); salt.Length.ShouldEqual(saltsize); var hasher = new Pbkdf2PasswordHasher(hashsize); var hashed = hasher.Hash(salt, Password); hashed.Length.ShouldEqual(hashsize); hasher.Compare(salt, Password, hashed).ShouldBeTrue(); }
static async Task Main(string[] args) { IConfigurationRoot config = new ConfigurationBuilder() .AddEnvironmentVariables() .AddCommandLine(args) .Build(); step = 50; count = config.GetValue("Count", 1000); threadsCount = config.GetValue("ThreadsCount", 10); onlyIfDbEmpty = config.GetValue("OnlyIfDbIsEmpty", true); connectionString = config["ConnectionString"]; logger = CreateLogger(); hasher = new Pbkdf2PasswordHasher(new Pdkdf2PasswordHasherOptions()); if (!await IsGenerationNeeded()) { return; } var tasks = new List <Task>(); for (int i = 0; i < threadsCount; i++) { tasks.Add(Task.Factory.StartNew(GenerateImpl)); } Task.WaitAll(tasks.ToArray()); logger.LogInformation($"Total generated users: {generated}"); /*var admin = new User * { * Age = 20, * City = "Муха", * Email = "*****@*****.**", * GivenName = "Админ", * FamilyName = "Административный", * IsActive = true, * Password = hasher.HashPassword("123"), * Interests = "администрирование" * }; * await repo.AddUser(admin);*/ }
public async Task ResetPassword(CredentialsViewModel viewModel) { var user = _unitOfWork.Users.All().FirstOrDefault(u => u.Email == viewModel.Email); if (user == null) { throw new Exception(Constants.InvalidEmailExceptionMessage); } user.IsEnabled = true; var hasher = new Pbkdf2PasswordHasher(); user.Password = hasher.HashPassword(user, viewModel.Password); _unitOfWork.Users.Update(user); await _unitOfWork.SaveChangesAsync(); }
public async Task Register(UserViewModel viewModel) { var user = await _userViewModelToUserConverter.Convert(viewModel); if (_unitOfWork.Users.All().Any(u => u.Email == user.Email)) { throw new Exception(Constants.EmailAlreadyUsedExceptionMessage); } var hasher = new Pbkdf2PasswordHasher(); user.Salt = hasher.GenerateSalt(); user.Password = hasher.HashPassword(user, hasher.GeneratePassword()); user.IsEnabled = false; _unitOfWork.Users.Add(user); await _unitOfWork.SaveChangesAsync(); var content = System.IO.File.ReadAllText(System.IO.Path.Combine(_environment.ContentRootPath, Constants.WwwRoot, Constants.EmailTemplateFoldername, Constants.RegistrationEmailFilename)) .Replace("@NAME@", user.Name); await _emailService.Send(user.Email, Constants.RegistrationEmailSubject, content); }