如何在ASP.NET中加密和解密我的Cookie

Val*_*yry 4 c# asp.net encryption cookies

你好,标题说,我试图通过页面传递我的cookie,但我需要加密它们,并在特定的页面(Home.aspx)我需要解密它.谁有任何想法如何?

我的代码到目前为止,Login.aspx:

    HttpCookie UserCookie = new HttpCookie("Login");
    UserCookie.Value = txtUsername.Text;
    UserCookie.Expires = DateTime.Now.AddHours(2);
    Response.Cookies.Add(UserCookie);
Run Code Online (Sandbox Code Playgroud)

LGS*_*Son 6

你可以使用MachineKey.Protect/MachineKey.Unprotect

此示例代码还使用Base64转换来避免cookie值中的无效字符出现意外错误.

MachineKey.Protect(Encoding.UTF8.GetBytes(cookieValue), "a token").FromBytesToBase64();

Encoding.UTF8.GetString(MachineKey.Unprotect(Request.Cookies(cookieName).Value.FromBase64ToBytes, "a token"));
Run Code Online (Sandbox Code Playgroud)

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


Jas*_*son 6

我不得不稍微改变LGSon的答案,所以它对我有用.

Convert.ToBase64String(MachineKey.Protect(Encoding.UTF8.GetBytes("your cookie value")))

Encoding.UTF8.GetString(MachineKey.Unprotect(Convert.FromBase64String("your cookie value")))
Run Code Online (Sandbox Code Playgroud)