Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP crypt() function in .Net?

I'm rewriting a PHP web site in ASP.NET MVC. I'd like to maintain the same user base but the passwords are hashed using the PHP crypt() function. I need the same function in .Net so that I can hash a password on login and check it against the hashed password in the user database.

crypt in this case is using the CRYPT_MD5 implementation - the hashes all start with $1$

I've tried Phalanger but it doesn't have an MD5 implementation of the crypt function.

Does anyone know of one in .Net? The C# example of crypt() on CodeProject uses DES, not MD5.

I've tried the following code in C#, with different permutations of salt+password, password+salt and salt with and without $1$ prefix and $ suffix. None gives same result as PHP:

static void Main(string[] args)
{
    const string salt = "somesalt";
    const string password = "fubar";
    const string plaintextString = password + salt;
    byte[] plaintext = GetBytes(plaintextString);
    var md5 = MD5.Create("MD5");
    byte[] hash = md5.ComputeHash(plaintext);
    string s = System.Convert.ToBase64String(hash);
    Console.WriteLine("Hash of " + password + " is " + s);
    Console.ReadKey();
}

private static byte[] GetBytes(string s)
{
    var result = new byte[s.Length];
    for (int i = 0; i < s.Length; i++)
        result[i] = (byte)s[i];
    return result;
}
like image 448
Mike Scott Avatar asked Dec 05 '08 14:12

Mike Scott


2 Answers

There are a few .NET methods for md5 hashing, System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(password, format) is the easiest to use, even though it's a mouthful. Just pass "md5" through as the format.

Depending on how PHP is doing this, it may be as simple as chopping the $1$ off the beginning of the hash when you import it. It may be more complex. If you can post an example password/hash, I'll see if I can come up with some C# that generates the same hash from that password for you.

like image 72
MrKurt Avatar answered Oct 01 '22 01:10

MrKurt


Have you taken a look at the .NET MD5 class? $1$ is part of a 12 character salt.

like image 38
chriscena Avatar answered Oct 01 '22 02:10

chriscena