Pergunta

I am using Rfc2898DeriveBytes to hash passwords.

However I am unsure as to what to pass to the GetBytes method which expects an int.

What value should I pass to this and why?

   Rfc2898DeriveBytes hasher = new Rfc2898DeriveBytes(password, System.Text.Encoding.Default.GetBytes(salt), PasswordHasher.Iterations);
      return Convert.ToBase64String(hasher.GetBytes(100));
Foi útil?

Solução

As documented at http://msdn.microsoft.com/en-us/library/system.security.cryptography.rfc2898derivebytes.getbytes.aspx, the argument to GetBytes is the number of bytes you want the GetBytes method to generate for you. If you want 5 bytes, pass 5. If you want 500, pass 500. How many bytes you ask for generally depends on how many you need for the intended usage of the key (or other cryptographic input) that you are generating.

To better understand the output, try running the following command line app:

internal static class Program
{
    private static void Main()
    {
        var deriver = new Rfc2898DeriveBytes("apples and oranges", 100, 20);
        Program.WriteArray(deriver, 5);
        Program.WriteArray(deriver, 10);
        Program.WriteArray(deriver, 20);

        Console.ReadLine();
    }

    private static void WriteArray(Rfc2898DeriveBytes source, int count)
    {
        source.Reset();
        Console.WriteLine(string.Join(" ", source.GetBytes(count).Select(b => b.ToString())));
    }
}

The output should look like this:

208 194 113 91 125
208 194 113 91 125 157 138 234 20 151
208 194 113 91 125 157 138 234 20 151 159 151 23 94 11 210 38 101 186 143

Essentially, you're getting a consistent list of bytes (based on the password, salt, and iterations) of whatever length you choose. You can regenerate exactly the same list of bytes from the same inputs at any time.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top