1

There is the function for sha256 computing:

static string GetHash(string input)
{
   byte[] bytes = Encoding.UTF8.GetBytes(input);  //1

   SHA256 SHA256 = SHA256Managed.Create();
   byte[] hashBytes =  SHA256.ComputeHash(bytes); //2

   var output = BitConverter.ToString(hashBytes); //3
   return output;
}

It gets utf8-bytes from c# string, next it computes hash and returns one as string.

I'am confusing about BitConverter. Its ToString(byte[]) method depends on machine architecture (liitle/big endian). My purpose is providing specific endianess (big-endian) for output string.

How can I do it?

I think it can be like:

byte[] bytes = Encoding.UTF8.GetBytes(input); //1
if (BitConverter.IsLittleEndian)
{
    Array.Reverse(bytes)
}
//..

But I dont' know how UTF8.GetBytes works (UTF8.GetBytes docs doesn't contains anything about endianness). Is it depending on endianness also? If so I suppose it is right way to reverse array after 1 step, is it?

Ilya Loskutov
  • 1,967
  • 2
  • 20
  • 34
  • 1
    A method converting a `byte[]` to a hex `string` should not and can not depend on endianess, which is a property of multi-byte representations of data types. I believe the documentation for `BitConverter.ToString()` is technically inaccurate. The results will be different *if you've obtained that `byte` array from some other method that **is** dependent on endianess*. – Damien_The_Unbeliever Jun 19 '17 at 12:15
  • @Damien_The_Unbeliever is it true UTF8.GetBytes represents c# string always as big-endian array? Then I could call Array.Reverse before 3 step. – Ilya Loskutov Jun 19 '17 at 12:24
  • 1
    **None** of `UTF8.GetBytes()`, `SHA256.ComputeHash()` or `BitConverter.ToString()` are dependent on the machine's endianess. – Damien_The_Unbeliever Jun 19 '17 at 12:26

1 Answers1

1

I think it doesn't matter here because UTF-8 is byte oriented as stated here : Isn’t on big endian machines UTF-8's byte order different than on little endian machines? So why then doesn’t UTF-8 require a BOM?

Jimbot
  • 696
  • 5
  • 20
  • I want to represent output sring as big-endian. There is [difference](https://stackoverflow.com/questions/6107121/bitconverter-vs-tostring-for-hex) – Ilya Loskutov Jun 19 '17 at 12:26
  • @Mergasov - the difference in that question is because of the `BitConverter.GetBytes()` method call, not the `ToString()`. – Damien_The_Unbeliever Jun 19 '17 at 12:30
  • @Damien_The_Unbeliever am I right that the difference between `BitConverter.ToString(BitConverter.GetBytes(...))` and `BitConverter.ToString(Encoding.UTF8.GetBytes(..))` is the first case depends on endianness and the second - not? Even if `BitConverter.ToString`, according doc, does? (as you say it is inaccurate) – Ilya Loskutov Jun 19 '17 at 13:01