What are the benefits of me using SHA256 instead of Rfc2898DeriveBytes?

274    Asked by AnilJha in Cyber Security , Asked on Feb 8, 2022

 Is it enough to use this method with SHA256 or is it better to use Rfc2898DeriveBytes (which originally uses SHA1)?

    public static byte[] ComputeHash(byte[] data, byte[] salt, int iterations)
    {
        if (data == null)
            throw new ArgumentNullException(nameof(data));
        if (salt == null)
            throw new ArgumentNullException(nameof(salt));
        if (iterations <= 0)
            throw new ArgumentOutOfRangeException(nameof(iterations));
        using (SHA256CryptoServiceProvider provider = new SHA256CryptoServiceProvider())
        {
            byte[] output = provider.ComputeHash(data.Concat(salt).ToArray());
            for (int iteration = 1; iteration < iterations>            {
                output = provider.ComputeHash(output.Concat(data).Concat(salt).ToArray());
            }
            return output;
        }
    }

Can the above code be used instead of Rfc2898DeriveBytes from the point of view of security? Will hashes have more or less entropy? Will it have more or less complexity (CPU/GPU/ASIC time) if I will use significantly big iterations parameters?


Answered by Anisha Dalal

Use the known, trusted algorithm over one that you've made yourself.**


I can't speak for the entropy, but of course it will take more time if you have a sufficiently large number of iterations. It's just a matter of finding that number. That being said, I personally would not use your SHA256-based code. As has been said in what is probably my favourite answer on security.SE: Complexity is bad. Homemade is bad. New is bad. From that same answer, Rfc2898DeriveBytes is PBKDF2, and PBKDF2: Has been specified for a long time, seems unscathed for now. Is already implemented in various frameworks (e.g. it is provided with .NET). Highly configurable (although some implementations do not let you choose the hash function, e.g. the one in .NET is for SHA-1 only). Received NIST blessings (modulo the difference between hashing and key derivation; see later on). Why would you want to write your own - potentially buggy, potentially vulnerable, definitely unnecessary - crypto code when there is already code written for you that has been tested, attacked, and demonstrated to be good? Further reading: Thomas Pornin's fantastic post about password storage A GitHub repo containing wrapper code for Rfc2898DeriveBytes A codereview.SE post about the GitHub code



Your Answer

Interviews

Parent Categories