Question

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?

Was it helpful?

Solution

It's only a single call so I'll walk you through the parameters:

  1. key: this is your password, use UTF-8 encoding (without byte order mark) to encode your password into a byte array;
  2. salt: a string of secure random bytes stored with the result of the scrypt function, 16 bytes should be ample;
  3. cost: the given suggestion is 262144, but you may want to increase that value if your server can handle the additional load;
  4. blockSize: see cost, the given suggestion is 8;
  5. parallel: I would keep this to 1 unless you want to experiment with multi-threading;
  6. maxThreads: in general null will do nicely;
  7. 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).

OTHER TIPS

@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);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top