您的位置:首页 > 其它

对Url传输参数进行加密和解密

2008-11-12 16:45 573 查看
最近做一个论坛入口时要实现帐号和密码不在IE地址栏出现而做的
index.aspx.cs (加密处理)
Byte[] Iv64={11, 22, 33, 44, 55, 66, 77, 85};
Byte[] byKey64={10, 20, 30, 40, 50, 60, 70, 80};
public string Encrypt(string strText)
{
try
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
Byte[] inputByteArray = Encoding.UTF8.GetBytes(strText);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey64, Iv64),

CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
return Convert.ToBase64String(ms.ToArray());
}
catch(Exception ex)
{
return ex.Message;
}
}

private void btnLogin_Click(object sender, System.Web.UI.ImageClickEventArgs e)
{
DateTime nowTime = DateTime.Now;
string postUser = txtUser.Text.ToString();
string postPass = txtPassword.Text.ToString();
Response.Redirect("Login.aspx?clubID="+Encrypt(postUser+","+postPass+",
"+nowTime.ToString()));
}
login.aspx.cs (解密处理)


//随机选8个字节既为密钥也为初始向量

Byte[] byKey64={10, 20, 30, 40, 50, 60, 70, 80};
Byte[] Iv64={11, 22, 33, 44, 55, 66, 77, 85};

public string Decrypt(string strText)
{
Byte[] inputByteArray = new byte[strText.Length];
try
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
inputByteArray = Convert.FromBase64String(strText);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey64, Iv64),
CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
System.Text.Encoding encoding = System.Text.Encoding.UTF8;
return encoding.GetString(ms.ToArray());
}
catch(Exception ex)
{
return ex.Message;
}
}

private void Page_Load(object sender, System.EventArgs e)
{
if(Request.Params["clubID"]!=null)
{
string originalValue = Request.Params["clubID"];
originalValue = originalValue.Replace(" ","+");
//+号通过url传递变成了空格。
string decryptResult = Decrypt(originalValue);
//DecryptString(string)解密字符串
string delimStr = ",";
char[] delimiterArray = delimStr.ToCharArray();
string [] userInfoArray = null;
userInfoArray = decryptResult.Split(delimiterArray);
string userName = userInfoArray[0];

User userToLogin = new User();
userToLogin.Username = userInfoArray[0];
userToLogin.Password = userInfoArray[1];
......
}
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: