2013-03-10 288 views
1
<?php 
$pwd = "test"; 
$crypted = base64_encode(pack("H*", sha1(utf8_encode($pwd)))); 
echo("$crypted"); 
?> 

因此,我得到了上面這個PHP代碼,我試圖將它轉換爲C#代碼。我試過以下,但它沒有相同的輸出。將PHP代碼轉換爲C#代碼

var bytes = Encoding.UTF8.GetBytes("test"); 
      SHA1 sha = new SHA1CryptoServiceProvider(); 
      var result = sha.ComputeHash(bytes); 
      string hex = Encoding.UTF8.GetString(result, 0, result.Length); 
      byte[] packH = PackH(hex); 
      var base64String = Convert.ToBase64String(packH); 

和方法:

public static byte[] PackH(string hex) 
     { 
      if ((hex.Length % 2) == 1) hex += '0'; 
      var bytes = new byte[hex.Length/2]; 
      for (int i = 0; i < hex.Length; i += 2) 
      { 
       bytes[i/2] = Convert.ToByte(hex.Substring(i, 2), 16); 
      } 
      return bytes; 
     } 

因爲我沒有足夠的信譽來回答我的問題,我將在這裏寫下了答案:d

It seems that i needed to do some extra things:D 

    public static string Crypt(string data) 
      { 
       SHA1 sha = new SHA1Managed(); 
       byte[] buffer = Encoding.UTF8.GetBytes(data); 
       byte[] computeHash = sha.ComputeHash(buffer); 

       string delimitedHexHash = BitConverter.ToString(computeHash); 
       string hexHash = delimitedHexHash.Replace("-", ""); 
       byte[] packH = PackH(hexHash); 
       return Convert.ToBase64String(packH); 
      } 

      public static byte[] PackH(string hex) 
      { 
       if ((hex.Length%2) == 1) hex += '0'; 
       var bytes = new byte[hex.Length/2]; 
       for (int i = 0; i < hex.Length; i += 2) 
       { 
        bytes[i/2] = Convert.ToByte(hex.Substring(i, 2), 16); 
       } 
       return bytes; 
      } 

甚至easyier

Console.WriteLine(Convert.ToBase64String(new SHA1CryptoServiceProvider().ComputeHash(Encoding.ASCII.GetBytes("root")))); 
+5

爲什麼不開始比較逐步比較值,並確切地看到什麼失敗? – Tchoupi 2013-03-10 17:32:17

+0

看起來你沒有實現一個等效的包函數,也許這將有助於:http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/ca080d6e-0707-4030-a3c7-462d5903b5f8 – Mark 2013-03-10 17:34:37

回答

3

它看起來像在PHP版本中,在你使用base64編碼之前,你也在SHA1函數的輸出上調用pack

如果我正確解釋PHP版本,您基本上首先對SHA1哈希的輸出進行十六進制編碼,然後對Base編碼的十六進制編碼的字符串進行編碼 - 這與Base64編碼SHA1的輸出不同直接散列這是在C#版本中發生的事情。

+1

那麼,對不起,這是一個錯字,但仍然不起作用 – 2013-03-10 17:34:19

+1

+1很好的答案:p – Tchoupi 2013-03-10 17:46:03

+0

謝謝..你的評論是現貨! – 2013-03-10 17:47:17