自动登录和解/加密

在asp.net中可以用cookie保存用户的帐户密码实现自动登录的功能,但是需要强调一下,cookie在客户端保存,是不安全的,推荐使用md5加密保存。

下面分析一下在asp.net中cookie的创建、提取与销毁的方法:
创建cookie
//向客户端写入Cookie

HttpCookie hcUserName1 = new HttpCookie("uname"); // 创建一个名为uname的cookie

hcUserName1.Expires = DateTime.Now.AddDays(7); // 设置该cookie的有效时间

hcUserName1.Value = uname; // 给cookie赋值(也就是你想保存的账号,或者密码)

HttpContext.Current.Response.Cookies.Add(hcUserName1); // 提交cookie

提取cookie
if (HttpContext.Current.Request.Cookies["uname"] != null) // 如果这个uname cookie 不为空

string uname = HttpContext.Current.Request.Cookies["uname"].Value.ToString(); // 提取cookie
销毁cookie
// 把cookie的时间设置为 -1 ,即cookie过期、销毁

HttpContext.Current.Response.Cookies["uname"].Expires = DateTime.Now.AddSeconds(-1);

//加密
public static string EncryptPassword(string sPASSWORD, Guid gKEY, Guid gIV)
{
UTF8Encoding utf8 = new UTF8Encoding(false);

string sResult = null;
byte[] byPassword = utf8.GetBytes(sPASSWORD);
using ( MemoryStream stm = new MemoryStream() )
{
Rijndael rij = Rijndael.Create();
rij.Key = gKEY.ToByteArray();
rij.IV = gIV.ToByteArray();
using ( CryptoStream cs = new CryptoStream(stm, rij.CreateEncryptor(), CryptoStreamMode.Write) )
{
cs.Write(byPassword, 0, byPassword.Length);
cs.FlushFinalBlock();
cs.Close();
}
sResult = Convert.ToBase64String(stm.ToArray());
}
return sResult;
}
//解密
public static string DecryptPassword(string sPASSWORD, Guid gKEY, Guid gIV)
{
UTF8Encoding utf8 = new UTF8Encoding(false);

string sResult = null;
byte[] byPassword = Convert.FromBase64String(sPASSWORD); //将指定的字符串(它将二进制数据编码为 Base64 数字)转换为等效的 8 位无符号整数数组。
using (MemoryStream stm = new MemoryStream()) //是内存流,为系统内存提供读写操作,由于MemoryStream是通过无符号字节数组组成的,底层内存的操作
{
Rijndael rij = Rijndael.Create(); //Rijndael算法,一个密钥分组加密的算法
rij.Key = gKEY.ToByteArray(); //转为字节数组
rij.IV = gIV.ToByteArray();
using (CryptoStream cs = new CryptoStream(stm, rij.CreateDecryptor(), CryptoStreamMode.Write)) //解密,参数(对其执行加密转换的流,要对流执行的加密转换,CryptoStreamMode 值之一)
{
cs.Write(byPassword, 0, byPassword.Length);
cs.Flush();
cs.Close();
}
byte[] byResult = stm.ToArray(); //内存流转为数组
sResult = utf8.GetString(byResult, 0, byResult.Length); //用UTF8编码得到字符串
}
return sResult;
}

原文地址:https://www.cnblogs.com/it-xcn/p/6086273.html