集册 Java实例教程 二进制Sid到字符串Sid

二进制Sid到字符串Sid

欢马劈雪     最近更新时间:2020-01-02 10:19:05

504
二进制Sid到字符串Sid
//时代Java公众号

//package com.nowjava;


public class Main {

    public static String binarySidToStringSid(String SID) {

        // A SID is max 28 bytes - http://msdn.microsoft.com/en-us/library/cc221018%28v=PROT.13%29.aspx

        // However the RID/SubAuthority is a variable length list of 16 byte additional chunks

        // https://msdn.microsoft.com/en-us/library/cc230371.aspx and https://msdn.microsoft.com/en-us/library/gg465313.aspx

        byte[] bytes = new byte[SID.length() / 3];

        int byteNum = 0;


        // parse unsigned SID represented as \01\05\00\00\00\00\00\05\15\00\00\00\dc\2f\15\0b\e5\76\d3\8c\be\0b\4e\be\01\02\00\00

        // into corresponding signed byte array (in Java bytes are signed so we need to do a little fancy footwork)

        for (int i = 0; i < SID.length(); i++) {

            char c = SID.charAt(i);/*来 自 NowJava.com*/


            if (c == '\\') {

                int highByte = Character.digit(SID.charAt(++i), 16);

                int lowByte = Character.digit(SID.charAt(++i), 16);


                int value = 16 * highByte + lowByte;


                // convert the byte to a signed value, Java requires this since byte is signed

                if (value < 128)

                    bytes[byteNum++] = (byte) value;

                else

                    bytes[byteNum++] = (byte) (value - 256);

            }

        }


        return binarySidToStringSid(bytes);

    }


    public static String binarySidToStringSid(byte[] SID) {

        StringBuilder strSID = new StringBuilder("S-");


        // bytes[0] : in the array is the version (must be 1 but might

        // change in the future)

        strSID.append(SID[0]).append('-');


        // bytes[2..7] : the Authority

        StringBuilder tmpBuff = new StringBuilder();

        for (int t = 2; t <= 7; t++) {

            String hexString = Integer.toHexString(SID[t] & 0xFF);

            tmpBuff.append(hexString);

        }

        strSID.append(Long.parseLong(tmpBuff.toString(), 16));


        // bytes[1] : the sub authorities count

        int count = SID[1];


        // bytes[8..end] : the sub authorities (these are Integers - notice

        // the endian)

        for (int i = 0; i < count; i++) {

            
展开阅读全文