2016-12-23 28 views
0

我使用FormsAuthenticationTicket加密密碼並將其存儲爲會話值,當我檢索密碼時,我無法解密密碼。如何解密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; 

錯誤 - 因爲你創建新的機票向度船票得到encrpted無法轉換FormAuthenticationTicket爲String

+1

如果將它存儲在會話中,在服務器端加密值,這有什麼意義?您可以將它以純文本格式存儲,會話容器不能直接提供給用戶。另一個問題是,爲什麼你需要在服務器端存儲用戶密碼? –

+0

@WiktorZychla我正在使用converse.js作爲聊天的目的,當用戶註冊或登錄我的主頁時,我需要將用戶名和密碼發送到客戶端(對於converse.js) –

+0

聽起來像是一個潛在的安全漏洞,您應該避免以純文本存儲用戶密碼,更不用說以純文本格式發送密碼。我強烈建議你重新考慮你的方法。可能的話,如果用戶已經登錄到您的網站並且您的網站發佈了加密的cookie,則您不再需要密碼。但是,很難確定,沒有關於您的架構的更多細節。 –

回答

2

,最好的做法是把它的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

+0

我是否需要將這些信息存儲到cookie中? –

+0

@MerbinJo對構造函數有多重覆蓋,請參閱適合您的情況。 –

+0

@MerbinJo你的問題解決了嗎? –