使用C#ASHX处理程序加密和解密令牌

时间:2014-01-07 16:21:29

标签: c# asp.net encryption encoding handler

我几天前读过一篇很好的指南,关于在服务器端生成一个令牌,以便在令牌中创建令牌的时间,以及“Guid.NewGuid()”的加密。

但是,我尝试调整结果以在令牌中拥有用户的用户名,而不是日期时间。我很接近,但是我无法提取用户名,我只能用它后面的一些随机字母来接收它。

在识别时生成令牌的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
}

示例:如果名称为“user”,则变量“theCode”将保留“userXyZxYzXyZ”的值(而XyZ代表GUID的“随机”键)。

我认为可以公平地说我的问题是如何在解密时将此GUID的密钥与用户名分开

1 个答案:

答案 0 :(得分:2)

guid长度为38个字符,因此名称为theCode.SubString(0, theCode.Length - 38)。或者,您可以将当前用户的名称与代码theCode.StartsWith(name)进行比较。

相关问题