代码之家  ›  专栏  ›  技术社区  ›  MidnightThoughtful

模拟编码UUID到base64

  •  2
  • MidnightThoughtful  · 技术社区  · 6 年前

    我试图模拟C应用程序将UUID转换为base64值的方式。出于某种原因,我可以得到部分字符串来匹配预期值,但不能得到整个字符串。

    给出了C代码I:

    public static string ToShortGuid(this Guid newGuid) {
    string modifiedBase64 = Convert.ToBase64String(newGuid.ToByteArray())
    .Replace('+', '-').Replace('/', '_') // avoid invalid URL characters
    .Substring(0, 22);
    return modifiedBase64;
    }
    

    我在python 3.6中的尝试:

    import uuid
    import base64
    
    encode_str = = base64.urlsafe_b64encode(uuid.UUID("fa190535-6b00-4452-8ab1-319c73082b60").bytes)
    print(encode_str)
    

    “fa190535-6b00-4452-8ab1-319c73082b60”是已知的UUID,应用程序显然使用上述C代码生成“nquz gbruksTgccwgrya”的“shortguid”值。

    当我通过python代码处理相同的uuid时,我得到:“-hkfnwsarfkkstgccwgrya==”

    从这两个输出字符串中,此部分匹配:“kstgccwgrya”,但其余部分不匹配。

    2 回复  |  直到 6 年前
        1
  •  5
  •   Aran-Fey Kevin    6 年前

    bytes_le Microsoft's 以下内容:

    base64.urlsafe_b64encode(uuid.UUID("fa190535-6b00-4452-8ab1-319c73082b60").bytes_le)
    

    b'NQUZ-gBrUkSKsTGccwgrYA=='

        2
  •  6
  •   melpomene    6 年前

    NQUZ-gBrUkSKsTGccwgrYA 对应于的字节序列 350519fa006b52448ab1319c73082b60

    如果我们加上 -

     350519fa-006b-5244-8ab1-319c73082b60
    #   \/     \/   \/
    #   /\     /\   /\
     fa190535-6b00-4452-8ab1-319c73082b60
    

    与您开始使用的已知UUID相比,字节是相同的,但前3个子组中的顺序是相反的。

    UUID.bytes_le

    ,请

    另请参见 Why does Guid.ToByteArray() order the bytes the way it does?