I’m writing a service that will fetch users from Active Directory server (on-premise, but I am not sure if this is relevant)
The code is written in C#.
I’m using an LDAP connection like this:
var authType = AuthType.Basic;
var connection = new LdapConnection(
new LdapDirectoryIdentifier(hostNameOrIP, portNumber),
new System.Net.NetworkCredential(userName, password, domain), authType);
connection.SessionOptions.ProtocolVersion = 3;
connection.Bind();
I can get Users from Active Directory, but when I try to parse the “objectguid” attribute from a user from Base64 to string I get “junk”
"objectguid": [
"jNXa6wSDYU6cy4peVH8GuQ=="
],
I read this post: /questions/74153453/how-to-get-objectsid-value-programmaticaly-from-active-directory
and I understand that the objectguid is a value in binary and base64 encoded
I tried to convert the script in the post to C# using chatGPT and i got this code:
```
private void Test()
{
try
{
string base64ObjectSid = "jNXa6wSDYU6cy4peVH8GuQ==";
// Decode base64 to byte array
byte[] objectSidBytes = Convert.FromBase64String(base64ObjectSid);
// Extract components from the byte array
int revision = objectSidBytes[0];
int subAuthorityCount = objectSidBytes[1];
// Construct the SID string
string sidString = $"S-{revision}-{objectSidBytes[7]}";
for (int i = 0; i < subAuthorityCount; i++)
{
int subAuthorityStartIndex = 8 + i * 4;
uint subAuthorityValue = BitConverter.ToUInt32(objectSidBytes, subAuthorityStartIndex);
sidString += $"-{subAuthorityValue}";
}
Console.WriteLine($"UserName: {userName}, Decoded SID: {sidString}");
}
catch (Exception ex)
{
string err = ex.ToString();
}
}
but it doesn't work. I get an exception :
{"Index was out of range. It must be non-negative and less than the size of the collection. (Parameter 'startIndex')"}
Does anyone know how to parse the "objectguid" value from AD to a readable string?
thanks