如何在 mvc c# 中解密 FormsAuthenticationTicket?
How to decrypt FormsAuthenticationTicket in mvc c#?
我正在加密密码并使用 FormsAuthenticationTicket 将其存储到会话值,当我检索它时我无法解密密码。
像下面这样加密
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)
我正在加密密码并使用 FormsAuthenticationTicket 将其存储到会话值,当我检索它时我无法解密密码。
像下面这样加密
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)