Skip to content

Instantly share code, notes, and snippets.

@koistya
Created June 16, 2012 23:37
Show Gist options
  • Select an option

  • Save koistya/2942857 to your computer and use it in GitHub Desktop.

Select an option

Save koistya/2942857 to your computer and use it in GitHub Desktop.
Password Utility utilizing PKBDF2 algorithm; hash and verify passwords with PKBDF2 aka RFC2898
//-------------------------------------------------------------------------------
// <copyright file="Password.cs" company="KriaSoft LLC">
// Copyright © 2012 Konstantin Tarkus, KriaSoft LLC. All rights reserved.
// See License.md in the project root for license information.
// </copyright>
//-------------------------------------------------------------------------------
namespace App.Security
{
using System.Linq;
using System.Security.Cryptography;
/// <summary>
/// A collection of password related utility methods. See also:
/// http://throwingfire.com/storing-passwords-securely/
/// http://en.wikipedia.org/wiki/PBKDF2"
/// Usage sample:
/// <code>
/// var hash = Password.Hash("Passw0rd", saltLength: 25, keyLength: 25);
/// var isValid = Password.Verify("PasswOrd", hash.Salt, hash.Key);
/// </code>
/// </summary>
internal static class Password
{
public static HashBytes Hash(string password, int saltLength, int keyLength)
{
using (var deriveBytes = new Rfc2898DeriveBytes(password, saltLength, 10000))
{
return new HashBytes {
Salt = deriveBytes.Salt,
Key = deriveBytes.GetBytes(keyLength)
};
}
}
public static bool Verify(string password, byte[] salt, byte[] key)
{
using (var deriveBytes = new Rfc2898DeriveBytes(password, salt, 10000))
{
return deriveBytes.GetBytes(key.Length).SequenceEqual(key);
}
}
public struct HashBytes
{
public byte[] Salt;
public byte[] Key;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment