Problem copying byte [] to another byte []

I have a method for creating a hashed password. However, it falls on salt. CopyTo (pwd, 0); Says that target byte [] is too small. How to solve the problem?

public static byte[] CreateHashedPassword(string password, byte[] salt)
        {
            SHA1 sha1 = SHA1.Create();
            byte[] pwd = CustomHelpers.StringToByteArray(password);
            salt.CopyTo(pwd, 0);
            sha1.ComputeHash(pwd);

            return pwd;            
        }
+3
source share
3 answers

You need to create a longer byte array containing both salt and password:

    byte[] result = new byte[salt.Length + password.Length];
    salt.CopyTo(result, 0);
    password.CopyTo(result, salt.Length);
+9
source

Maybe something like this?

public static byte[] CreateHashedPassword(string password, byte[] salt) 
{ 
    SHA1 sha1 = SHA1.Create(); 
    byte[] pwd = CustomHelpers.StringToByteArray(password);
    byte[] pwdPlusSalt = new byte[salt.Length + pwd.Length];
    salt.CopyTo(pwdPlusSalt, 0); 
    pwd.CopyTo(pwdPlusSalt, salt.Length); 

    return sha1.ComputeHash(pwdPlusSalt);
}
+1
source

How big is salt? Are you planning to add it to the password?

Here's how to add it to the top of the password:

byte[] pwdAndSalt = new byte[pwd.Length + salt.Length];
for (int i = 0; i < pwdAndSalt.Length; i++)
{
    if (i < salt.Length)
    {
        pwdAndSalt[i] = salt[i];
    }
    else
    {
        pwdAndSalt[i] = pwd[i - salt.Length];
    }
}
0
source

Source: https://habr.com/ru/post/1734331/


All Articles