PasswordHashOMatic is broken!

The Verify() in this class is broken. The hashedPassword passed to Convert.FromBase64(hashedPassword) is never valid.

I can’t get passed this part of the M220N course without this class working. Who can help resolve this issue?

using System;
using System.Security.Cryptography;

namespace M220N
{
public static class PasswordHashOMatic
{
    private const int SaltSize = 16;
    private const int HashSize = 20;
    private const int Iterations = 1000;

    public static string Hash(string password)
    {
        byte[] salt;
        new RNGCryptoServiceProvider().GetBytes(salt = new byte[SaltSize]);

       var pbkdf2 = new Rfc2898DeriveBytes(password, salt, Iterations);
       var hash = pbkdf2.GetBytes(HashSize);

       var hashBytes = new byte[SaltSize + HashSize];
       Array.Copy(salt, 0, hashBytes, 0, SaltSize);
       Array.Copy(hash, 0, hashBytes, SaltSize, HashSize);

       return Convert.ToBase64String(hashBytes);
    }

    public static bool Verify(string password, string hashedPassword)
    {
        var hashBytes = Convert.FromBase64String(hashedPassword);
  

        var salt = new byte[SaltSize];
        Array.Copy(hashBytes, 0, salt, 0, SaltSize);

        var pbkdf2 = new Rfc2898DeriveBytes(password, salt, Iterations);

        byte[] hash = pbkdf2.GetBytes(HashSize);

        for (var i = 1; i < HashSize; i++)
        {
            if (hashBytes[i + SaltSize] != hash[i])
            {
                return false;
            }
        }

        return true;
    }
}
}

Hi @Don_Krause :wave:.
Can you please post a screenshot of the error that you are getting while executing the same?

In case you have any doubts, please feel free to reach out to us.

Thanks and Regards.
Sourabh Bagrecha,
Curriculum Services Engineer

I figured out the problem. I needed to Hash the password before sending it to Convert.FromBase64String.

2 Likes