2010-02-03 52 views
5

我需要下面的C#代碼的PHP版本:如何將此C#代碼轉換爲PHP?

string dateSince = "2010-02-01"; 
string siteID = "bash.org"; 
string sharedSecret = "12345"; // the same combination on my luggage! 

using System.Security.Cryptography; 

MD5CryptoServiceProvider x = new MD5CryptoServiceProvider(); 
byte[] dataBytes = System.Text.Encoding.ASCII.GetBytes(string.Format("{0}{1}{2}", dateSince, siteID, sharedSecret)); 
string result = BitConverter.ToString(x.ComputeHash(dataBytes)); 

...這個代碼片段似乎是不完整的。但這是我的想法:

  1. concatenating dateSince,siteID和sharedSecret。偷內褲。

  2. ???

  3. 將該字符串轉換爲ascii編碼的字節數組。

  4. 獲取該數組的MD5散列值。

這個神祕的BitConverter對象似乎是將該MD5散列數組轉換爲一串十六進制數字。根據上述文件,結果的值應該如下所示:「6D-E9-9A-B6-73-D8-10-79-BC-4F-EE-51-A4-84-15-D8」

任何幫助非常感謝!


忘記包含此更早。這裏是我寫到目前爲止的PHP版本:

$date_since = "2010-02-01"; 
$site_id = "bash.org"; 
$shared_secret = "12345"; 

$initial_token = $date_since.$site_id.$shared_secret; 

$ascii_version = array(); 
foreach($i=0; $i < strlen($initial_token); $i++) { 
    $ascii_version[] = ord(substr($initial_token,$i,1)); 
} 

$md5_version = md5(join("", $ascii_version)); 

$hexadecimal_bits = array(); 
foreach($i=0; $i < strlen($md5_version); $i++) { 
    // @todo convert to hexadecimal here? 
    $hexadecimal_bits[] = bin2hex(substr($md5_version,$i,1)); 
} 

$result = join("-", $hexadecimal_bits); 
+0

請發佈您迄今爲止編寫的代碼。人們通常不喜歡只爲你寫代碼。 – 2010-02-03 01:35:06

+0

啊,對不起,我剛來這地方。一會兒......。 – sayajay 2010-02-03 01:46:04

+0

+1與您的行李一樣。 – benjy 2010-02-03 02:27:02

回答

1

我認爲這會對你有用。它看起來像MD5CryptoServiceProvider :: ComputeHash方法返回一個16字節的數組,而不是像普通的PHP md5()函數一樣的32個字符的字符串。但是,PHP的md5()具有第二個可選參數,該參數強制「原始輸出」,其中確實對應於ComputeHash()的輸出

$date_since = "2010-02-01"; 
$site_id = "bash.org"; 
$shared_secret = "12345"; 
$initial_token = $date_since.$site_id.$shared_secret; 

//get the RAW FORMAT md5 hash 
//corresponds to the output of MD5CryptoServiceProvider::ComputeHash 
$str = md5($initial_token, true); 
$len = strlen($str); 
$hex = array(); 
for($i = 0; $i < $len; $i++) { 
    //convert the byte to a hex string representation (left padded with zeros) 
    $hex[] = str_pad(dechex(ord($str[$i])), 2, '0', STR_PAD_LEFT); 
} 
//dump output 
echo implode("-",$hex); 

//outputs fe-0d-58-fd-5f-3d-83-fe-0f-6a-02-b4-94-0c-aa-7b 
+0

感謝您的解釋!現在它變得更有意義。你是一個很棒的幫手。對此,我真的非常感激。 – sayajay 2010-02-03 06:03:52

+0

Np,很高興幫助。 – zombat 2010-02-03 06:38:56

0

這是我所看到的,除了它輸出的內容不會輸入破折號。那些必須以其他方式注入。

var $dateSince = "2010-02-01"; 
var $siteID = "bash.org"; 
var $sharedSecret = "12345"; // the same combination on my luggage! 

var $full_string = $dateSince . $siteID . $sharedSecret; 

string result = md5($full_string);