Convert a SID to String with Java
A Security Identifier (SID) is a unique identifier widely used in Microsoft’s systems, such as identifying users within Windows or within an Active Directory. The SID, a binary value of variable length, can also be represented as a string. This conversion is facilitated by the function
ConvertSidToStringSid, provided by the
Advapi32.dll library, exclusive to Windows.
Therefore, to perform this conversion, one can either use
Advapi32.dll (Windows only) or rewrite the conversion algorithm. Having this conversion implemented in a specific language, like Java, makes it universally usable. After extensive research, I found that most available implementations were incorrect, despite generally working. Hence, I decided to create my own Java implementation, rigorously tested for accuracy.
A string SID follows this format:
This syntax is formally defined using ABNF as follows:
Each field corresponds to a specific byte group in the binary SID, as officially detailed.
The final Java algorithm I implemented is as follows:
This algorithm was extensively tested by generating numerous SIDs and comparing the results with those from the original
Advapi32.dll conversion. For instance, the following test function was used:
You can download the complete code along with tests from the following link: https://gist.github.com/miromannino/04be6a64ea0b5f4d4254bb321e09d628