我如何将这个C#代码翻译成PHP?

say*_*jay 5 php c# porting

我需要以下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));
Run Code Online (Sandbox Code Playgroud)

...此代码段似乎不完整.但这就是我的想法:

  1. 连接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);
Run Code Online (Sandbox Code Playgroud)

zom*_*bat 1

我认为这对你有用。看起来 MD5CryptoServiceProvider::ComputeHash 方法返回一个 16 字节的数组,而不是像普通 PHPmd5()函数那样返回 32 个字符的字符串。然而,PHPmd5()有第二个可选参数强制“原始输出”,它确实对应于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
Run Code Online (Sandbox Code Playgroud)