tags:

views:

181

answers:

3

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;            
        }
+5  A: 

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);
Mark Byers
It shouldn't be random, you need to know what it is to test passwords against the hashed and salted password.
Zach Johnson
Zach: It should be random, but you should keep a copy of it. But I've changed my answer now anyway as I realise what he was trying to do (insert the bytes at the start of the array).
Mark Byers
From what I understand, it need not be random since the purpose of salt is to defeat rainbow table attacks. Even if the bad guys know what the salt is, they still have to manually calculate the hashes of the passwords.
Zach Johnson
If the salt is the same for each password you use, then you still haven't stopped a dictionary attack. The point of the salt is so that an attacker can only brute-force your password database one password at a time, instead of all at once.
Anon.
Works like a charm, Mark. Thank you very much.And yes, my salts are random for each password. It's the safest way to do it.
Jova
A: 

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

Here's how to add it to the start 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];
    }
}
Zach Johnson
+1  A: 

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);
}
Jeffrey L Whitledge
Thank you Jeffrey, this is exactly how my code looks like after adding what Mark suggested.
Jova