C#从Guid创建一个Auth Token并结合40Char Hex string(UUID)

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

我希望Iphone发送给我的UUID看起来像这样:

2b6f0cc904d137be2e1730235f5664094b831186

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

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

在Iphone和服务器上,我需要一个简单的方法来将这两个值组合成一个可以传递的Auth令牌。 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看起来像一个hex字符串,所以转换为二进制和XORing字节应该这样做。 您可以根据需要将结果存储为数组,hex字符串或base-64编码字符串。

然而,您将此称为“身份validation令牌”的方式有点令人担忧。 会话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没有内置的方法来转换为hex字符串/从hex字符串转换,但是之前已经涉及过这个主题: 将字节数组转换为hex字符串,反之亦然

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

正如旁注所示,我使用的所有“身份validation令牌”机制(至少)将当前时间的常量值(“秘密”)连接在一起,然后将它们一起散列,然后发送散列和日期。 然后,服务器从接收的日期和已知的“秘密”重建散列,然后与接收的散列(签名)进行比较。 我在这里的观点是“与日期连接” – 这使得每次出现的签名都不同,理论上应该更加安全。

您可以只连接这些hex数字,而不是丢失信息的XORing。

为什么你甚至需要GUID? 手机ID是唯一的,GUID似乎没有增加任何价值。

我以为你可以使用双向算法。 这意味着该算法可以像Base64,SHA256,AES一样进行编码和解码