コード例 #1
0
ファイル: LfPasswordHasher.cs プロジェクト: llldar/lonefire2
        public PasswordVerificationResult VerifyHashedPassword(string hashedPassword, string providedPassword)
        {
            if (hashedPassword == null)
            {
                throw new ArgumentNullException(nameof(hashedPassword));
            }
            if (providedPassword == null)
            {
                throw new ArgumentNullException(nameof(providedPassword));
            }
            bool isValid;

            switch (options.HashFunction)
            {
            case LfHashFunction.Argon2:
                isValid = PasswordHash.ArgonHashStringVerify(hashedPassword, providedPassword);
                break;

            case LfHashFunction.SCrypt:
                isValid = PasswordHash.ScryptHashStringVerify(hashedPassword, providedPassword);
                break;

            case LfHashFunction.MD5:
                isValid = hashedPassword.Equals(CalcMd5(providedPassword));
                break;

            default:
                throw new IndexOutOfRangeException();
            }
            return(isValid ? PasswordVerificationResult.Success : PasswordVerificationResult.Failed);
        }
コード例 #2
0
ファイル: Argon2id.cs プロジェクト: inamvar/OpenIdDictUI
        public PasswordVerificationResult VerifyHashedPassword(TUser user, string hashedPassword, string providedPassword)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user), $"{nameof(user)} should not be null");
            }

            if (string.IsNullOrEmpty(hashedPassword))
            {
                throw new ArgumentNullException(nameof(hashedPassword), $"{nameof(hashedPassword)} should not be null");
            }

            if (string.IsNullOrEmpty(providedPassword))
            {
                throw new ArgumentNullException(nameof(providedPassword), $"{nameof(providedPassword)} should not be null");
            }


            try
            {
                var passwordHasher = new PasswordHasher <TUser>();
                return(passwordHasher.VerifyHashedPassword(user, hashedPassword, providedPassword));
            }
            catch
            {
                return(PasswordHash.ArgonHashStringVerify(hashedPassword, providedPassword)
                          ? PasswordVerificationResult.Success
                          : PasswordVerificationResult.Failed);
            }
        }
コード例 #3
0
ファイル: Crypto.cs プロジェクト: SupremeGenius/PIMUX
        // Verify that the user has entered the correct master password.
        public static void Authenticate(TextBox passTextBox, Button loginButton, Label statusLabel, Label infoLabel, TabControl tabControl, ListView passwordListView)
        {
            statusLabel.Text = "Authenticating your master password";



            // Prevent multiple login attempts at once.
            loginButton.Enabled = false;
            tControl            = tabControl;
            accountLoginButton  = loginButton;
            string masterPassword     = passTextBox.Text;
            string masterPasswordHash = File.ReadAllText(PIMUX_AUTH);


            // Start a background thread to verify password.
            // Background thread is used due to intensivity of Argon2i.
            new Thread(() => {
                Thread.CurrentThread.IsBackground = true;
                if (PasswordHash.ArgonHashStringVerify(masterPasswordHash, masterPassword))
                {
                    // Correct master password.
                    statusLabel.Invoke((MethodInvoker)(() => statusLabel.Text = ""));
                    tabControl.Invoke((MethodInvoker)(() => tabControl.SelectTab(2)));
                    passTextBox.Invoke((MethodInvoker)(() => passTextBox.Text = ""));
                    PasswordManage pm = new PasswordManage(masterPassword, infoLabel, passwordListView);
                }
                else
                {
                    // Incorrect master password.
                    statusLabel.Invoke((MethodInvoker)(() => statusLabel.Text = "Invalid master password"));
                    MessageBox.Show("Invalid master password");
                }
                loginButton.Invoke((MethodInvoker)(() => loginButton.Enabled = true));
            }).Start();
        }
コード例 #4
0
        /// <summary>
        /// Verify Argon Hash password.
        /// </summary>
        /// <returns><c>true</c>, if pwd was verifiyed, <c>false</c> otherwise.</returns>
        /// <param name="hash">Hash.</param>
        /// <param name="pwd">Pwd.</param>
        public static bool VerifiyPwd(byte[] hash, byte[] pwd)
        {
            Guard.Argument(hash, nameof(hash)).NotNull();
            Guard.Argument(pwd, nameof(pwd)).NotNull();

            return(PasswordHash.ArgonHashStringVerify(hash, pwd));
        }
コード例 #5
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);
        }
コード例 #6
0
        public void ArgonHashStringModerateTest()
        {
            const string PASSWORD = "******";
            var          hash     = PasswordHash.ArgonHashString(PASSWORD, PasswordHash.StrengthArgon.Moderate);

            Assert.IsTrue(PasswordHash.ArgonHashStringVerify(hash, PASSWORD));
        }
        public void HashPassword_WithDefaultSettings_ExpectVerifiableHash()
        {
            var password = Guid.NewGuid().ToString();

            var hasher         = new Argon2PasswordHasher <string>();
            var hashedPassword = hasher.HashPassword("", password);

            PasswordHash.ArgonHashStringVerify(hashedPassword, password).Should().BeTrue();
        }
コード例 #8
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));
        }
        public void HashPassword_WithCustomStrength_ExpectVerifiableHash()
        {
            var password = Guid.NewGuid().ToString();

            var hasher = new Argon2PasswordHasher <string>(
                new OptionsWrapper <Argon2PasswordHasherOptions>(
                    new Argon2PasswordHasherOptions {
                Strength = Argon2HashStrength.Sensitive
            }));
            var hashedPassword = hasher.HashPassword("", password);

            PasswordHash.ArgonHashStringVerify(hashedPassword, password).Should().BeTrue();
        }
コード例 #10
0
ファイル: Cryptography.cs プロジェクト: KrakenOverlord/Cypher
        /// <summary>
        /// Verify Argon Hash password.
        /// </summary>
        /// <returns><c>true</c>, if pwd was verifiyed, <c>false</c> otherwise.</returns>
        /// <param name="hash">Hash.</param>
        /// <param name="pwd">Pwd.</param>
        public static bool VerifiyPwd(byte[] hash, byte[] pwd)
        {
            if (hash == null)
            {
                throw new ArgumentNullException(nameof(hash));
            }

            if (pwd == null)
            {
                throw new ArgumentNullException(nameof(pwd));
            }

            return(PasswordHash.ArgonHashStringVerify(hash, pwd));
        }
コード例 #11
0
    /// <summary>
    /// Verify a password hashed using argon2id
    /// </summary>
    /// <param name="this">Password hash</param>
    /// <param name="password">Password to verify</param>
    public static bool VerifyPassword(this string @this, string password)
    {
        if (string.IsNullOrWhiteSpace(@this))
        {
            return(false);
        }

        if (string.IsNullOrEmpty(password))
        {
            return(false);
        }

        return(PasswordHash.ArgonHashStringVerify(@this.Trim(), password));
    }
コード例 #12
0
        public void HashPassword_WithDefaultSettings_ExpectVerifiableHash()
        {
            var password = "******";

            var hasher         = new Argon2PasswordHasher <string>();
            var hashedPassword = hasher.HashPassword("", password);

            output.WriteLine(hashedPassword);

            //this will produce a 32 byte hash
            var hash = PasswordHash.ScryptHashString(password);

            PasswordHash.ArgonHashStringVerify(hashedPassword, password).Should().BeTrue();
        }
コード例 #13
0
        /// <summary>Method which verifies that a supplied plain-text password matches the encrypted password.</summary>
        public bool Verify(string plaintext)
        {
            if (EncryptedPasswordb64 == null)
            {
                throw new Exception("You must have an encrypted password to verify against");
            }

            // Unpack the Encrypted Password
            var base10          = Convert.FromBase64String(EncryptedPasswordb64);
            var dec             = new ChaCha20Poly1305(Encoding.ASCII.GetBytes(Key));
            var decryptedBytes  = dec.Decrypt(base10);
            var decryptedString = Encoding.ASCII.GetString(decryptedBytes);

            return(PasswordHash.ArgonHashStringVerify(decryptedString, plaintext));
        }
        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));
            }

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

            return(isValid ? PasswordVerificationResult.Success : PasswordVerificationResult.Failed);
        }
コード例 #15
0
        public PasswordVerificationResult VerifyHashedPassword(TUser user, string hashedPassword,
                                                               string providedPassword)
        {
            if (PasswordHash.ArgonHashStringVerify(hashedPassword, providedPassword))
            {
                return(PasswordVerificationResult.Success);
            }

            if (_previous?.VerifyHashedPassword(user, hashedPassword, providedPassword) ==
                PasswordVerificationResult.Success)
            {
                return(PasswordVerificationResult.SuccessRehashNeeded);
            }

            return(PasswordVerificationResult.Failed);
        }
コード例 #16
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());
            }
        }
コード例 #17
0
        public ActionResult Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var list = db.Accounts.Where(a => a.Login == model.Email).Take(1).ToList();

            if (list.Count == 0)
            {
                ModelState.AddModelError("", "Такой аккаунт не существует.");
                return(View(model));
            }
            else
            {
                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.Password, empty, 32))))
                {
                    FormsAuthentication.SetAuthCookie(model.Email, false);
                    var rolesArray = Roles.GetRolesForUser(User.Identity.Name);
                    Roles.CreateRole("User");

                    //Roles.AddUserToRole(User.Identity.Name, "Member");
                    //RolePrincipal r = (RolePrincipal)User;
                    //var rolesArray1 = r.GetRoles();
                    return(RedirectToLocal(returnUrl));
                }
                else
                {
                    ModelState.AddModelError("", "Неверный логин или пароль.");
                    return(View(model));
                }
            }
        }
コード例 #18
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));
        }
コード例 #19
0
ファイル: LfPasswordHasher.cs プロジェクト: llldar/lonefire2
        public PasswordVerificationResult VerifyHashedPassword(ApplicationUser user, string hashedPassword, string providedPassword)
        {
            if (hashedPassword == null)
            {
                throw new ArgumentNullException(nameof(hashedPassword));
            }
            if (providedPassword == null)
            {
                throw new ArgumentNullException(nameof(providedPassword));
            }
            var isValid = options.HashFunction switch
            {
                LfHashFunction.MD5 => hashedPassword.Equals(CalcMd5(providedPassword)),
                LfHashFunction.Argon2 => PasswordHash.ArgonHashStringVerify(hashedPassword, providedPassword),
                LfHashFunction.SCrypt => PasswordHash.ScryptHashStringVerify(hashedPassword, providedPassword),
                _ => throw new IndexOutOfRangeException(),
            };

            return(isValid ? PasswordVerificationResult.Success : PasswordVerificationResult.Failed);
        }
コード例 #20
0
        public async Task <ActionResult <string> > Login(string identifier, string password)
        {
            var user = await _userRepository.FindByIdentifier(identifier);

            if (user == null)
            {
                return(new ActionResult <string>(false, ("", "Invalid credentials")));
            }

            var passwordCorrect = PasswordHash.ArgonHashStringVerify(user.PasswordHash, password);

            if (!passwordCorrect)
            {
                return(new ActionResult <string>(false, ("", "Invalid credentials")));
            }

            var token = TokenGenerator.GenerateAuthToken();
            await _authRepository.CreateToken(user.Id, token);

            return(new ActionResult <string>(true, token));
        }
コード例 #21
0
        public JwtSecurityToken Authenticate(string email, string password)
        {
            if (string.IsNullOrWhiteSpace(email) || string.IsNullOrWhiteSpace(password))
            {
                return(null);
            }

            var user = mSentryContext
                       .Users
                       .FirstOrDefault(p => p.Email == email);

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

            if (PasswordHash.ArgonHashStringVerify(user.PasswordHash, password))
            {
                var claims = new[]
                {
                    new Claim("uid", user.UserIdentifier.ToString())
                };

                var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(mConfiguration["Authentication:SecurityKey"]));
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                return(new JwtSecurityToken(
                           issuer: "yourdomain.com",
                           audience: "yourdomain.com",
                           claims: claims,
                           expires: DateTime.Now.AddMinutes(30),
                           signingCredentials: creds));
            }

            return(null);
        }
コード例 #22
0
        public void ArgonHashStringVerifyTest()
        {
            const int OUTPUT = 1;
            const int PASS   = 0;
            var       tests  = new List <string[]>
            {
                new[] { "", "$argon2i$v=19$m=2048,t=4,p=1$SWkxaUhpY21ISDcrRnYzSw$Mbg/Eck1kpZir5T9io7C64cpffdTBaORgyriLQFgQj8" },
                new[]
                {
                    "^T5H$JYt39n%K*j:W]!1s?vg!:jGi]Ax?..l7[p0v:1jHTpla9;]bUN;?bWyCbtqg ",
                    "$argon2i$v=19$m=4096,t=3,p=2$X1NhbHQAAAAAAAAAAAAAAA$z/QMiU4lQxGsYNc/+K/bizwsA1P11UG2dj/7+aILJ4I"
                },
                new[]
                {
                    "K3S=KyH#)36_?]LxeR8QNKw6X=gFbxai$C%29V*",
                    "$argon2i$v=19$m=4096,t=3,p=1$X1NhbHQAAAAAAAAAAAAAAA$fu2Wsecyt+yPnBvSvYN16oP5ozRmkp0ixJ1YL19V3Uo"
                }
            };

            foreach (var test in tests)
            {
                Assert.IsTrue(PasswordHash.ArgonHashStringVerify(test[OUTPUT], test[PASS]));
            }
        }
コード例 #23
0
 public override PasswordVerificationResult VerifyHashedPassword(TUser user, string hashedPassword, string providedPassword)
 {
     return(PasswordHash.ArgonHashStringVerify(hashedPassword, providedPassword) ? PasswordVerificationResult.Success : PasswordVerificationResult.Failed);
 }
コード例 #24
0
 /// <summary>Verifies a password with its hashed counterpart.</summary>
 /// <param name="hashedPassword">Hashed password</param>
 /// <param name="password">Plaintext password</param>
 /// <returns>Returns result of validation</returns>
 public static bool ValidatePassword(string hashedPassword, string password) => PasswordHash
 .ArgonHashStringVerify(hashedPassword, password);
コード例 #25
0
 public bool VerifyHashedPassword(string plaintext, string hash)
 {
     return(PasswordHash.ArgonHashStringVerify(hash, plaintext));
 }
コード例 #26
0
 public bool VerifyPassword(string hash, string password)
 {
     return(PasswordHash.ArgonHashStringVerify(hash, password));
 }