1

I am trying to reproduce the result of a PHP pack('H40',$string) function. So far i got good results but slightly different. Here is what i tried

PHP Code

<?php
function test(){
   $packed = pack('H40',"42d5abcd859afd2cc0f6b6f8cc2a9cd41f66a120");
   return $packed;
}
echo test();
?> 

C# Code:

private void test(){
    string result = PackH40("42d5abcd859afd2cc0f6b6f8cc2a9cd41f66a120");
}
private string PackH40(string input)
{
    string result = string.Empty;
    input = input.Replace("-", " ");
    byte[] hashBytes = new byte[input.Length / 2];
    for (int i = 0; i < hashBytes.Length; i++)
    {
        hashBytes[i] = Convert.ToByte(input.Substring(i * 2, 2), 16);
    }
    return Encoding.UTF8.GetString(hashBytes);
}

The results look similar in browser but if you write them to a file they are not equal. So far i tried every Encoding for the C# output and nothing. What am i doing wrong?

Edit: I tried the approach in Trying to reproduce PHP's pack("H*") function in C# the issue is similar and in this case did not help me.

Resolved: Major problem was that i wanted to 'see' the data and compare it. I was terribly wrong! Converted all to byte[] and it worked like a charm !

  • Does this answer your question? [Trying to reproduce PHP's pack("H\*") function in C#](https://stackoverflow.com/questions/20508193/trying-to-reproduce-phps-packh-function-in-c-sharp) – jira May 17 '20 at 13:40
  • I tried exactly that approach and in this case it is not the answer. Not sure if H40 is somehow different. – Svetoslav Angelov May 17 '20 at 13:54
  • I just tried two things. First i did base64string conversions on both sides and they matched! Second i did all bytes to string conversion and they match as well. My guess is the Encoding when i convert them back to string. I will investigate this further. – Svetoslav Angelov May 17 '20 at 14:38

0 Answers0