2009-11-13 216 views
1

我試圖將這段代碼從PHP轉換爲C#。它是Captive Portal的一部分。有人可以解釋它的作用嗎?將PHP加密代碼轉換爲C#

$hexchal = pack ("H32", $challenge); 
    if ($uamsecret) { 
    $newchal = pack ("H*", md5($hexchal . $uamsecret)); 
    } else { 
    $newchal = $hexchal; 
    } 
    $response = md5("\0" . $password . $newchal); 
    $newpwd = pack("a32", $password); 
    $pappassword = implode ("", unpack("H32", ($newpwd^$newchal))); 
+0

我沒有看到任何加密離開這裏...有沒有辦法解密它,因爲散列步驟 – 2009-11-13 02:35:42

+2

他不想解密它,只是將代碼移植到C# – RageZ 2009-11-13 02:39:45

+2

我知道,我只是指出了一個不正確的使用術語「加密「... – 2009-11-13 03:25:22

回答

2

愛德華多,

如果你看看在 pack手動

pack用於在(十六進制,八進制,二進制)字符串轉換爲他的號碼錶示。

所以

$hexcal = pack('H32', $challenge); 

想 'cca86bc64ec5889345c4c3d8dfc7ade9' 實際0xcca ...字符串轉換DE9

如果$ uamsecret存在與hexchal concacteate與uamsecret的MD5做同樣的事情。 ($ uamsecret){ $ newchal = pack(「H *」,md5($ hexchal。$ uamsecret)); } else { $ newchal = $ hexchal; }

$response = md5("\0" . $password . $newchal); 

MD% '\ 0' + $密碼+ $ newchal

$newpwd = pack("a32", $password); 

password到32字節

$pappassword = implode ("", unpack("H32", ($newpwd^$newchal))); 

做XOR newpwdnewchal並將其轉換爲一個十六進制字符串,我沒有得到implode()也許它是將字符串轉換爲一個字符數組。

+0

謝謝RageZ。你可以發佈這些包結果的輸入/輸出示例嗎? – Eduardo 2009-11-14 00:42:50

1

我也遇到了php的pack-unpack函數在c#中的需求,但沒有得到任何好的資源。

所以我想自己做。我使用onlinephpfunctions.com上的pack/unpack/md5方法驗證了函數的輸入。因爲我只按照我的要求完成代碼。這可以擴展爲其他格式

private static string pack(string input) 
    { 
     //only for H32 & H* 
     return Encoding.Default.GetString(FromHex(input)); 
    } 
    public static byte[] FromHex(string hex) 
    { 
     hex = hex.Replace("-", ""); 
     byte[] raw = new byte[hex.Length/2]; 
     for (int i = 0; i < raw.Length; i++) 
     { 
      raw[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16); 
     } 
     return raw; 
    } 

MD5

private static string md5(string input) 
    { 
     byte[] asciiBytes = Encoding.Default.GetBytes(input); 
     byte[] hashedBytes = MD5CryptoServiceProvider.Create().ComputeHash(asciiBytes); 
     string hashedString = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower(); 
     return hashedString; 
    } 

拆開

private static string unpack(string p1, string input) 
    { 
     StringBuilder output = new StringBuilder(); 

     for (int i = 0; i < input.Length; i++) 
     { 
      string a = Convert.ToInt32(input[i]).ToString("X"); 
      output.Append(a); 
     } 

     return output.ToString(); 
    }