如何在MVC C#中解密FormsAuthenticationTicket?

Mer*_* Jo 1 c# asp.net-mvc-4 form-authentication

我正在加密密码,并使用FormsAuthenticationTicket将其存储到会话值,当我检索到密码时,我无法解密密码。

如下加密

    string pw="xyz";
    FormsAuthenticationTicket ticketpw = new FormsAuthenticationTicket(pw, true, 1000);
    string securepw = FormsAuthentication.Encrypt(ticketpw);

    Session["password"] = securepw;
Run Code Online (Sandbox Code Playgroud)

我试图像下面尝试解密
1

            FormsAuthenticationTicket ticketuname = new FormsAuthenticationTicket(pw, true, 1000);
            string secureuname = FormsAuthentication.Decrypt(pw);

            Session["password"] = securepw;
Run Code Online (Sandbox Code Playgroud)

试试2

            string securepw=FormsAuthentication.Decrypt(pw);               
            Session["password"] = securepw;
Run Code Online (Sandbox Code Playgroud)

错误-无法将FormAuthenticationTicket转换为字符串

Ahm*_*med 5

因为您创建的新票证不同于被加密的票证,所以最佳实践是将其放入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));
Run Code Online (Sandbox Code Playgroud)

并崩溃

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)
Run Code Online (Sandbox Code Playgroud)

https://msdn.microsoft.com/zh-CN/library/system.web.security.formsauthentication.encrypt(v=vs.110).aspx