Mimicking the .NET Membership in PHP

Few days ago I needed this code, but surprisingly, most of the stuff you can find on the Net is “I don’t know how”, and very scarcely you can see a code that seems to work.

Yet, it’s trivial.

Presented here is the function that returns bool value whether the user authentication was successful or not. The code for password hash generation is the same, salt is created simply as a base64 encoding of random 16 bytes (binary in .NET, feel free to just use e.g. base64_encode(substr(md5(microtime()), 0, 16)), works just as well).

Input is $passhash – the password hash stored in DB, $salt – the base64 encoded salt from DB, and $password – (UTF-8/ASCII) string of the password provided by the user:

function ValidateLogin($passhash, $salt, $password)
{
    $salt = base64_decode($salt);
    $pass_ucs2 = iconv('UTF-8', 'UCS-2', $password);
    $hash_to_check = base64_encode(sha1($salt.$pass_ucs2, true));
    return ($hash_to_check == $passhash);
}

And… that’s it. You can of course make it a one liner, if that’s your cup of coffee.

The $hash_to_check value is what you would use for password hash upon user creation.

One response to “Mimicking the .NET Membership in PHP

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s