Problem with copy byte[] into another byte[]

15,994

Solution 1

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

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

Solution 2

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);
}
Share:
15,994
Jova
Author by

Jova

Updated on June 04, 2022

Comments

  • Jova
    Jova almost 2 years

    I have a method to create a hashed password. However it crashes at salt.CopyTo(pwd, 0); Says that the target byte[] is too small. How do I 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;            
            }