kmaragon / Konscious.Security.Cryptography

MIT License
202 stars 20 forks source link

How to compare hashes? #45

Closed OoLunar closed 2 years ago

OoLunar commented 2 years ago

With SHA512, I'd compare hashes and see if they were the same by doing:

return user.PasswordHash.SequenceEqual(_sHA512Generator.ComputeHash(Encoding.UTF8.GetBytes(Password)));

With Argon2id, this returns false. Here's what I'm doing:

// Comparison
loginPayload.Password.Argon2idHash(user.Id).SequenceEqual(user.PasswordHash));

/// <summary>
/// Creates a Argon2ID hash of the given string, using the userid as associated data.
/// </summary>
/// <param name="password">The password to hash.</param>
/// <param name="userId">The user id to associate.</param>
/// <returns>A 1024 Argon2ID hash.</returns>
public static byte[] Argon2idHash(this string password, Guid userId)
{
    Argon2id argon2id = new(Encoding.UTF8.GetBytes(password));
    argon2id.DegreeOfParallelism = 1;
    argon2id.Iterations = 2;
    argon2id.MemorySize = 15729;
    argon2id.AssociatedData = userId.ToByteArray();
    return argon2id.GetBytes(1024);
}

No, I am not using the previous SHA512 hash to compare with the new Argon2id hash. Both hashes are new and calculated with the same data.

OoLunar commented 2 years ago

Closing as I can't seem to reproduce anymore. Seems like there was something else going wrong on my end. A CompareHash method would be nice to have available though.

OoLunar commented 2 years ago

Reopening due to a faulty if statement that made me think the hashes were equal. Two different hashes are still being produced by the same set of data.

OoLunar commented 2 years ago

Closed. Turns out different userId's were being passed around.