0 day streak
csharp / expert
Snippet

Secure Key Derivation via PBKDF2 and SHA512

Security at an expert level requires proper key stretching. PBKDF2 (Password-Based Key Derivation Function 2) with a high iteration count and SHA512 ensures that even if the database is leaked, deriving the original password requires massive computational effort, protecting sensitive user data.

snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
using System.Security.Cryptography;
byte[] salt = RandomNumberGenerator.GetBytes(32);
int iterations = 600_000; // High iteration count for brute-force resistance
// Derive a 256-bit key from a password
byte[] derivedKey = Rfc2898DeriveBytes.Pbkdf2(
password: "UserSecret123!",
salt: salt,
iterations: iterations,
hashAlgorithm: HashAlgorithmName.SHA512,
outputLength: 32);
Breakdown
1
RandomNumberGenerator.GetBytes(32)
Creates a cryptographically strong random salt to prevent rainbow table attacks.
2
iterations: 600_000
Defines the work factor; higher numbers increase the time required to guess the password.