Trying to port C# function to PHP5

2019-05-30 09:29发布

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);
}

2条回答
啃猪蹄的小仙女
2楼-- · 2019-05-30 09:38

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.ASCII.GetBytes
  • Encoding.UTF8.GetBytes
  • ...

encoding PHP:

查看更多
我命由我不由天
3楼-- · 2019-05-30 09:52

You need to tell PHP to encode the password string using UTF16 and the salt as raw bytes.

查看更多
登录 后发表回答