Encriptar y Desencriptar QueryString asp.net | utilizando vb.net
Encriptar y Desencriptar QueryString asp.net o mas bien cifrar y decifrar los valores o variables que son enviados de página en página a través de la dirección URL también conocidos como QueryString es una tarea muy importante cuando tenemos en línea una aplicación web que maneja datos de importancia.
Encriptar y Desencriptar QueryString asp.net se puede hacer directamente utilizando el WebConfig, pero en este artículo hablaremos de como cifrar las variables que enviamos en las URL de forma individual, es decir, desde una página origen hacia una página destino. Para ello utilizaremos algoritmos de claves AES codificados (debido a que la salida cifrada puede contener caracteres especiales)
Marcado HTML
Página Origen
En este ejemplo de Encriptar y Desencriptar QueryString asp.net utilizaremos el siguiente formato HTML, que consiste en un cuadro de texto, un DropDownList y un botón. El valor del cuadro de texto y las listas desplegables se cifrará y enviar utilizando parámetros de cadena de consulta a la siguiente página en el botón de clic.
<table border="0" cellpadding="0" cellspacing="0"> <tr> <td> Name: </td> <td> <asp:TextBox ID="txtName" runat="server" Text="Mudassar Khan" /> </td> </tr> <tr> <td> Technology: </td> <td> <asp:DropDownList ID = "ddlTechnology" runat="server"> <asp:ListItem Text="ASP.Net" Value = "ASP.Net" /> <asp:ListItem Text="PHP" Value = "PHP" /> <asp:ListItem Text="JSP" Value = "JSP" /> </asp:DropDownList> </td> </tr> </table> <hr /> <asp:Button ID="Button1" Text="Submit" runat="server" OnClick = "Submit" /> |
<table border="0" cellpadding="0" cellspacing="0"> <tr> <td> Name: </td> <td> <asp:TextBox ID="txtName" runat="server" Text="Mudassar Khan" /> </td> </tr> <tr> <td> Technology: </td> <td> <asp:DropDownList ID = "ddlTechnology" runat="server"> <asp:ListItem Text="ASP.Net" Value = "ASP.Net" /> <asp:ListItem Text="PHP" Value = "PHP" /> <asp:ListItem Text="JSP" Value = "JSP" /> </asp:DropDownList> </td> </tr> </table> <hr /> <asp:Button ID="Button1" Text="Submit" runat="server" OnClick = "Submit" />
Página destino
Para Encriptar y Desencriptar QueryString asp.net en la página destino utilizaremos el siguiente formato HTML que consta de dos controles Label que se utilizarán para mostrar los valores de los parámetros de QueryString recibidas en la página.
<table border="0" cellpadding="0" cellspacing="0"> <tr> <td> Name: </td> <td> <asp:Label ID="lblName" runat="server" Text="" /> </td> </tr> <tr> <td> Technology: </td> <td> <asp:Label ID="lblTechnology" runat="server" Text="" /> </td> </tr> </table> |
<table border="0" cellpadding="0" cellspacing="0"> <tr> <td> Name: </td> <td> <asp:Label ID="lblName" runat="server" Text="" /> </td> </tr> <tr> <td> Technology: </td> <td> <asp:Label ID="lblTechnology" runat="server" Text="" /> </td> </tr> </table>
Espacios de Nombre a Importar
Para Encriptar y Desencriptar QueryString asp.net Usted tendrá que importar los siguientes espacios de nombres.
Imports System.IO Imports System.Text Imports System.Security.Cryptography |
Imports System.IO Imports System.Text Imports System.Security.Cryptography
Encriptando QueryString en página de origen
Protected Sub Submit(sender As Object, e As EventArgs) Dim name As String = HttpUtility.UrlEncode(Encrypt(txtName.Text.Trim())) Dim technology As String = HttpUtility.UrlEncode(Encrypt(ddlTechnology.SelectedItem.Value)) Response.Redirect(String.Format("~/VB2.aspx?name={0}&technology={1}", name, technology)) End Sub Private Function Encrypt(clearText As String) As String Dim EncryptionKey As String = "MAKV2SPBNI99212" Dim clearBytes As Byte() = Encoding.Unicode.GetBytes(clearText) Using encryptor As Aes = Aes.Create() Dim pdb As New Rfc2898DeriveBytes(EncryptionKey, New Byte() {&H49, &H76, &H61, &H6E, &H20, &H4D, _ &H65, &H64, &H76, &H65, &H64, &H65, _ &H76}) encryptor.Key = pdb.GetBytes(32) encryptor.IV = pdb.GetBytes(16) Using ms As New MemoryStream() Using cs As New CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write) cs.Write(clearBytes, 0, clearBytes.Length) cs.Close() End Using clearText = Convert.ToBase64String(ms.ToArray()) End Using End Using Return clearText End Function |
Protected Sub Submit(sender As Object, e As EventArgs) Dim name As String = HttpUtility.UrlEncode(Encrypt(txtName.Text.Trim())) Dim technology As String = HttpUtility.UrlEncode(Encrypt(ddlTechnology.SelectedItem.Value)) Response.Redirect(String.Format("~/VB2.aspx?name={0}&technology={1}", name, technology)) End Sub Private Function Encrypt(clearText As String) As String Dim EncryptionKey As String = "MAKV2SPBNI99212" Dim clearBytes As Byte() = Encoding.Unicode.GetBytes(clearText) Using encryptor As Aes = Aes.Create() Dim pdb As New Rfc2898DeriveBytes(EncryptionKey, New Byte() {&H49, &H76, &H61, &H6E, &H20, &H4D, _ &H65, &H64, &H76, &H65, &H64, &H65, _ &H76}) encryptor.Key = pdb.GetBytes(32) encryptor.IV = pdb.GetBytes(16) Using ms As New MemoryStream() Using cs As New CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write) cs.Write(clearBytes, 0, clearBytes.Length) cs.Close() End Using clearText = Convert.ToBase64String(ms.ToArray()) End Using End Using Return clearText End Function
Descifrando el QueryString en la página destino
En el caso de carga de la página, los valores del cuadro de texto y DropDownList enviada desde la página anterior son primero tomaron de los parámetros de cadena de consulta y luego se decodifican utilizando el método de la clase urldecode HttpUtility.
Después de la decodificación de la secuencia se descifran utilizando el Algoritmo de clave simétrica AES y luego los valores desencriptados se muestran usando controles Label.
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load If Not Me.IsPostBack Then lblName.Text = Decrypt(HttpUtility.UrlDecode(Request.QueryString("name"))) lblTechnology.Text = Decrypt(HttpUtility.UrlDecode(Request.QueryString("technology"))) End If End Sub Private Function Decrypt(cipherText As String) As String Dim EncryptionKey As String = "MAKV2SPBNI99212" cipherText = cipherText.Replace(" ", "+") Dim cipherBytes As Byte() = Convert.FromBase64String(cipherText) Using encryptor As Aes = Aes.Create() Dim pdb As New Rfc2898DeriveBytes(EncryptionKey, New Byte() {&H49, &H76, &H61, &H6E, &H20, &H4D, _ &H65, &H64, &H76, &H65, &H64, &H65, _ &H76}) encryptor.Key = pdb.GetBytes(32) encryptor.IV = pdb.GetBytes(16) Using ms As New MemoryStream() Using cs As New CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write) cs.Write(cipherBytes, 0, cipherBytes.Length) cs.Close() End Using cipherText = Encoding.Unicode.GetString(ms.ToArray()) End Using End Using Return cipherText End Function |
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load If Not Me.IsPostBack Then lblName.Text = Decrypt(HttpUtility.UrlDecode(Request.QueryString("name"))) lblTechnology.Text = Decrypt(HttpUtility.UrlDecode(Request.QueryString("technology"))) End If End Sub Private Function Decrypt(cipherText As String) As String Dim EncryptionKey As String = "MAKV2SPBNI99212" cipherText = cipherText.Replace(" ", "+") Dim cipherBytes As Byte() = Convert.FromBase64String(cipherText) Using encryptor As Aes = Aes.Create() Dim pdb As New Rfc2898DeriveBytes(EncryptionKey, New Byte() {&H49, &H76, &H61, &H6E, &H20, &H4D, _ &H65, &H64, &H76, &H65, &H64, &H65, _ &H76}) encryptor.Key = pdb.GetBytes(32) encryptor.IV = pdb.GetBytes(16) Using ms As New MemoryStream() Using cs As New CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write) cs.Write(cipherBytes, 0, cipherBytes.Length) cs.Close() End Using cipherText = Encoding.Unicode.GetString(ms.ToArray()) End Using End Using Return cipherText End Function
Puedes leer el artículo original en ingles que incluye un ejemplo para C# dando clic en este enlace: Encrypt and Decrypt QueryString!
Muy buen artículo, gracias.
Excelente articulo, me gustó, yo vi este video y me funcionó bastante bien! Espero les sirva: https://www.youtube.com/watch?v=CpSGtkZNvn0
En la descripción comparten el código
Excelente, funciona perfecto. Había visto otros códigos que no incluyen caracteres especiales y en ocasiones generan error. Este está formidable. Gracias.