我正在尝试模拟 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;
}
我在 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-gBrUkSKsTGccwgrYA”的“ShortGuid”值。
当我通过 Python 代码处理相同的 UUID 时,我得到:“-hkFNWsARFKKsTGccwgrYA==”
从这两个输出字符串中,这部分匹配:“KsTGccwgrYA”,但其余部分不匹配。
最佳答案
NQUZ-gBrUkSKsTGccwgrYA
对应一个字节序列350519fa006b52448ab1319c73082b60
。
如果我们在适当的位置添加-
,我们得到:
350519fa-006b-5244-8ab1-319c73082b60
# \/ \/ \/
# /\ /\ /\
fa190535-6b00-4452-8ab1-319c73082b60
与您开始使用的已知 UUID 相比,字节相同,但前 3 个子组中的顺序相反。
要模拟 .NET 的功能,您需要使用 UUID.bytes_le :
The UUID as a 16-byte string (with time_low, time_mid, and time_hi_version in little-endian byte order).
另见 Why does Guid.ToByteArray() order the bytes the way it does?
关于python - 模拟将 UUID 编码为 Base64,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51114707/