C# 如何在mvc中解密FormsAuthenticationTicket?
我正在使用FormsAuthenticationTicket加密密码并将其存储到会话值,当我检索密码时,我无法解密密码 如下所示进行加密C# 如何在mvc中解密FormsAuthenticationTicket?,c#,asp.net-mvc-4,form-authentication,C#,Asp.net Mvc 4,Form Authentication,我正在使用FormsAuthenticationTicket加密密码并将其存储到会话值,当我检索密码时,我无法解密密码 如下所示进行加密 string pw="xyz"; FormsAuthenticationTicket ticketpw = new FormsAuthenticationTicket(pw, true, 1000); string securepw = FormsAuthentication.Encrypt(ticketpw); Sessio
string pw="xyz";
FormsAuthenticationTicket ticketpw = new FormsAuthenticationTicket(pw, true, 1000);
string securepw = FormsAuthentication.Encrypt(ticketpw);
Session["password"] = securepw;
我试图解密,如下所示尝试1
FormsAuthenticationTicket ticketuname = new FormsAuthenticationTicket(pw, true, 1000);
string secureuname = FormsAuthentication.Decrypt(pw);
Session["password"] = securepw;
尝试2次
string securepw=FormsAuthentication.Decrypt(pw);
Session["password"] = securepw;
错误-无法将FormAuthenticationTicket转换为字符串,因为您创建的新票证与加密的票证不同。最佳做法是将其放入
HttpCookie
中,然后检索它:
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
username,
DateTime.Now,
DateTime.Now.AddMinutes(30),
isPersistent,
userData,
FormsAuthentication.FormsCookiePath);
// Encrypt the ticket.
string encTicket = FormsAuthentication.Encrypt(ticket);
// Create the cookie.
Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
并解密:
var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie == null) return;
var cookieValue = authCookie.Value;
if (String.IsNullOrWhiteSpace(cookieValue)) return;
var ticket = FormsAuthentication.Decrypt(cookieValue)
如果将值存储在会话中的服务器端,那么加密该值有什么意义?您也可以将其存储为纯文本,因为会话容器不能直接供用户使用。不过,另一个问题是,为什么需要在服务器端存储用户密码?@WiktorZychla我使用converse.js聊天,当用户注册或登录到我的主页时,我需要将用户名和密码发送到客户端(对于converse.js)听起来像是一个潜在的安全漏洞,您应该避免以纯文本形式存储用户密码,更不用说以纯文本形式在任何地方发送密码了。我强烈建议你重新考虑你的方法。可能,如果用户已经登录到您的网站,并且您的网站发布了加密cookie,那么您就不再需要密码了。但是,如果没有关于您的体系结构的更多详细信息,则很难确定。@WiktorZychla我将仅将此加密密码用于聊天目的,是否有机会黑客或其他问题?当用户登录时,我将加密此密码并发送到客户端进行聊天登录。请提供更多建议,因为我也不熟悉登录注册过程。我是否需要将这些信息存储到Cookie中?@MerbinJo构造函数有多个覆盖,请参阅适合您的案例。感谢您的回答,我的问题已经解决,但WiktorZychla他说了一些安全问题。@MerbinJo如果这解决了您的问题,将其标记为答案,以便其他人可以使用。