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



几天前我读过一个很好的指南,关于在服务器端生成令牌,以便在令牌中创建令牌的时间,以及"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 的密钥与用户名分开

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

最新更新