首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在mvc c#中解密FormsAuthenticationTicket?

如何在mvc c#中解密FormsAuthenticationTicket?
EN

Stack Overflow用户
提问于 2016-12-23 09:29:53
回答 1查看 5.6K关注 0票数 3

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

加密类似于下面

代码语言:javascript
复制
    string pw="xyz";
    FormsAuthenticationTicket ticketpw = new FormsAuthenticationTicket(pw, true, 1000);
    string securepw = FormsAuthentication.Encrypt(ticketpw);

    Session["password"] = securepw;

我试图像下面那样解密

Try 1

代码语言:javascript
复制
            FormsAuthenticationTicket ticketuname = new FormsAuthenticationTicket(pw, true, 1000);
            string secureuname = FormsAuthentication.Decrypt(pw);

            Session["password"] = securepw;

Try 2

代码语言:javascript
复制
            string securepw=FormsAuthentication.Decrypt(pw);               
            Session["password"] = securepw;

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-12-23 09:58:41

因为您创建的新票证不同于票证,所以它是加密的。最佳实践是将其放入HttpCookie中,然后检索它:

代码语言:javascript
复制
  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));

解密:

代码语言:javascript
复制
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)

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

票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41298679

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档