c# - Hashing and GetString/GetBytes issue -
i have below code hash/store/retrieve data passwords first unit test , fails.
i beleive encoding causing problem because when getbytes called returns byte[38]
, byte[36]
when should 20 think.
i have convert string i'm storing in database.
any ideas? thanks
[fact] public void encryptdecryptpasswordshouldmatch() { string password = "password"; string passwordkey = string.empty; string passwordsalt = string.empty; helpers.createpasswordhash(password, out passwordsalt, out passwordkey); assert.true(helpers.passwordsmatch(passwordsalt, passwordkey, password)); } public static bool passwordsmatch(string passwordsalt, string passwordkey, string password) { byte[] salt = encoding.utf8.getbytes(passwordsalt); byte[] key = encoding.utf8.getbytes(passwordkey); using (var derivebytes = new rfc2898derivebytes(password, salt)) { byte[] newkey = derivebytes.getbytes(20); // derive 20-byte key if (!newkey.sequenceequal(key)) return false; } return true; } public static void createpasswordhash(string password, out string passwordsalt, out string passwordkey) { // specify want randomly generate 20-byte salt using (var derivebytes = new rfc2898derivebytes(password, 20)) { byte[] salt = derivebytes.salt; byte[] key = derivebytes.getbytes(20); // derive 20-byte key passwordsalt = encoding.utf8.getstring(salt); passwordkey = encoding.utf8.getstring(key); } }
use base64 encode binary values string, can deal arbitrary byte sequences. utf-8 transforming between unicode text , bytes , not every valid sequence of bytes valid utf-8. use utf-8 turn password(which text) bytes, use base64 salt , hash.
convert.tobase64string
, convert.frombase64string
should trick.
some additional notes:
- your terminology weird, don't call hash
key
, callhash
. i'd concatenate hash , salt in
createpasswordhash
function, caller doesn't have bother having 2 separate values.something
return base64encode(salt)+"$"+base64encode(hash)
usestring.split
in verification function.it's recommended use constant time comparison verify, seems unlikely timing side-channel can exploited.
- your iteration count pretty low. recommend increasing 10000.
Comments
Post a Comment