将UUID编码为Base64

Mid*_*ful 2 .net python uuid

我试图模仿C#应用程序将UUID转换为Base64值的方式.出于某种原因,我可以获得字符串的一部分以匹配预期值,但不是整个字符串.

我得到的C#代码:

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

我在Python 3.6中尝试过的:

import uuid
import base64

encode_str = = base64.urlsafe_b64encode(uuid.UUID("fa190535-6b00-4452-8ab1-319c73082b60").bytes)
print(encode_str)
Run Code Online (Sandbox Code Playgroud)

"fa190535-6b00-4452-8ab1-319c73082b60"是已知的UUID,该应用程序显然使用上述c#代码生成"NQUZ-gBrUkSKsTGccwgrYA"的"ShortGuid"值.

当我通过我的Python代码处理相同的UUID时,我得到:" - hkFNWsARFKKsTGccwgrYA =="

从这两个输出字符串中,此部分匹配:"KsTGccwgrYA",但其余部分不匹配.

mel*_*ene 6

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

如果我们添加-适当的位置,我们会得到:

 350519fa-006b-5244-8ab1-319c73082b60
#   \/     \/   \/
#   /\     /\   /\
 fa190535-6b00-4452-8ab1-319c73082b60
Run Code Online (Sandbox Code Playgroud)

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

要模拟.NET的功能,您需要使用UUID.bytes_le:

UUID为16字节字符串(以little-endian字节顺序的time_low,time_midtime_hi_version).

另请参阅为什么Guid.ToByteArray()按照它的方式对字节进行排序?


Joh*_*nck 5

您需要使用bytes_le以获得与Microsoft的匹配的字节顺序:

base64.urlsafe_b64encode(uuid.UUID("fa190535-6b00-4452-8ab1-319c73082b60").bytes_le)
Run Code Online (Sandbox Code Playgroud)

这给了b'NQUZ-gBrUkSKsTGccwgrYA=='.