Skip to content

Instantly share code, notes, and snippets.

@PaulNichols
Created January 9, 2017 23:06
Show Gist options
  • Save PaulNichols/2dd17aba3bfa23fb212d2b4d51f8fdd8 to your computer and use it in GitHub Desktop.
Save PaulNichols/2dd17aba3bfa23fb212d2b4d51f8fdd8 to your computer and use it in GitHub Desktop.
Cryptography - Password Based Key Derivation Function Demonstration
using System.Security.Cryptography;
namespace CryptographyInDotNet
{
public class Pbkdf2
{
public static byte[] GenerateSalt()
{
using (var randomNumberGenerator = new RNGCryptoServiceProvider())
{
var randomNumber = new byte[32];
randomNumberGenerator.GetBytes(randomNumber);
return randomNumber;
}
}
public static byte[] HashPassword(byte[] toBeHashed, byte[] salt, int numberOfRounds)
{
using (var rfc2898 = new Rfc2898DeriveBytes(toBeHashed, salt, numberOfRounds))
{
return rfc2898.GetBytes(32);
}
}
}
}
using System;
using System.Diagnostics;
using System.Text;
namespace CryptographyInDotNet
{
class Program
{
static void Main()
{
const string passwordToHash = "VeryComplexPassword";
Console.WriteLine("Password Based Key Derivation Function Demonstration in .NET");
Console.WriteLine("------------------------------------------------------------");
Console.WriteLine();
Console.WriteLine("PBKDF2 Hashes");
Console.WriteLine();
HashPassword(passwordToHash, 100);
HashPassword(passwordToHash, 1000);
HashPassword(passwordToHash, 10000);
HashPassword(passwordToHash, 50000);
HashPassword(passwordToHash, 100000);
HashPassword(passwordToHash, 200000);
HashPassword(passwordToHash, 500000);
Console.ReadLine();
}
private static void HashPassword(string passwordToHash, int numberOfRounds)
{
var sw = new Stopwatch();
sw.Start();
var hashedPassword = Pbkdf2.HashPassword(Encoding.UTF8.GetBytes(passwordToHash),
Pbkdf2.GenerateSalt(),
numberOfRounds);
sw.Stop();
Console.WriteLine();
Console.WriteLine("Password to hash : " + passwordToHash);
Console.WriteLine("Hashed Password : " + Convert.ToBase64String(hashedPassword));
Console.WriteLine("Iterations <" + numberOfRounds + "> Elapsed Time : " + sw.ElapsedMilliseconds + "ms") ;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment