Вопрос

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);
        }
Это было полезно?

Решение

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.

Другие советы

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top