将PHP代码转换为C#代码

时间:2013-03-10 17:29:52

标签: c# php

<?php 
$pwd = "test"; 
$crypted = base64_encode(pack("H*", sha1(utf8_encode($pwd)))); 
echo("$crypted"); 
?>

所以我上面得到了这个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;
            }

甚至更容易

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

1 个答案:

答案 0 :(得分:3)

在您使用base64编码之前,在PHP版本中,您似乎也在SHA1函数的输出上调用pack

如果我正确解释PHP版本,你基本上首先对SHA1哈希的输出进行十六进制编码,然后你对Base64编码十六进制编码的字符串 - 这与编码SHA1哈希输出的Base64编码不同直接就是C#版本中发生的事情..