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

标签 c# iphone asp.net-mvc algorithm guid

我正在编写一个驱动 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/

相关文章:

ios - 用于在 Windows 中开发 iOS 应用程序的 Smartface 或 Xamarin

asp.net - 在 Asp.Net MVC Controller 中反序列化 JSON 对象

asp.net-mvc - MVC View 找不到我的扩展方法

c# - 使用 EF Code First 方法在域模型中使用枚举值

c# - ProtoBuf-net 序列化 IEnumerable<T>

c# - 配置缓存类与使用 HTTP header 缓存

c# - 在 Windows 10 上打开手电筒

ios - iOS 9.0.2 更新后的 App "Not Verified"

iphone - 自定义 slider 控件

c# - 在 Silverlight 中获取 VisualState