0

Trying to understand hashing functions and I can't seem to work out why BlockCopy is used within it.

public static string HashPassword(string password)
        {
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }

            // Produce a version 0 (see comment above) password hash.
            byte[] salt;
            byte[] subkey;
            using (var deriveBytes = new Rfc2898DeriveBytes(password, SaltSize, PBKDF2IterCount))
            {
                salt = deriveBytes.Salt;
                subkey = deriveBytes.GetBytes(PBKDF2SubkeyLength);
            }

            byte[] outputBytes = new byte[1 + SaltSize + PBKDF2SubkeyLength];
            Buffer.BlockCopy(salt, 0, outputBytes, 1, SaltSize);
            Buffer.BlockCopy(subkey, 0, outputBytes, 1 + SaltSize, PBKDF2SubkeyLength);
            return Convert.ToBase64String(outputBytes);
        }
litterbugkid
  • 3,534
  • 7
  • 36
  • 54

2 Answers2

1

Buffer.BlockCopy() is a faster way to do an array copy when using primitives.

In your code it is copying from salt and subkey to outputBytes.

Jon B
  • 51,025
  • 31
  • 133
  • 161
  • Ahh okay. But why does it need to copy the salt and subkey into an array? – litterbugkid Jan 08 '13 at 16:57
  • @Neeta You need both of these pieces of information to later use the hashed key. Without either piece, the password is lost and cannot be used for verification any more. You will probably want to use the salt information later to compare another password’s hash against this one. – Konrad Rudolph Jan 08 '13 at 16:59
1

This code concatenates a 0 byte (for the version), the salt and the hash. It's equivalent to:

new byte[]{0}.Concat(salt).Concat(subkey).ToArray()

But it's faster and leaves behind less garbage.

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
  • Why does it need to copy the salt and subkey into an array? – litterbugkid Jan 08 '13 at 16:58
  • @Neeta You need to store both salt and hash to verify your hash later on. The `Verify` function will extract the salt part from the concatenated value, hash the password with it, and then compare with the hash part. – CodesInChaos Jan 08 '13 at 16:58