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

来源:互联网 发布:python 列表 replace 编辑:程序博客网 时间:2024/05/16 01:04

最近做一个论坛入口时要实现帐号和密码不在IE地址栏出现而做的

index.aspx.cs (加密处理)

  1. Byte[] Iv64={11, 22, 33, 44, 55, 66, 77, 85};
  2. Byte[] byKey64={10, 20, 30, 40, 50, 60, 70, 80};
  3. public string Encrypt(string strText)
  4. {
  5.   try
  6.   {
  7.      DESCryptoServiceProvider des = new DESCryptoServiceProvider();
  8.      Byte[] inputByteArray  = Encoding.UTF8.GetBytes(strText);
  9.      MemoryStream ms = new MemoryStream();
  10.      CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey64, Iv64),
  11.                     CryptoStreamMode.Write);
  12.      cs.Write(inputByteArray, 0, inputByteArray.Length);
  13.      cs.FlushFinalBlock();
  14.      return Convert.ToBase64String(ms.ToArray());
  15.   }
  16.   catch(Exception ex)
  17.   {
  18.      return ex.Message;
  19.   }
  20. }

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


  1. //随机选8个字节既为密钥也为初始向量
  2. Byte[] byKey64={10, 20, 30, 40, 50, 60, 70, 80};
  3. Byte[] Iv64={11, 22, 33, 44, 55, 66, 77, 85};
  4. public string Decrypt(string strText)
  5. {
  6.   Byte[] inputByteArray = new byte[strText.Length];
  7.   try
  8.   {
  9.      DESCryptoServiceProvider des = new DESCryptoServiceProvider();
  10.      inputByteArray = Convert.FromBase64String(strText);
  11.      MemoryStream  ms = new MemoryStream();
  12.      CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey64, Iv64),
  13.                            CryptoStreamMode.Write);
  14.      cs.Write(inputByteArray, 0, inputByteArray.Length);
  15.      cs.FlushFinalBlock();
  16.      System.Text.Encoding encoding = System.Text.Encoding.UTF8;
  17.      return encoding.GetString(ms.ToArray());
  18.   }
  19.   catch(Exception ex)
  20.   {
  21.     return ex.Message;
  22.   }
  23. }
  24. private void Page_Load(object sender, System.EventArgs e)
  25. {
  26.   if(Request.Params["clubID"]!=null)
  27.   {
  28.      string originalValue = Request.Params["clubID"];
  29.      originalValue = originalValue.Replace(" ","+");
  30.      //+号通过url传递变成了空格。
  31.      string decryptResult = Decrypt(originalValue);
  32.      //DecryptString(string)解密字符串
  33.      string delimStr = ",";
  34.      char[] delimiterArray = delimStr.ToCharArray();
  35.      string [] userInfoArray = null;
  36.      userInfoArray = decryptResult.Split(delimiterArray);
  37.      string userName = userInfoArray[0];
  38.      User userToLogin = new User();
  39.      userToLogin.Username = userInfoArray[0];
  40.      userToLogin.Password = userInfoArray[1];
  41.      ......
  42.   }
  43. }

原创粉丝点击