c# - Rfc2898DeriveBytes how to verify the password which is store in database as hash value -
how verify password store in database hash value
when verify password hash database value never same because generates random salt.
how append salt in order verify , test.
below code using hashing , verify hashed password.
my code :
/// <summary> /// generate value bytes. /// </summary> /// <param name="password"></param> /// <param name="iterationcount"></param> /// <returns></returns> private static string generatehashvalue(string password) { return convert.tobase64string(generatehashbytes(password)); } /// <summary> /// hashing password using pbkdf2 /// </summary> /// <param name="password"></param> /// <param name="iterationcount"></param> /// <returns></returns> private static byte[] generatehashbytes(string password) { byte[] hashvalue; //create salt byte[] salt = generaterandomsalt(); var valuetohash = string.isnullorempty(password) ? string.empty : password; using (var pbkdf2 = new rfc2898derivebytes(valuetohash,salt, iterationcount)) { hashvalue = pbkdf2.getbytes(derivedkeylength); } return hashvalue; } public static bool verifypassword(string password, string correcthash) { byte[] hash; byte[] originalhash = encoding.ascii.getbytes(correcthash); hash = generatehashbytes(password); return slowequals(hash, originalhash); } private static bool slowequals(byte[] a, byte[] b) { var diff = (uint)a.length ^ (uint)b.length; (int = 0; < a.length && < b.length; i++) { diff |= (uint)(a[i] ^ b[i]); } return diff == 0; } /// <summary> /// used generate random string append hash. /// </summary> /// <returns></returns> private static byte[] generaterandomsalt() { /*we using rngcryptoserviceprovider class create cryptography secure pseudo-random number generator generate level of randomness , uniqueness require salt.*/ var csprng = new rngcryptoserviceprovider(); var salt = new byte[saltbytelength]; csprng.getbytes(salt); return salt; }
you have create salt , store in database along password hash.
upon hashing password, request salt user x (or whatever) db, check if exists, , apply salt hash.
it (pseudo-code little of provided code):
var salt = getsaltfromdb(); if (salt == null) //not yet in db salt = generatesalt(); //this saves salt db using (var pbkdf2 = new rfc2898derivebytes(valuetohash, salt, iterationcount)) { hashvalue = pbkdf2.getbytes(derivedkeylength); }
Comments
Post a Comment