1

I'm trying to implement the XTEA algorithm in C#, and I've found a function to do that for me.

However, there's a hurdle I have to pass. The function requires the data and the key be put into a UInt32 array.

For the sake of time, I'll just post the stuff relevant to getting the key into usable format.

Here's what I'm trying to do in C# psuedocode:

            String keyStr = "foobar";
            byte[] keyBytes = Encoding.ASCII.GetBytes(keyStr);
            /* keyBytes = 66, 6F, 6F, 62, 61, 72 (obviously I need to pad it
            out to be followed by i 00's, i = 16 - keyBytes.Length); */

            UInt32[] keyArr = new UInt32[4];
            keyArr[0] = keyBytes[0 to 3];
            keyArr[1] = keyBytes[4 to 7];

I've heard that I need to use Bitwise OR, or something like that, but I'm not totally sure how that works. I've also heard of using BitConverter.ToString, parsing it correctly, then assuming the result is a string: "666F6F62", I can convert THAT into one of the uint32's. But that seems sloppy/lazy/inefficient.

While writing this question I also tried this, maybe it'll clarify even though it doesn't work:

            String keyStr = "foobar"

            byte[] keyBytes = new byte[16];
            Encoding.ASCII.GetBytes(keyStr).CopyTo(keyBytes, 0);

            UInt32[] keyArr = new UInt32[4];

            Buffer.BlockCopy(keyBytes, 0, keyArr[0], 0, 4);

            Console.WriteLine("keyBytes[]: " + BitConverter.ToString(keyBytes));
            Console.WriteLine(keyArr[0].ToString());
Fuselight
  • 554
  • 6
  • 17
  • Does `BitConverter.ToUInt32` not work for you? And what "doesn't work" with `BlockCopy`? – Ben Voigt Apr 12 '15 at 17:47
  • @BenVoigt I totally overlooked that possibility. And my method actually does work, but I forgot to account for endianness. – Fuselight Apr 12 '15 at 17:59

1 Answers1

1

This should do it...

String keyStr = "foobar";

byte[] keyBytes = new byte[16];
Encoding.ASCII.GetBytes(keyStr).CopyTo(keyBytes, 0);

UInt32[] keyArr = new UInt32[4];

if (BitConverter.IsLittleEndian)
    Array.Reverse(keyBytes);

for (int i = 0; i < 4; i++)
    keyArr[i] = BitConverter.ToUInt32(keyBytes, i * 4);

adapted from - https://msdn.microsoft.com/en-us/library/bb384066.aspx

ajg
  • 1,743
  • 12
  • 14