簡體   English   中英

C# 解碼 Active Directory SID 第三位數字解碼不正確。 其他都對

[英]C# Decoding Active Directory SID third digit being decoded incorrectly. All other's correct

我從 Active Directory 中檢索了一個objectsid值。 它以 base64 編碼的字符串形式出現。

我有以下 function(下方)將其解碼為實際的 SID 文本字符串。

以下 function 在所有情況下都可以正常工作,除了少數.

在 Active Directory 屬性編輯器中檢查時,返回的 SID 為“S- 1-5 -21-3477787073-812361429-1014394821”,而不是“S- 1-4-21-3477787073-812361429-1014394821 ”。 第三位數字相差一位。

同樣,“S-1- 5 -32-573”的 SID 返回為“S-1- 2 -32-573”,第三個數字再次減去 3。

我已經對它進行了足夠的調試,發現是 byte[] 數組的長度不同,我認為這是導致此錯誤的原因。

當字節數組為 28 位時,它可以正確解碼。 如果它短於 28 位,則第三個 SID 數字直接與 byte[] 數組短多少有關。

我認為 for() 循環條件i < bytes[7]有一些問題,盡管byte[7]在所有情況下似乎總是5 (至少在我設置斷點的情況下)。

或者可能是 BitConverter 的第二個參數(8 + (i * 4)) 如果byte[7]總是5,那么(5*4) + 8 = 28。而當byte數組為28位時,返回值總是正確的。 就是當byte[]數組小於28位時,返回值是錯誤的。

我沒有寫這個 function(在另一個堆棧溢出問題的答案中找到),所以除了我在這里描述的內容之外,我真的不明白它在做什么。 我確實添加了代碼注釋。

public static string Base64DecodeSID(string data) {

if (data == "") {
    return "";
}

byte[] bytes = Convert.FromBase64String(data);

try {

    string sid = "S-" + bytes[0].ToString();                                        // Add SID revision.

    if (bytes[6] != 0 || bytes[5] != 0) {                                           // SID authority

        sid += ("-" +
            String.Format(                                                          // Left 0-pad hex
                "0x{0:2x}{1:2x}{2:2x}{3:2x}{4:2x}{5:2x}",                           // values to 2 places.
                bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6]
            )
        );

    } else {
        sid += ("-" + (bytes[1] + (bytes[2] << 8) + (bytes[3] << 16) + (bytes[4] << 24)).ToString());
    }

    for (int i = 0; i < bytes[7]; i++) {                                            // Sub-Authority...
        sid += ("-" + BitConverter.ToUInt32(bytes, 8 + (i * 4)).ToString()); 
        
    }

    return sid;

}

(為簡潔起見,我排除了 catch() )

例子

Base64: "AQQAAAAAAAUVAAAAwdFKz9WmazDFb3Y8"

解碼后的 byte[] 數組:

[00] 1
[01] 4
[02] 0
[03] 0
[04] 0
[05] 0
[06] 0
[07] 5
[08] 21
[09] 0
[10] 0
[11] 0
[12] 193
[13] 209
[14] 74
[15] 207
[16] 213
[17] 166
[18] 107
[19] 48
[20] 197
[21] 111
[22] 118
[23] 60

預期返回值:“S-1- 5 -21-3477787073-812361429-1014394821”

實際返回值:“S-1- 4 -21-3477787073-812361429-1014394821”

知道如何解決這個問題嗎? 我是否需要將數組填充到 28 位甚至 32 位?

如評論中所述, SecurityIdentifier class 使這變得容易:

public static string Base64DecodeSID(string data) {

    var bytes = Convert.FromBase64String(data);
    
    var sid = new SecurityIdentifier(bytes, 0);
    
    return sid.Value;
}

您可能想在其中添加一些錯誤檢查,以防它傳遞了錯誤的值。

調用Base64DecodeSID("AQQAAAAAAAUVAAAAwdFKz9WmazDFb3Y8")返回S-1-5-21-3477787073-812361429-1014394821

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM