Search code examples
c#.netsecurityrfc2898

How many bytes should a password hash be when using Rfc2898DeriveBytes?


I have a hashing function below, is 128 byte hash for password overkill or underkill?

  public string HashPassword(string password)
  {
    Rfc2898DeriveBytes rfc = new(
      password,
      _salt,
      _iterations,
      _hashAlgorithmName
    );
    // is 128 bytes a good number?
    var hashedPasswordBytes = rfc.GetBytes(128);

    return Convert.ToBase64String(hashedPasswordBytes);
  }

Solution

  • This is related to the output length of _hashAlgorithmName you use. For example, if you use HMAC-SHA512, the output length is 512 bits (64 bytes) and getting more bytes than 64 bytes is a bit overkill. Even 256 bits of entrophy is enough for today's standards.

    Actually, this is why ASP.NET Core Identity package uses only 32 bytes (256 bits) when hashing passwords with Rfc2898DeriveBytes by using HMAC-SHA512.

    For reference: https://github.com/dotnet/aspnetcore/blob/main/src/Identity/Extensions.Core/src/PasswordHasher.cs