What is the .NET Rfc2898DeriveBytes class?

Posted: (EET/GMT+2)

 

The class Rfc2898DeriveBytes implements the PBKDF2 (Password-Based Key Derivation Function 2) standard defined in RFC 2898. It's used to create strong cryptographic keys from passwords by applying a salt and many hash iterations.

Let's take an example. To derive a 256-bit key from a password and salt, you could use code like this:

using System.Security.Cryptography;
using System.Text;

string password = "MySecret@Password";
byte[] salt = Encoding.UTF8.GetBytes("MyUnique!SaltValue");
int iterations = 10000;

using (var deriveBytes = new Rfc2898DeriveBytes(password, salt, iterations))
{
    byte[] key = deriveBytes.GetBytes(32); // 256-bit key
    Console.WriteLine(Convert.ToBase64String(key));
}

Key points to remember:

  • Always use a unique random salt per password.
  • Use a high iteration count (at least 10,000 in 2018; higher is better as CPUs improve).
  • Store the iteration count alongside the hash for verification later.

To verify a password, recreate the same key using the known salt and stored iterations and compare it to the saved value. If they match, the user must have the correct password.