php гексобин не работает точно в c# - PullRequest
0 голосов
/ 06 февраля 2020

У меня следующий php код, я не могу написать c# код, который точно работает как php. Выглядит там разные кодировки. Мне нужно написать c# код, который дает результат как php код

Мой php код

echo hexbin('246439589af7f1d84eb638c995687d53');


    function hexbin($hexdata) {
      $bindata="";

      for ($i=0;$i<strlen($hexdata);$i+=2) {
        echo hexdec(substr($hexdata,$i,2)) ;

        $bindata.=chr(hexdec(substr($hexdata,$i,2)));
      }
      echo "<br>";
      return $bindata;
    }

Вывод

361005788154247241216781825620114910412583
$d9X����N�8ɕh}S

Мой c# код

public static void Main()
    {
        HexToBin("246439589af7f1d84eb638c995687d53");
    }

    static String HexToBin(string hexdata)
    {
        String bindata="";
        for (int i=0;i<hexdata.Length;i+=2) {
           Console.Write(Convert.ToInt64(hexdata.Substring(i,2), 16));
           bindata+= Convert.ToChar(Convert.ToInt64(hexdata.Substring(i,2), 16)).ToString();
        }
        Console.WriteLine();
        Console.WriteLine(bindata);
        return bindata;
    }

Выход

361005788154247241216781825620114910412583
$d9X÷ñØN¶8Éh}S

I, m, вычисление hash_ma c в следующем коде, который дает различный вывод

in php

hash_hmac('SHA1','123456', hexbin('246439589af7f1d84eb638c995687d53'));

в c#

static void hash_mac()
        {
           string  message = "123456";
            var keyByte = encoding.GetBytes(HexToBin("246439589af7f1d84eb638c995687d53"));
            using (var hmacsha1 = new System.Security.Cryptography.HMACSHA1(keyByte))
            {
                hmacsha1.ComputeHash(encoding.GetBytes(message));

                Console.WriteLine("Result: {0}", ByteToString(hmacsha1.Hash));
            }
        }

1 Ответ

1 голос
/ 06 февраля 2020

После подсказок Longoon12000 я исправил код со следующим code.Storing и использовал его как байты. Это работает, как мне нужно

static void hash_mac()
        {
            message = "123456";
            using (var hmacsha256 = new System.Security.Cryptography.HMACSHA1(StringToByteArray("246439589af7f1d84eb638c995687d53")))
            {
                hmacsha256.ComputeHash(encoding.GetBytes(message));

                Console.WriteLine("Result: {0}", ByteToString(hmacsha256.Hash));
            }
        }


        public static byte[] StringToByteArray(String hex)
        {
            int NumberChars = hex.Length;
            byte[] bytes = new byte[NumberChars / 2];
            for (int i = 0; i < NumberChars; i += 2)
                bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
            return bytes;
        }
...