I'm trying to convert this function into PHP but somehow it does not give same results.
public static string EncodePassword(string pass, string salt) {
byte[] bytes = Encoding.Unicode.GetBytes(pass);
byte[] src = Convert.FromBase64String(salt);
byte[] dst = new byte[src.Length + bytes.Length];
byte[] inArray = null;
Buffer.BlockCopy(src, 0, dst, 0, src.Length);
Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length);
HashAlgorithm algorithm = HashAlgorithm.Create("SHA1");
inArray = algorithm.ComputeHash(dst);
return Convert.ToBase64String(inArray);
}
This is my take on that in PHP
function CreatePasswordHash($password, $salt) {
$salted_password = base64_decode($salt).$password;
$result = hash('SHA1',$salted_password,true);
return base64_encode($result);
}
And of course it does not work. So what am I doing wrong here?
These are the values for testing:
$salt = 'Xh2pHwDv3VEUQCvz5qOm7w==';
$hashed_value = '0U/kYMz3yCXLsw/r9kocT5zf0cc=';
$password = 'Welcome1!';
if ($hashed_value === CreatePasswordHash($password,$salt)) {
echo "Good job!";
}
Edit: Working solution based on suggestions from Martyx and Slacks
function CreatePasswordHash($password, $salt) {
$upass = mb_convert_encoding($password,'UCS-2LE','auto');
$salted_password = base64_decode($salt).$upass;
$result = hash('SHA1',$salted_password,true);
return base64_encode($result);
}
Once I used SHA1 in PHP and C# and in C# output letters were in uppercase and in PHP it was in lowercase.
I would recommend to use the same encoding in C# and in PHP (UTF8 and UTF16 are good choices).
Choices in C#:
encoding PHP:
You need to tell PHP to encode the password string using UTF16 and the salt as raw bytes.