在C#中加密Cookie数据,可以使用System.Web.Security命名空间中的FormsAuthentication类。以下是一个简单的示例,展示了如何加密和解密Cookie数据:
<system.web> <authentication mode="Forms"> <forms loginUrl="~/Account/Login" timeout="30" /> </authentication></system.web>在代码中,使用FormsAuthentication.SetAuthCookie方法设置加密的Cookie:using System.Web.Security;public void SetEncryptedCookie(string username, string password){ FormsAuthentication.SetAuthCookie(username, false);}若要从Cookie中读取加密的数据,可以使用FormsAuthentication.GetAuthCookie方法:using System.Web.Security;public string GetUsernameFromCookie(){ if (FormsAuthentication.Authenticate(Request.Cookies["AuthCookie"])) { return FormsAuthentication.GetUsernameFromCookie(); } else { return null; }}注意:默认情况下,FormsAuthentication使用名为"AuthCookie"的Cookie来存储加密的身份验证信息。你可以根据需要更改此名称。


