C#将Active Directory十六进制转换为GUID

时间:2019-06-17 21:03:10

标签: c# powershell active-directory data-conversion

我们正在将AD对象推送给第三方供应商,在该供应商中objectGUID属性以十六进制形式输出,如“属性编辑器”窗口中所见。我们需要能够将十六进制转换回GUID格式,以便我们可以对数据库执行查找。

是否可以将十六进制转换回GUID格式?十六进制很可能会以字符串格式返回。

示例:

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

更新

接受答案后,我可以使用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://docs.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;
        }
    }

1 个答案:

答案 0 :(得分:1)

Guid has a constructor which takes a byte array

您可以将十六进制string转换为字节数组,然后使用该数组来构造新的Guid

如果您需要了解如何将十六进制字符串转换为字节数组,请Stack Overflow already has a few answers to 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;
}