Criptografar QueryString

<< Click to Display Table of Contents >>

Navigation:  ASP.NET > Dicas avançadas >

Criptografar QueryString

Previous pageReturn to chapter overviewNext page

Veja o exemplo. Você tem uma página que deverá passar para outra página uma informação confidencial, mas deve ser por query string.

Aqui vemos passando uma senha: 123456

 

criptqy

 

Note na barra de endereços que o "id" está criptografado e no corpo da página novamente descriptografado (a titulo de exemplo):

criptqy2

 

CryptUtil.cs

 

using System;

using System.IO;

using System.Security.Cryptography;

using System.Text;

 

public class CryptUtil

{

  private static Byte[] ConvertStringToByArray(string s)

   {

      return (new UnicodeEncoding()).GetBytes(s);

   }

 

  public static string MD5(string s)

   {

      if (string.IsNullOrEmpty(s))

       {

          return null;

       }

      Byte[] toHash = ConvertStringToByArray(s);

      byte[] hashValue = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(toHash);

      return BitConverter.ToString(hashValue);

   }

 

  public static string Base64Encode(string key)

   {

      if (string.IsNullOrEmpty(key))

          return string.Empty;

 

      byte[] buffer = Encoding.UTF8.GetBytes(key);

      return Convert.ToBase64String(buffer);

   }

 

  public static string Base64Decode(string key)

   {

      if (string.IsNullOrEmpty(key))

          return "";

 

      byte[] buffer = Convert.FromBase64String(key);

      return Encoding.UTF8.GetString(buffer);

   }

 

  // Arbitrary key and iv vector.

  // You will want to generate (and protect) your own when using encryption.

  private const string actionKey = "EA81AA1D5FC1EC53E84F30AA746139EEBAFF8A9B76638895";

  private const string actionIv = "87AF7EA221F3FFF5";

 

  private TripleDESCryptoServiceProvider des3;

 

  public CryptUtil()

   {

       des3 = new TripleDESCryptoServiceProvider();

       des3.Mode = CipherMode.CBC;

   }

 

  public string GenerateKey()

   {

       des3.GenerateKey();

      return BytesToHex(des3.Key);

   }

 

  public string GenerateIV()

   {

       des3.GenerateIV();

      return BytesToHex(des3.IV);

   }

 

  private byte[] HexToBytes(string hex)

   {

      byte[] bytes = new byte[hex.Length / 2];

      for (int i = 0; i < hex.Length / 2; i++)

       {

          string code = hex.Substring(i * 2, 2);

           bytes[i] = byte.Parse(code, System.Globalization.NumberStyles.HexNumber);

       }

      return bytes;

   }

 

  private string BytesToHex(byte[] bytes)

   {

      StringBuilder hex = new StringBuilder();

      for (int i = 0; i < bytes.Length; i++)

           hex.AppendFormat("{0:X2}", bytes[i]);

      return hex.ToString();

   }

 

  public string Encrypt(string data, string key, string iv)

   {

      byte[] bdata = Encoding.UTF8.GetBytes(data);

      byte[] bkey = HexToBytes(key);

      byte[] biv = HexToBytes(iv);

 

      MemoryStream stream = new MemoryStream();

      CryptoStream encStream = new CryptoStream(stream,

       des3.CreateEncryptor(bkey, biv), CryptoStreamMode.Write);

 

       encStream.Write(bdata, 0, bdata.Length);

       encStream.FlushFinalBlock();

       encStream.Close();

 

      return BytesToHex(stream.ToArray());

   }

 

  public string Decrypt(string data, string key, string iv)

   {

      byte[] bdata = HexToBytes(data);

      byte[] bkey = HexToBytes(key);

      byte[] biv = HexToBytes(iv);

 

      MemoryStream stream = new MemoryStream();

      CryptoStream encStream = new CryptoStream(stream,

       des3.CreateDecryptor(bkey, biv), CryptoStreamMode.Write);

 

       encStream.Write(bdata, 0, bdata.Length);

       encStream.FlushFinalBlock();

       encStream.Close();

 

      return Encoding.UTF8.GetString(stream.ToArray());

   }

 

  public string ActionEncrypt(string data)

   {

      return Encrypt(data, actionKey, actionIv);

   }

 

  public string ActionDecrypt(string data)

   {

      return Decrypt(data, actionKey, actionIv);

   }

}

 

Pagina1.aspx

 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Pagina1.aspx.cs" Inherits="WebApplication1.Pagina1" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

  <title></title>

</head>

<body>

  <form id="form1" runat="server">

  <div>

      <asp:TextBox ID="txtMensagem" runat="server"></asp:TextBox>

      <asp:Button ID="Button1" runat="server" Text="Passar mensagem por QueryString" onclick="Button1_Click" />

  </div>

  </form>

</body>

</html>

 

Pagina1.aspx.cs

 

using System;

 

public partial class Pagina1 : System.Web.UI.Page

{

  protected void Page_Load(object sender, EventArgs e)

   {

   }

 

  protected void Button1_Click(object sender, EventArgs e)

   {

      CryptUtil crypt = new CryptUtil();

      string query = crypt.ActionEncrypt(txtMensagem.Text);

       Response.Redirect("~/Pagina2.aspx?id=" + query);

   }

}

 

Pagina2.aspx

 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Pagina2.aspx.cs" Inherits="WebApplication1.Pagina2" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

  <title></title>

</head>

<body>

  <form id="form1" runat="server">

  <div>

      <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

  </div>

  </form>

</body>

</html>

 

Pagina2.aspx.cs

 

using System;

 

public partial class Pagina2 : System.Web.UI.Page

{

  protected void Page_Load(object sender, EventArgs e)

   {

      if (Request.Params["id"] != null)

       {

          CryptUtil crypt = new CryptUtil();

          string id = crypt.ActionDecrypt(Request.Params["id"].ToString());

           Label1.Text = id;

       }

   }

}