How to get a equal hash to the FormsAuthentication.HashPasswordForStoringInConfigFile("asdf", "MD5") method?
Solution 1
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);
Solution 2
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")));
Solution 3
This answer is derived from your answers:
This method in .NET is equivalent to sha1 in php:
string sha1Hash(string password)
{
return string.Join("", SHA1CryptoServiceProvider.Create().ComputeHash(Encoding.UTF8.GetBytes(password)).Select(x => x.ToString("X2"))).ToLower();
}
Solution 4
The following is the actual code used to create the password with that method:
System.Web.Configuration.MachineKeySection.ByteArrayToHexString(
System.Security.Cryptography.MD5.Create().ComputeHash(
Encoding.UTF8.GetBytes(password)
), 0
);
![John Farrell](https://i.stack.imgur.com/IqagT.jpg?s=256&g=1)
John Farrell
Updated on June 07, 2022Comments
-
John Farrell about 2 years
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.