gpt4 book ai didi

C# 从 Guid 结合 40Char 十六进制字符串 (UUID) 创建一个 Auth Token

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:20:23 24 4
gpt4 key购买 nike

我正在编写一个驱动 iPhone 应用程序的 asp.net MVC 应用程序。

我希望 Iphone 向我发送它的 UUID,如下所示:

2b6f0cc904d137be2e1730235f5664094b831186

在服务器上我想生成一个 Guid:

466853EB-157D-4795-B4D4-32658D85A0E0

在 Iphone 和服务器上,我需要一个简单的算法来将这 2 个值组合成一个可以传递的 Auth token 。 IPhone 和 ASP.NET MVC 应用程序都需要能够根据 UUID 和 GUID 反复计算值。

所以这需要是一个简单的算法,没有来自 .net 框架的库。

这里有完整的解决方案

        public void Test()
{
var DeviceId = Guid.NewGuid();
var newId = "2b6f0cc904d137be2e1730235f5664094b831186";

var guidBytes = DeviceId.ToByteArray();
var iphoneBytes = StringToByteArray(newId);
byte[] xor = new byte[guidBytes.Length];

for (int i=0;i<guidBytes.Length;i++)
{
xor[i] = (byte) (guidBytes[i] ^ iphoneBytes[i]);
}

var result = ByteArrayToString(xor);
}

public static byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes;
}

public static string ByteArrayToString(byte[] ba)
{
StringBuilder hex = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)
hex.AppendFormat("{0:x2}", b);
return hex.ToString();
}

最佳答案

好吧,iPhone ID 看起来像一个十六进制字符串,因此应该将两者都转换为二进制并对字节进行异或运算。您可以根据需要将结果存储为数组、十六进制字符串或 base-64 编码字符串。

然而,您将其称为“授权 token ”的方式有点令人担忧。 session ID 必须不可预测。您可能会考虑在服务器上生成一组加密随机数据而不是 GUID。

编辑

// Convert the server GUID to a byte array.
byte[] guidBytes = severGuid.ToByteArray();

// Convert the iPhone device ID to an array
byte[] idBytes = StringToByteArray(iPhoneId);

遗憾的是,似乎 .NET 没有内置的方法来与十六进制字符串相互转换,但之前已经讨论过这个主题:Convert byte array to hex string and vice versa

// Once you've XORed the bytes, conver the result to a string.
string outputString = ByteArrayToString(outputBytes);

关于C# 从 Guid 结合 40Char 十六进制字符串 (UUID) 创建一个 Auth Token,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3484097/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com