Thread: C# Some Math

1. C# Some Math

Okay I am screwing around with web sockets and am trying to negotiate a connection but I have to do some math to generate a proper negotiation.

draft-ietf-hybi-thewebsocketprotocol-03 - The WebSocket protocol That is the RFC I am referencing.

Okay I have the following information:
Code:
```Key1: 18x 6]8vM;54 *(5:  {   U1]8  z [  8
Key2: 1_ tx7X d  <  nw  334J702) 7]o}` 0
Final: Tm[K T2u```
First step is removing all non-numeric characters from key1 and key 2 leaving me with.

Code:
```Key1: 1868545188
Key2: 1733470270```
I used a simple regex for that [^[0-9]] that worked fine

Next I have to calculate the spaces in the original key1 and key 2 which I did sucesfully with a foreach statement.

Key1 spaces = 12
Key2 spaces = 10

Now heres the part I am not sure of and need help on. I need to divide the key1 number by the number of spaces

1868545188 / 12 155712099
1733470270 / 10 173347027

I need to express each of these output as Big Endian 32 bit numbers? Does that mean flip them? how would I do that in C#.

After that I concatenate the two numbers with the Final and get the md5 sum of that. Again how do I do this in c#. I am currently doing it this way:
Code:
```MD5CryptoServiceProvider x = new MD5CryptoServiceProvider();
byte[] output = x.ComputeHash(input);
string MD5Output = ASCIIEncoding.UTF8.GetString(output);```
If you guys could help me out I would appreciate it. Note the final outcome of those calculations should be a 16 byte 128 bit value, which in this case is: fQJ,fN/4F4!~K~MH

2. I need to express each of these output as Big Endian 32 bit numbers? Does that mean flip them? how would I do that in C#.
Use BitConverter.GetBytes, reverse the array and put it back to an int (or not, depending on what you want to do next):

Code:
```int value;
if (BitConverter.IsLittleEndian)
{
byte[] temp = BitConverter.GetBytes(155712099);
Array.Reverse(temp);
value = BitConverter.ToInt32(temp);
}```
After that I concatenate the two numbers with the Final and get the md5 sum of that. Again how do I do this in c#
See the System.Security.Cryptography.MD5 class

3. Yes, reversing the arrays for the two ints is required.

Just a small point, but if you're already looping through the chars of each key to count the spaces, you could use that same loop to check for numbers.

Code:
```        static int NumberFromKey(String key, out int spaces)
{
spaces = 0;
String str = String.Empty;

// why bother with regex if you're already looping to count spaces?
foreach (char c in key.ToCharArray())
if (c == ' ')
spaces++;
else if (Char.IsDigit(c))
str += c.ToString();

return int.Parse(str);
}```

Popular pages Recent additions