gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 19:49:41 25 4
gpt4 key购买 nike

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

像下面这样加密

    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)

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

关于c# - 如何在 mvc c# 中解密 FormsAuthenticationTicket?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41298679/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com