How to convert objectSID value in Active Directory from binary form to string (SDDL representation)
This posting is provided "AS IS" with no warranties, and confers no rights. Use of included script samples are subject to the terms specified at http://www.microsoft.com/info/cpyright.htm
Recently I have been working on a project in where I was extracting some data from Active Directory into a SQL table. One of the attributes that I wanted to get from AD was objectSID (this attribute uniquely identifies an object in a domain). ObjectSID is stored in AD as a binary value, but in order for it to be useful in my application I wanted to convert it to string representation, so that I could later conduct searches against it. I searched the web, posted on MSDN ADSI forum but could not really find an elegant solution that would easily accomplish this task.
Basically before .NET 2.0 the only way to convert objectSID to a string was by using win32 API called ConvertSidToStringSid. Here is a link to the pinvoke.net site, which provies examples on how to call this API from your .NET code.
But of couse, my preference would be to use managed code, as oppoesed going through win32 API, plus I knew that there must have been a more elegant way to perform this task, since this should be probably a very common operaton for folks working with AD. Anyway, I am currenlty reading an excellent book by Stefan Schackow “Professional ASP.NET 2.0 Security, Membership, and Role Management”, and in there I stumbled on a piece of code where author was using SecurityIdentifier class in one of his examples. I did some further searching on this class in .NET documentation and was very happy to find out that this class allows us to easly (2 lines of code) convert objectSID from binary to string.
Here is how to do this:
public static string SIDtoString(byte sidBinary)
SecurityIdentifier sid = new SecurityIdentifier(sidBinary, 0);