Search code examples
c#securityencryptionhashpbkdf2

Performance of PBKDF2 c#.NET with


I need to implement a password hashing mechanism for our system. I am using PBKDF2 for the purpose. I have made a small console application for the demo purpose. With the parameters I am using, Its taking my desktop 56 ms to generate the final hash.

From the sources I have gone through, they mentioned the generation time of 100ms should be reasonably secured. Is it the correct assumption or should I make my generation slower? If yes, what parameters should I probably change?

CODE:

class Program
{
    static void Main(string[] args)
    {
        var watch = System.Diagnostics.Stopwatch.StartNew();
        byte[] op = null;
        op = GetPDKDF2("password", 20, 10000);
        watch.Stop();
        Console.WriteLine("total time: " + watch.ElapsedMilliseconds);
        Console.ReadKey();
    }

    public static byte[] GetPDKDF2(string password, int saltSize, int iterationCount)
    {
        var pdf = new Rfc2898DeriveBytes(password, saltSize, iterationCount);
        return pdf.GetBytes(20);
    }

}

Solution

  • The standard delay to aim for is, as you said, 100ms. The time taken to compute a hash with PBKDF2 is proportionate to the iteration count. With this in mind, you could probably just double your iteration count to get a delay of around 100ms.

    I suggest you don't allow the iteration count to change, at least not as an argument to the function. Changing the iteration count in future, as hardware progresses, is a good idea, but you need to ensure the iteration count used is noted with the produced hash.

    I'd use a constant value for the iteration count instead:

    const int ITERATION_COUNT = 20000;
    

    And use:

    public static byte[] GetPDKDF2(string password, int saltSize)
    {
        var pdf = new Rfc2898DeriveBytes(password, saltSize, ITERATION_COUNT);
        return pdf.GetBytes(20);
    }