コード例 #1
0
        public void ArgonHashStringModerateTest()
        {
            const string PASSWORD = "******";
            var          hash     = PasswordHash.ArgonHashString(PASSWORD, PasswordHash.StrengthArgon.Moderate);

            Assert.IsTrue(PasswordHash.ArgonHashStringVerify(hash, PASSWORD));
        }
コード例 #2
0
        public string HashPassword(TUser user, string password)
        {
            if (string.IsNullOrEmpty(password))
            {
                throw new ArgumentNullException(nameof(password), $"{nameof(password)} should not be null");
            }

            if (user == null)
            {
                throw new ArgumentNullException(nameof(user), $"{nameof(user)} should not be null");
            }

            if (_options.OpsLimit.HasValue && _options.MemLimit.HasValue)
            {
                return(PasswordHash.ArgonHashString(password, _options.OpsLimit.Value, _options.MemLimit.Value));
            }

            // Removing trailing 0x00. Some database providers doesnt support it.:
            // https://github.com/npgsql/efcore.pg/issues/1069
            return(_options.Strenght switch
            {
                PasswordHasherStrenght.Interactive => PasswordHash.ArgonHashString(password).Replace("\0", string.Empty),
                PasswordHasherStrenght.Moderate => PasswordHash.ArgonHashString(password, PasswordHash.StrengthArgon.Moderate).Replace("\0", string.Empty),
                PasswordHasherStrenght.Sensitive => PasswordHash.ArgonHashString(password, PasswordHash.StrengthArgon.Sensitive).Replace("\0", string.Empty),
                _ => throw new ArgumentOutOfRangeException()
            });
コード例 #3
0
        public bool Register(RegistrationModel registrationModel)
        {
            try
            {
                if (mSentryContext.Users.Any(p => p.Email == registrationModel.Email))
                {
                    return(false);
                }

                var passwordHash = PasswordHash.ArgonHashString(registrationModel.Password);

                var user = new User
                {
                    FirstName      = registrationModel.FirstName.Trim(),
                    MiddleName     = (registrationModel.MiddleName ?? string.Empty).Trim(),
                    LastName       = registrationModel.LastName.Trim(),
                    Email          = registrationModel.Email.Trim(),
                    PasswordHash   = passwordHash,
                    DateOfBirth    = registrationModel.DateOfBirth,
                    UserIdentifier = Guid.NewGuid()
                };

                mSentryContext.Users.Add(user);
                mSentryContext.SaveChanges();

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
コード例 #4
0
        public PasswordVerificationResult VerifyHashedPassword(TUser user, string hashedPassword, string providedPassword)
        {
            if (hashedPassword == null)
            {
                throw new ArgumentNullException(nameof(hashedPassword));
            }
            if (providedPassword == null)
            {
                throw new ArgumentNullException(nameof(providedPassword));
            }
            try
            {
                var previousHash = PreviousHasher.VerifyHashedPassword(user, hashedPassword, providedPassword);
                if (previousHash == PasswordVerificationResult.Success)
                {
                    user.Password = PasswordHash.ArgonHashString(providedPassword, HasherOptions.Strength);
                    return(PasswordVerificationResult.SuccessRehashNeeded);
                }
            }
            catch (FormatException)
            {
            }

            var currentHashSuccess = PasswordHash.ArgonHashStringVerify(hashedPassword, providedPassword);

            return(currentHashSuccess ? PasswordVerificationResult.Success : PasswordVerificationResult.Failed);
        }
コード例 #5
0
        public string HashPassword(TUser user, string password)
        {
            if (string.IsNullOrEmpty(password))
            {
                throw new ArgumentNullException(nameof(password), $"{nameof(password)} should not be null");
            }
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user), $"{nameof(user)} should not be null");
            }

            if (_options.OpsLimit.HasValue && _options.MemLimit.HasValue)
            {
                return(PasswordHash.ArgonHashString(password, _options.OpsLimit.Value, _options.MemLimit.Value));
            }

            switch (_options.Strenght)
            {
            case PasswordHasherStrenght.Interactive:
                return(PasswordHash.ArgonHashString(password));

            case PasswordHasherStrenght.Moderate:
                return(PasswordHash.ArgonHashString(password, PasswordHash.StrengthArgon.Moderate));

            case PasswordHasherStrenght.Sensitive:
                return(PasswordHash.ArgonHashString(password, PasswordHash.StrengthArgon.Sensitive));

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
コード例 #6
0
 public string HashPassword(TUser user, string password)
 {
     if (password == null)
     {
         throw new ArgumentNullException(nameof(password));
     }
     return(PasswordHash.ArgonHashString(password, HasherOptions.Strength));
 }
コード例 #7
0
        private void CpuIntensive(int quantity)
        {
            var faker = new Faker();

            for (int i = 0; i < quantity; i++)
            {
                PasswordHash.ArgonHashString(faker.Internet.Password(), PasswordHash.StrengthArgon.Sensitive);
            }
        }
        public void VerifyHashedPassword_WhenSuppliedPasswordDoesNotMatch_ExpectFailure()
        {
            var password       = Guid.NewGuid().ToString();
            var hashedPassword = PasswordHash.ArgonHashString(Guid.NewGuid().ToString());

            var hasher = new Argon2PasswordHasher <string>();

            hasher.VerifyHashedPassword("", hashedPassword, password).Should().Be(PasswordVerificationResult.Failed);
        }
        public void VerifyHashedPassword_WithCustomStrength_ExpectSuccess()
        {
            var password       = Guid.NewGuid().ToString();
            var hashedPassword = PasswordHash.ArgonHashString(password, PasswordHash.StrengthArgon.Sensitive);

            var hasher = new Argon2PasswordHasher <string>();

            hasher.VerifyHashedPassword("", hashedPassword, password).Should().Be(PasswordVerificationResult.Success);
        }
        public void VerifyHashedPassword_WithDefaultSettings_ExpectSuccess()
        {
            var password       = Guid.NewGuid().ToString();
            var hashedPassword = PasswordHash.ArgonHashString(password);

            var hasher = new Argon2PasswordHasher <string>();

            hasher.VerifyHashedPassword("", hashedPassword, password).Should().Be(PasswordVerificationResult.Success);
        }
コード例 #11
0
        public virtual string HashPassword(TUser user, string password)
        {
            if (password == null)
            {
                throw new ArgumentNullException(nameof(password));
            }

            return(PasswordHash.ArgonHashString(password, ParseStrength()));
        }
コード例 #12
0
        private static void CalcArgon2(string source, int total)
        {
            var sw   = Stopwatch.StartNew();
            var hash = PasswordHash.ArgonHashString(source, PasswordHash.StrengthArgon.Sensitive);

            Console.WriteLine($"The Argon2 hash of {source} is: {hash}.");
            Parallel.For(0, total, (i) => { PasswordHash.ArgonHashString(source, PasswordHash.StrengthArgon.Sensitive); });
            Console.WriteLine($"{total} Interaction: {sw.ElapsedMilliseconds}");
            sw.Stop();
        }
コード例 #13
0
        public void ArgonHashStringTest()
        {
            const string PASSWORD = "******";
            //See: https://download.libsodium.org/doc/password_hashing/the_argon2i_function.html
            // (MEM_LIMIT: It is recommended to allow the function to use at least 32 megabytes.)
            const long OPS_LIMIT = 4;
            const int  MEM_LIMIT = 33554432;

            var hash = PasswordHash.ArgonHashString(PASSWORD, OPS_LIMIT, MEM_LIMIT);

            Assert.IsTrue(PasswordHash.ArgonHashStringVerify(hash, PASSWORD));
        }
コード例 #14
0
        public void Argon2PasswordNeedsRehashOnStringTest()
        {
            string password = "******";

            string argonHash = PasswordHash.ArgonHashString(password, 4, 134_217_728);

            Assert.IsTrue(PasswordHash.ArgonPasswordNeedsRehash(argonHash, 4, 107_374_182_4));

            Assert.IsFalse(PasswordHash.ArgonPasswordNeedsRehash(argonHash, 4, 134_217_728));

            Assert.IsTrue(PasswordHash.ArgonPasswordNeedsRehash(argonHash, PasswordHash.StrengthArgon.Sensitive));
        }
コード例 #15
0
ファイル: Cryptography.cs プロジェクト: georgehara/Cypher
        public static byte[] ArgonHashString(SecureString password)
        {
            Guard.Argument(password, nameof(password)).NotNull();

            byte[] hash;

            using (var insecurePassword = password.Insecure())
            {
                hash = PasswordHash.ArgonHashString(insecurePassword.Value, 4, 64000000).FromHex();
            }

            return(hash);
        }
コード例 #16
0
        /// <summary>
        /// Argon2 Hash password.
        /// </summary>
        /// <returns>The pwd.</returns>
        /// <param name="pwd">Pwd.</param>
        public static byte[] HashPwd(string pwd)
        {
            if (string.IsNullOrEmpty(pwd))
            {
                throw new ArgumentException("Password cannot be null or empty!", nameof(pwd));
            }

            const long OPS_LIMIT = 4;
            const int  MEM_LIMIT = 33554432;

            var hash = PasswordHash.ArgonHashString(pwd, OPS_LIMIT, MEM_LIMIT);

            return(Encoding.UTF8.GetBytes(hash));
        }
コード例 #17
0
        /// <summary>
        /// Argons hash password.
        /// </summary>
        /// <returns>The hash password.</returns>
        /// <param name="password">Password.</param>
        public static byte[] ArgonHashPassword(SecureString password)
        {
            Guard.Argument(password, nameof(password)).NotNull();

            const long OPS_LIMIT = 4;
            const int  MEM_LIMIT = 33554432;
            string     hash;

            using (var insecurePassword = password.Insecure())
            {
                hash = PasswordHash.ArgonHashString(insecurePassword.Value, OPS_LIMIT, MEM_LIMIT);
            }

            return(Encoding.UTF8.GetBytes(hash));
        }
コード例 #18
0
        public void ArgonHashStringSensitiveTest()
        {
            const string PASSWORD = "******";

            try
            {
                //Could cause OutOfMemoryException
                var hash = PasswordHash.ArgonHashString(PASSWORD, PasswordHash.StrengthArgon.Sensitive);

                Assert.IsTrue(PasswordHash.ArgonHashStringVerify(hash, PASSWORD));
            }
            catch (OutOfMemoryException e)
            {
                Assert.Inconclusive(e.ToString());
            }
        }
コード例 #19
0
    /// <summary>
    /// Hash a password using argon2id - returns hash containing the salt (of length 128 bytes)
    /// </summary>
    /// <param name="this">Password to hash</param>
    public static string HashPassword(this string @this)
    {
        // Return empty string
        if (string.IsNullOrWhiteSpace(@this))
        {
            return(string.Empty);
        }

        // Hash string and then remove null characters
        var hash = PasswordHash
                   .ArgonHashString(@this, PasswordHash.StrengthArgon.Moderate)
                   .Where(c => c != char.MinValue)
                   .ToArray();

        // Return as a string
        return(new(hash));
    }
コード例 #20
0
        public async Task <ActionResult <User> > CreateUser(string email, string username, string password)
        {
            var exists = await _userRepository.CheckIfExists(email, username);

            if (exists)
            {
                return(new ActionResult <User>(false, ("", "Email or username already exists.")));
            }

            var dbModel = new User
            {
                Email        = email,
                Username     = username,
                PasswordHash = PasswordHash.ArgonHashString(password)
            };

            return(new ActionResult <User>(true, await _userRepository.Create(dbModel)));
        }
コード例 #21
0
ファイル: Cryptography.cs プロジェクト: KrakenOverlord/Cypher
        /// <summary>
        /// Argons hash password.
        /// </summary>
        /// <returns>The hash password.</returns>
        /// <param name="password">Password.</param>
        public static byte[] ArgonHashPassword(SecureString password)
        {
            if (password == null)
            {
                throw new ArgumentNullException(nameof(password));
            }

            const long OPS_LIMIT = 4;
            const int  MEM_LIMIT = 33554432;
            string     hash;

            using (var insecurePassword = password.Insecure())
            {
                hash = PasswordHash.ArgonHashString(insecurePassword.Value, OPS_LIMIT, MEM_LIMIT);
            }

            return(Encoding.UTF8.GetBytes(hash));
        }
コード例 #22
0
        public BaseApiResponse RegisterAccount(AccountRegisterRequest accountRequest)
        {
            var validUsername = ValidUsername(accountRequest.Username);

            if (!validUsername)
            {
                return(new BaseApiResponse(HttpStatusCode.BadRequest, "Please enter a valid username."));
            }

            //check if username exists
            var usernameExists = UsernameTaken(accountRequest.Username);

            if (usernameExists)
            {
                return(new BaseApiResponse(HttpStatusCode.BadRequest, $"Username {accountRequest.Username} is already taken."));
            }

            var validPassword = ValidPassword(accountRequest.Password);

            if (!validPassword)
            {
                return(new BaseApiResponse(HttpStatusCode.BadRequest, "Please enter a valid password"));
            }

            var passwordSaltBytes = PasswordHash.ArgonGenerateSalt();
            var passwordSalt      = System.Text.Encoding.ASCII.GetString(passwordSaltBytes);

            var saltedPassword = accountRequest.Password + passwordSalt;

            var passwordHash = PasswordHash.ArgonHashString(saltedPassword, PasswordHash.StrengthArgon.Interactive);

            var newAccount = new PUAccountRecord
            {
                Username     = accountRequest.Username,
                PasswordSalt = passwordSalt,
                PasswordHash = passwordHash
            };

            m_AccountContext.Accounts.Add(newAccount);
            m_AccountContext.SaveChanges();

            return(new ApiOkResponse());
        }
コード例 #23
0
        public ActionResult ChangePassword(ChangePasswordViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var list = db.Accounts.Where(a => a.Login == User.Identity.Name).Take(1).ToList();

            if (list.Count != 0)
            {
                Account account = list[0];
                byte[]  empty   = null;
                byte[]  key     = null;
                using (FileStream fstream = new FileStream(@"C:\Users\Valentine\source\repos\SecuritySystemLab1\SecuritySystemLab1\note.txt", FileMode.Open))
                {
                    key = new byte[fstream.Length];
                    fstream.Read(key, 0, key.Length);
                }

                var decrypted = SecretAead.Decrypt(list[0].Password, list[0].Nonce, key, null);

                if (PasswordHash.ArgonHashStringVerify(Encoding.UTF8.GetString(decrypted), Encoding.UTF8.GetString(GenericHash.Hash(model.OldPassword, empty, 32))))
                {
                    var nonce     = SecretAead.GenerateNonce();
                    var encrypted = SecretAead.Encrypt(Encoding.UTF8.GetBytes(
                                                           PasswordHash.ArgonHashString(Encoding.UTF8.GetString(GenericHash.Hash(model.NewPassword, empty, 32)),
                                                                                        PasswordHash.StrengthArgon.Interactive)), nonce, key, null);
                    account.Nonce           = nonce;
                    account.Password        = encrypted;
                    db.Entry(account).State = EntityState.Modified;
                    db.SaveChanges();

                    return(RedirectToAction("Main", new { Message = ManageMessageId.ChangePasswordSuccess }));
                }
            }
            else
            {
                ModelState.AddModelError("", "Произошла ошибка.");
                return(View(model));
            }
            return(View(model));
        }
コード例 #24
0
ファイル: LfPasswordHasher.cs プロジェクト: llldar/lonefire2
        public string HashPassword(ApplicationUser user, string password)
        {
            if (password == null)
            {
                throw new ArgumentNullException(nameof(password));
            }
            switch (options.HashFunction)
            {
            case LfHashFunction.Argon2:
                return(PasswordHash.ArgonHashString(password, options.Argon2Option.OpsLimit, options.Argon2Option.MemLimit).TrimEnd('\0'));

            case LfHashFunction.SCrypt:
                return(PasswordHash.ScryptHashString(password, options.SCryptOption.OpsLimit, options.SCryptOption.MemLimit).TrimEnd('\0'));

            case LfHashFunction.MD5:
                return(CalcMd5(password));

            default:
                throw new IndexOutOfRangeException();
            }
        }
コード例 #25
0
        public ActionResult Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                Account account = new Account();
                account.Login = model.Email;
                var list = db.Accounts.Where(a => a.Login == model.Email).Take(1).ToList();
                if (list.Count == 0)
                {
                    byte[] empty = null;
                    byte[] key   = null;
                    using (FileStream fstream = new FileStream(@"C:\Users\Valentine\source\repos\SecuritySystemLab1\SecuritySystemLab1\note.txt", FileMode.Open))
                    {
                        key = new byte[fstream.Length];
                        fstream.Read(key, 0, key.Length);
                    }

                    var nonce     = SecretAead.GenerateNonce();
                    var encrypted = SecretAead.Encrypt(Encoding.UTF8.GetBytes(
                                                           PasswordHash.ArgonHashString(Encoding.UTF8.GetString(GenericHash.Hash(model.Password, empty, 32)),
                                                                                        PasswordHash.StrengthArgon.Interactive)), nonce, key, null);
                    account.Nonce    = nonce;
                    account.Password = encrypted;
                    db.Accounts.Add(account);
                    db.SaveChanges();
                    Roles.AddUserToRole(model.Email, "User");
                    FormsAuthentication.SetAuthCookie(model.Email, false);
                    return(RedirectToAction("Index", "Home"));
                }
                else
                {
                    ModelState.AddModelError("", "Уже существует пользователь з данным логином.");
                    return(View(model));
                }
            }
            return(View(model));
        }
コード例 #26
0
ファイル: Crypto.cs プロジェクト: SupremeGenius/PIMUX
 // Function to run Argon2i.
 public static string ArgonHash(string masterPassword)
 {
     return(PasswordHash.ArgonHashString(masterPassword, PasswordHash.StrengthArgon.Moderate));
 }
コード例 #27
0
 public string HashPassword(string plaintext)
 {
     return(PasswordHash.ArgonHashString(plaintext, PasswordHash.StrengthArgon.Sensitive));
 }
コード例 #28
0
 public string HashPassword(string password)
 {
     return(PasswordHash.ArgonHashString(password, PasswordHash.StrengthArgon.Moderate));
 }
コード例 #29
0
 public override string HashPassword(TUser user, string password)
 {
     return(PasswordHash.ArgonHashString(password, _operationsLimit, _memoryLimit));
 }
コード例 #30
0
 /// <summary>Hashes a password using the Argon2 hashing scheme.</summary>
 /// <param name="password">Password to be hashed</param>
 /// <returns>Hashed password</returns>
 public static string HashPassword(string password) => PasswordHash.ArgonHashString(password);