views:

780

answers:

3

In an ongoing effort to improve my code I am looking for the best way to create and compare a salted password in .NET.

Is there a better, or more secure, way of doing this?

My current code is as follows:

    public static string CreateSaltedPassword(string salt, string password)
    {
        SHA1CryptoServiceProvider SHA1 = null;

        SHA1 = new SHA1CryptoServiceProvider();

        // Convert the string into an array of bytes
        byte[] byteValue = System.Text.Encoding.UTF8.GetBytes(salt + password);

        // Compute the hash value
        byte[] byteHash = SHA1.ComputeHash(byteValue);

        // Dispose the unmanaged cryptographic object 
        SHA1.Clear();

        return Convert.ToBase64String(byteHash);
    }

    public static bool ComparePasswords(string salt, string password, string storedPassword)
    {
        string passwordHash = string.Empty;

        // Create the hashed password
        passwordHash = PasswordProvider.CreateSaltedPassword(
            salt, password);

        // Compare the passwords
        return (string.Compare(storedPassword, passwordHash) == 0);
    }
+2  A: 

Jeff Atwood's code project article:

This class is heavily documented, string oriented, and most of all, simple! It's ideal for learning more about encryption.

Mitch Wheat
+8  A: 
erickson
+2  A: 

Use the Rfc2898DeriveBytes class from System.Security.Cryptography.

It's built-in to the .NET framework since version 2.0 and it implements PBKDF2-HMACSHA1, which gives solid password salting and a slowing-down of the hash (which is critical for password hashes).

orip