Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a equal hash to the FormsAuthentication.HashPasswordForStoringInConfigFile("asdf", "MD5") method?

Tags:

c#

asp.net

hash

Looking for a method or to be pointed in the right direction so I can return an hash equal to the hash returned by FormsAuthentication.HashPasswordForStoringInConfigFile("asdf", "MD5"). I've been trying code like:

        ASCIIEncoding encoding = new ASCIIEncoding();
        encoding.GetBytes("asdf");

        var hashedBytes = MD5.Create().ComputeHash(bytes);
        var password = encoding.GetString(hashedBytes);

I'm not that strong on Hashing so I don't know where to go next. I always end up with crazy special characters while the FormsAuth method always returns something readable.

Just trying to remove the external dependency to FormAuthentication from some internal business classes.

like image 838
John Farrell Avatar asked Nov 28 '22 11:11

John Farrell


2 Answers

Here is the reflector's output:

Your problem is not using UTF8

public static string HashPasswordForStoringInConfigFile(string password, string passwordFormat)
{
    HashAlgorithm algorithm;
    if (password == null)
    {
        throw new ArgumentNullException("password");
    }
    if (passwordFormat == null)
    {
        throw new ArgumentNullException("passwordFormat");
    }
    if (StringUtil.EqualsIgnoreCase(passwordFormat, "sha1"))
    {
        algorithm = SHA1.Create();
    }
    else
    {
        if (!StringUtil.EqualsIgnoreCase(passwordFormat, "md5"))
        {
            throw new ArgumentException(SR.GetString("InvalidArgumentValue", new object[] { "passwordFormat" }));
        }
        algorithm = MD5.Create();
    }
    return MachineKeySection.ByteArrayToHexString(algorithm.ComputeHash(Encoding.UTF8.GetBytes(password)), 0);
}

So here is your updated code:

    encoding.GetBytes("asdf");

    var hashedBytes = MD5.Create().ComputeHash(bytes);
    var password = Encoding.UTF8.GetString(hashedBytes);
like image 187
Aliostad Avatar answered Dec 06 '22 00:12

Aliostad


After some Googling, I changed @Pieter's code to make it independent of the System.Web

return string.Join("",
  new MD5CryptoServiceProvider().ComputeHash(
    new MemoryStream(Encoding.UTF8.GetBytes(password))).Select(x => x.ToString("X2")));
like image 26
Sentient Avatar answered Dec 06 '22 00:12

Sentient