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.
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);
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")));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With