0 day streak
csharp / intermediate
Snippet

Cryptographically Secure Hashing with PBKDF2

PBKDF2 (Password-Based Key Derivation Function 2) is a standard for secure password hashing. It applies a pseudo-random function to the password along with a salt many times, making brute-force attacks significantly more difficult.

snippet.cs
csharp
1
2
3
4
5
6
7
8
using System.Security.Cryptography;
public string HashPassword(string password, byte[] salt)
{
using var pbkdf2 = new Rfc2898DeriveBytes(password, salt, 100000, HashAlgorithmName.SHA256);
byte[] hash = pbkdf2.GetBytes(32);
return Convert.ToBase64String(hash);
}
Breakdown
1
new Rfc2898DeriveBytes(password, salt, 100000, ...)
Initializes the hashing algorithm with 100,000 iterations for security.
2
pbkdf2.GetBytes(32);
Generates a 32-byte hash from the derived key.