【问题标题】:php hextobin not works exactly in c#php hextobin 在 c# 中不完全有效
【发布时间】:2020-02-06 12:50:55
【问题描述】:

我有以下 php 代码,我无法编写与 php 完全相同的 c# 代码。看起来有不同的编码。我需要编写 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

我在下面的代码中计算 hash_mac,给出不同的输出

在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));
            }
        }

【问题讨论】:

  • 输出是一样的,只是你的 php 输出与你的 c# 输出有不同的编码(例如,一个使用 ascii,另一个使用 utf8,或类似的东西)。如果您使用的是二进制数据,则不应将其存储在字符串中,而应将其存储在字节[]中。
  • 但是在我计算hash_hmac这个函数之后,它给出了不同的结果
  • @Longoon12000 谢谢!!!! 4-5 小时寻找解决方案

标签: c# php encoding ascii chr


【解决方案1】:

在 Longoon12000 的帮助下,我用以下代码修复了一个代码。存储并将其用作字节。 它按我的需要工作

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;
        }

【讨论】:

    猜你喜欢
    • 2018-04-14
    • 1970-01-01
    • 2022-12-28
    • 2017-06-10
    • 2013-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多