// Collection of code snippets by Arne Vajhøj // (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) using System; using System.Security.Cryptography; using System.Text; namespace Encrypt { public class TestPasswordHashing { private const string PREFIX = "pbkdf2"; // generate salt private static RandomNumberGenerator rng = RandomNumberGenerator.Create(); private static byte[] GenSalt(int size) { byte[] res = new byte[size]; rng.GetBytes(res); return res; } // hash: byte[] + byte[] salt -> byte[] public static byte[] Hash(byte[] pw, byte[] salt, int nit, int keylen) { Rfc2898DeriveBytes alg = new Rfc2898DeriveBytes(pw, salt, nit); return alg.GetBytes(keylen / 8); } // Base64 encode: byte[] -> string // Base64 decode: string -> byte[] private static string Encode(byte[] b) { return Convert.ToBase64String(b); } private static byte[] Decode(string s) { return Convert.FromBase64String(s); } // hash: string -> Base64 string // verify: string + saved hash string -> bool public static string Hash(string pw, int saltlen, int nit, int keylen) { byte[] salt = GenSalt(saltlen); return String.Format("{0}${1}${2}${3}${4}", PREFIX, nit, keylen, Encode(salt), Encode(Hash(Encoding.UTF8.GetBytes(pw), salt, nit, keylen))); } public static bool Verify(string pw, string savedhash) { string[] parts = savedhash.Split('$'); if(parts[0] != PREFIX) throw new Exception("Unsupported algorithm: " + parts[0]); int nit = int.Parse(parts[1]); int keylen = int.Parse(parts[2]); byte[] salt = Decode(parts[3]); return Encode(Hash(Encoding.UTF8.GetBytes(pw), salt, nit, keylen)) == parts[4]; } // test private const string PW = "A super secret password"; private static void Test(string label, int saltlen, int nit, int keylen) { Console.WriteLine(label + ":"); string hashval = Hash(PW, saltlen, nit, keylen); Console.WriteLine(" " + hashval); bool ok = Verify(PW, hashval); Console.WriteLine(" " + ok); bool ok2 = Verify(PW + "X", hashval); Console.WriteLine(" " + ok2); } private static void Test2() { if(!Verify(PW, "pbkdf2$10000$512$OPf3qDpgi7iIyQ/Cn2XUHQ==$3T8Yhih2SEq22bnbhCucHs9TTQmsSz28O8jk2cvYh6ihZhNHBcOXsUlX2UAKWJEdmjAA+R8yMOAqtJYdSfqYwg==")) { throw new Exception("Ooops"); } } public static void Main(string[] args) { Test("PBKDF2 with HMAC SHA-1", 16, 10000, 512); Test2(); } } }