Replicating .NET Password Hashing in PHP

Published 12th April 2011

This is a bit of a geeky one which I’m putting down mostly for reference. I’m writing a PHP app just now that needs to connect to a Sql Server 2005 database from a previous ASP.NET project. It already has the membership set up and users in the database. All I need to do is connect to the database and authenticate my user using the information stored in the database.

However this raises a problem when you try to compare your users password to the hashed password in the database. The ASP.NET membership has a certain way of hashing passwords which you will need to re-create in PHP to authenticate your users. So this is how I did it.

$bytes = mb_convert_encoding($password, 'UTF-16LE'); 
$salt = base64_decode($password_salt);
$password = base64_encode(sha1($salt . $bytes, true));
if ($password == $hashed_password) {
// success

Note that `$hashed_password` and `$password_salt` above need to first be retrieved from the aspnet_Membership table of the database (from the Password and PasswordSalt fields).