I have searched all over Google and I can't find a code sample of Scrypt usage (for hashing a password) using the Cryptsharp library.
Can you please provide a sample for hashing the password?
It's only a single call so I'll walk you through the parameters:
key
: this is your password, use UTF-8 encoding (without byte order mark) to encode your password into a byte array;salt
: a string of secure random bytes stored with the result of the scrypt function, 16 bytes should be ample;cost
: the given suggestion is 262144, but you may want to increase that value if your server can handle the additional load;blockSize
: see cost, the given suggestion is 8;parallel
: I would keep this to 1 unless you want to experiment with multi-threading;maxThreads
: in general null
will do nicely;derivedKeyLength
: well, that depends, for passwords 128 should be ample though, it's unlikely that your password has more than 128 bits of security.You should store at least the salt and result. You may want to use base 64 encoding if you want to store them as strings.
I would recommend you to store one additional piece of data: a version of your password based key derivation scheme (PBKDF). Say, set it to 1
for using scrypt, using the given key encoding, salt size, cost, blocksize etc. In that case you can upgrade your scheme later on (you need the user to supply his/her password to do this, so you will have to do this online, so you will end up having multiple schemes operational at the same time).
Note that you may chain PBKDF function calls, so you could use the original PBKDF output and use that as input for the next PBKDF. In that case the user doesn't have to supply the password (this hint was taken from CodesInChaos on another question).
@MaartebBodewes provides an excellent answer with very wise additional tips. Here is a code sample with his recommendations. I would also suggest reading 'Your password is too damn short' which shows the importance of using modern cryptography like (at the time of writing) BCrypt or Scrypt.
public string Hash(string secret, string salt)
{
var keyBytes = Encoding.UTF8.GetBytes(secret);
var saltBytes = Encoding.UTF8.GetBytes(salt);
var cost = 262144;
var blockSize = 8;
var parallel = 1;
var maxThreads = (int?)null;
var derivedKeyLength = 128;
var bytes = SCrypt.ComputeDerivedKey(keyBytes, saltBytes, cost, blockSize, parallel, maxThreads, derivedKeyLength);
return Convert.ToBase64String(bytes);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With