J Weezy
J Weezy

Reputation: 3957

C# Convert Active Directory Hexadecimal to GUID

We are pushing AD objects to a 3rd party vendor where the objectGUID attribute is outputted as hexadecimal, as seen in the Attribute Editor window. We need to be able to convert the hexadecimal back to GUID format so that we can perform lookups against the database.

Is it possible to convert hexadecimal back to GUID format? In all likelihood, the hexadecimal will come back in string format.

Example:

Hexadecimal: EC 14 70 17 FD FF 0D 40 BC 03 71 A8 C5 D9 E3 02
or
Hexadecimal (string): ec147017fdff0d40bc0371a8c5d9e302

GUID: 177014EC-FFFD-400D-BC03-71A8C5D9E302

Update

After accepting the answer, I can validate it using some code from Microsoft See here: Guid.ToByteArray Method

using System;

namespace ConsoleApp3
{
    class Program
    {
        static void Main()
        {
            // https://stackoverflow.com/questions/56638890/c-sharp-convert-active-directory-hexadecimal-to-guid
            byte[] bytearray = StringToByteArray("ec147017fdff0d40bc0371a8c5d9e302");

            // https://learn.microsoft.com/en-us/dotnet/api/system.guid.tobytearray?view=netframework-4.8
            Guid guid = new Guid(bytearray);
            Console.WriteLine("Guid: {0}", guid);
            Byte[] bytes = guid.ToByteArray();
            foreach (var byt in bytes)
                Console.Write("{0:X2} ", byt);

            Console.WriteLine();
            Guid guid2 = new Guid(bytes);
            Console.WriteLine("Guid: {0} (Same as First Guid: {1})", guid2, guid2.Equals(guid));
            Console.ReadLine();

        }

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

Upvotes: 4

Views: 1586

Answers (1)

Joshua Robinson
Joshua Robinson

Reputation: 3549

Guid has a constructor which takes a byte array

You can convert the hexadecimal string into a byte array and use that to construct a new Guid.

If you need to know how to convert the hexadecimal string to a byte array, Stack Overflow already has a few answers to that question.

From the accepted answer of that question:

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

Upvotes: 3

Related Questions