Skip to content

Instantly share code, notes, and snippets.

@antdimot
Last active October 10, 2018 15:32
Show Gist options
  • Save antdimot/cc0a0552c82366a94edd4f21e5e3e87d to your computer and use it in GitHub Desktop.
Save antdimot/cc0a0552c82366a94edd4f21e5e3e87d to your computer and use it in GitHub Desktop.
Simple HashUtility useful for password encryption based on PBKDF2 algorithm
// https://en.wikipedia.org/wiki/PBKDF2
using Microsoft.AspNetCore.Cryptography.KeyDerivation;
using System;
using System.Security.Cryptography;
namespace Utils
{
public class HashUtility
{
const int saltSize = 128 / 8;
const int outputKeySize = 128 / 8;
const int numberOfIterations = 100000;
public HashUtility() { }
public string MakeHash( string text, string saltText )
{
byte[] salt = Convert.FromBase64String( saltText );
return MakeHash( text, salt );
}
public string MakeHash( string text, byte[] salt = null )
{
if( salt == null ) salt = HashUtility.CreateSalt();
var derivedKey = KeyDerivation.Pbkdf2( text, salt, KeyDerivationPrf.HMACSHA256, numberOfIterations, outputKeySize );
return Convert.ToBase64String( derivedKey );
}
public static byte[] CreateSalt()
{
var salt = new byte[saltSize];
using( var rng = RandomNumberGenerator.Create() )
{
rng.GetBytes( salt );
return salt;
}
}
public static byte[] CreateSalt( string saltText )
{
return Convert.FromBase64String( saltText );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment