Search code examples
c#linqlinq-to-sqlencryptioncodeplex

Comparing Encrypted Passwords in Database and User Input With Encrypto


How do I compare Encrypted passwords that I inserted in the database from the users Input? and I notice that while I was testing my program, I've created an account where they both have the same password but they have different encryptions, how would I know if the users input is the same as the one in the database? does Encrypto do it that way? or Encrypto has a distinctive way of determining which is which?

and am I using Encrypto right in this code?

var hasher = new Hasher();

hasher.SaltSize = 16;

//Encrypts The password
var encryptedPassword = hasher.Encrypt(txtPass.Text);

Account newUser = new Account();

System.Text.UTF8Encoding encoding=new System.Text.UTF8Encoding();

newUser.accnt_User = txtUser.Text;
newUser.accnt_Position = txtPosition.Text;
newUser.accnt_Pass = new System.Data.Linq.Binary(encoding.GetBytes(encryptedPassword));

Solution

  • Two identical passwords can result in different hashes because Encrypto appends a random salt to the end of the password before hashing it.

    On codeplex check out the source code for Hasher.cs to see how they do this. They basically use the salt to do the hash and then append the salt to the end of the hash. this is what you store in the DB.

    When a user sets their password or a new user registers, you hash the password and store it in the DB

    var hasher = new Hasher();
    hasher.SaltSize = 16;
    var hashedPasswordToStoreInDB = hasher.Encrypt(passwordToSet);
    

    Later on when they log in and enter their password you compare the password that the user types to the previously hashed version retrieved from the DB like this

    var hasher = new Hasher();
    hasher.SaltSize = 16;
    bool areEqual = hasher.CompareStringToHash(enteredPassword, hashFromDatabase);
    

    Again, if you look at the source code (Hasher.CompareStringToHash) you will see that the random salt is recovered from the stored hash and then used to compute a new hash from the entered password.