2014-01-07 101 views
0

幾天前,我已經閱讀了一個很好的指南,關於在服務器端生成令牌以在令牌內創建令牌的時間,以及「Guid.NewGuid ()「的加密。使用C#ASHX處理程序加密和解密令牌

但是,我試圖調整結果在令牌中有一個用戶的用戶名,而不是日期時間。我很接近,但我無法提取用戶名,我只能在它後面接收一些隨機字母。

的ASP.NET通用處理器的代碼來生成經鑑定令牌

ASCIIEncoding encoder = new ASCIIEncoding(); 
if(postType == "identify") 
{ 
     byte[] binName = encoder.GetBytes(name); 
     byte[] key = Guid.NewGuid().ToByteArray(); 
     string _token = Convert.ToBase64String(binName.Concat(key).ToArray()); 
     // The above creates a token with the name and the "key", works well 
} 

通用處理器來解密令牌(參見實施例爲結果)

if(postType == "check") 
{ 
     string _token = dict["token"] as string; 
     byte[] data = Convert.FromBase64String(_token); 
     string theCode = encoder.GetString(data); // This will get both the username and the GUID key within 
     context.Response.Write(jss.Serialize(new Code { eCode = theCode })); // Returns in JSON, irrelevant to the question, it works well 
} 
的代碼

示例:如果名稱爲「用戶」,則變量「theCode」將保存「userXyZxYzXyZ」的值(而XyZ代表GUID的「隨機」鍵)。

我認爲這是公平地說,我的問題是如何將這種GUID的重點從用戶名解密時

+1

'Guid.NewGuid'!= =加密 – spender

+0

[相關鏈接](http://stackoverflow.com/q/6267555/969613) – JMK

+0

你不需要在它們之間添加一些字符,這樣你就可以在它們之間進行拆分你可以像加密時那樣進行解密,然後添加一個|在名字和guid之間。 – MoZahid

回答

2

分開GUID是38個字符長,所以這個名字會theCode.SubString(0, theCode.Length - 38)。或者,您可以將當前用戶的名稱與代碼進行比較:theCode.StartsWith(name)

+0

謝謝。不知道長度。 – Kfirprods