2010-08-18 26 views
1

我試圖將此函數轉換爲PHP,但不知何故它不會給出相同的結果。嘗試將C#函數移植到PHP5中

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

這是我對在PHP

function CreatePasswordHash($password, $salt) { 
    $salted_password = base64_decode($salt).$password; 
    $result = hash('SHA1',$salted_password,true); 
    return base64_encode($result); 
} 

當然,這是行不通的。那麼我在這裏做錯了什麼?

這些是測試值:

$salt   = 'Xh2pHwDv3VEUQCvz5qOm7w=='; 
$hashed_value = '0U/kYMz3yCXLsw/r9kocT5zf0cc='; 
$password  = 'Welcome1!'; 

if ($hashed_value === CreatePasswordHash($password,$salt)) { 
    echo "Good job!"; 
} 

編輯:基於從Martyx和休閒褲

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

有一次,我在PHP和C#和C#輸出字母使用SHA1是建議工作的解決方案用大寫字母和PHP用小寫字母。

我建議在C#和PHP中使用相同的編碼(UTF8和UTF16是很好的選擇)。

選擇在C#:

  • Encoding.ASCII.GetBytes
  • Encoding.UTF8.GetBytes
  • ...

編碼PHP:

+0

你的建議是現貨。我需要將密碼轉換爲unicode,而不是產生正確的結果。謝啦! – 2010-08-19 12:31:04

2

您需要告訴PHP使用UTF16和鹽作爲原始字節對密碼字符串進行編碼。