【问题标题】:How to decrypt FormsAuthenticationTicket in mvc c#?如何在 mvc c# 中解密 FormsAuthenticationTicket?
【发布时间】:2016-12-23 09:29:53
【问题描述】:

我正在加密密码并使用 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 转换为字符串

【问题讨论】:

  • 如果将值存储在服务器端的会话中,加密的意义何在?您也可以将其存储为纯文本,会话容器不能直接供用户使用。不过,另一个问题是,为什么需要在服务器端存储用户密码?
  • @WiktorZychla 我正在使用 converse.js 进行聊天,当用户注册或登录我的主页时,我需要将用户名和密码发送到客户端(用于 converse.js)
  • 听起来像是一个潜在的安全漏洞,您应该避免以纯文本形式存储用户密码,更不用说在任何地方以纯文本形式发送密码。我强烈建议你重新考虑你的方法。可能,如果用户已经登录到您的网站并且您的网站发布了加密的 cookie,那么您就不再需要密码了。但是,如果没有关于您的架构的更多详细信息,就很难确定。
  • @WiktorZychla 我只会将此加密密码用于聊天目的,有没有机会破解或其他问题?当用户登录时,我将加密此密码并发送到客户端进行聊天登录。请提出更多建议,因为我也是登录注册过程的新手。

标签: c# asp.net-mvc-4 form-authentication


【解决方案1】:

因为您创建的新票证与加密票证不同。最佳做法是将其放在 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)

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

【讨论】:

  • 我是否需要将这些信息存储到 cookie 中?
  • @MerbinJo 构造函数有多个覆盖,请参阅适合您的情况。
  • 感谢您的回答我的问题已解决,但 WiktorZychla 他谈到了一些安全问题。
  • @MerbinJo 如果这解决了您的问题,请将其标记为答案,以便其他人可以使用它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-29
  • 2013-03-03
  • 2011-02-27
  • 1970-01-01
  • 2015-03-24
  • 1970-01-01
相关资源
最近更新 更多