Amait
Amait

Reputation: 134

C#: comparing the password hash with the user input different sizes , when Authenticating the user

I have made a user registration where I have salted the user password and hashed it using SHA256. later, when the user needs to log into my system I need to have his password salted and hashed, so I : 1.retrieved the salt "string" from Database 2. converted the salt into bytes 3. created a new byte[] = [inputPassword.length + salt.length] 4. and hashed that.

now the new hash is shorter than Original hash ...(using same hashing functions)

given these information what do you think the problem might be ... is storing the salt as CHAR on my database wrong , if yes what or how should I save it ?

Note: both hashes are compared on byte level. Note: all user information are stored in the database password and salt as CHAR

thank you in advance

Upvotes: 3

Views: 7718

Answers (2)

Poma
Poma

Reputation: 8484

Usually hash functions return fixed size hash, so if you tell that new hash is shorter I think problem might be in your hash function.

Upvotes: 1

Tom W Hall
Tom W Hall

Reputation: 5283

You could generate a salt from a Guid converted into a base 64 string, then save that in the database as char. I use nvarchar to maximise my options using a .NET string.

Then you can implement something like this for generating the original password hash, and comparing the hash when the user logs in:

    public static byte[] GetHash(string password, string salt)
    {
        byte[] unhashedBytes = Encoding.Unicode.GetBytes(String.Concat(salt, password));

        SHA256Managed sha256 = new SHA256Managed();
        byte[] hashedBytes = sha256.ComputeHash(unhashedBytes);

        return hashedBytes;
    }

    public static bool CompareHash(string attemptedPassword, byte[] hash, string salt)
    {
        string base64Hash = Convert.ToBase64String(hash);
        string base64AttemptedHash = Convert.ToBase64String(GetHash(attemptedPassword, salt));

        return base64Hash == base64AttemptedHash;
    }

Upvotes: 4

Related Questions