Created
June 16, 2012 23:37
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //------------------------------------------------------------------------------- | |
| // <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