How to validate inputs with CryptSharp?

1k views Asked by At

Using the following unction you can encrypt an input string with bcrypt.

public static string CreatePassword(string password)
{
    // no need to provide a Salt value since bcrypt does that automatically
    byte[] PasswordBytes = Encoding.ASCII.GetBytes(password);

    return Crypter.Blowfish.Crypt(PasswordBytes);
}

This uses CryptSharp which is awesome, but how do you validate user input against the hash returned by this function?

I can't find any function in the library to do this.

The best way I can think to do it is with the following:

public static bool ValidatePassword(string password, string passwordHash)
{
    // crypt the entered password
    string Crypted = Crypter.Blowfish.Crypt(Encoding.ASCII.GetBytes(password));

    // compare the crypted password against the value in the database
    if (String.Compare(Crypted, passwordHash, false) != 0) return false;

    return true;
}

The only problem with this is that the salt value will not be the same and so the values almost always will not agree.

1

There are 1 answers

8
Pepernoot On

A salt is supposed to be unique. to avoid database password cracking for same passwords. You should store the salt with the password and if a user logs in you should check the user input and the password with the same salt

In the second argument you can give a custom salt

 string salt = Crypter.Blowfish.GenerateSalt(20);
 Crypter.Blowfish.Crypt(PasswordBytes,salt);

for Validate you can use this

public static bool ValidatePassword(string inputPassword, string storedPassword, string salt)
        {
            // crypt the entered password and stored password
            string CryptedInput = Crypter.Blowfish.Crypt(Encoding.ASCII.GetBytes(inputPassword), salt);
            string CryptedPassword = Crypter.Blowfish.Crypt(Encoding.ASCII.GetBytes(storedPassword), salt);

            // compare the crypted passwords
            return string.Equals(CryptedInput, CryptedPassword);
        }