Etiquetas

, ,

cookies
Aquí les dejo fragmento de un código que les puede ser útil a la hora de encriptar cookies en sus aplicaciones.

Imports System.Security.Cryptography.Rfc2898DeriveBytes

Imports System.Security.Cryptography

Imports System.IO

Partial Class _Default

Inherits System.Web.UI.Page

Public Function DecryptString(ByVal inString As String, ByVal password As String, ByVal Mysalt As String) As String

Dim DescryText As String = “”

Try

Dim myAlg As RijndaelManaged = New RijndaelManaged()

Dim salt As Byte() = System.Text.Encoding.ASCII.GetBytes(Mysalt)

Dim key As Rfc2898DeriveBytes = New Rfc2898DeriveBytes(password, salt)

myAlg.Key = key.GetBytes(myAlg.KeySize / 8 )

myAlg.IV = key.GetBytes(myAlg.BlockSize / 8 )

Dim buffer As Byte() = Convert.FromBase64String(inString)

Dim memStrm As New MemoryStream()

Dim memStrmOut As New MemoryStream(buffer)

Dim encryptor As ICryptoTransform = myAlg.CreateDecryptor

Dim encryptStream As CryptoStream = New CryptoStream(memStrmOut, encryptor, CryptoStreamMode.Read)

Dim reader As New StreamReader(encryptStream)

DescryText = reader.ReadToEnd

Catch ex As Exception

DescryText = “”

End Try

Return DescryText

End Function

Public Function EncryptString(ByVal inString As String, ByVal password As String, ByVal Mysalt As String) As String

Dim DescryText As String = “”

Try

Dim myAlg As RijndaelManaged = New RijndaelManaged()

Dim salt As Byte() = System.Text.Encoding.ASCII.GetBytes(Mysalt)

Dim key As Rfc2898DeriveBytes = New Rfc2898DeriveBytes(password, salt)

myAlg.Key = key.GetBytes(myAlg.KeySize / 8 )

myAlg.IV = key.GetBytes(myAlg.BlockSize / 8 )

Dim memStrm As New MemoryStream()

Dim memStrmOut As New MemoryStream()

Dim encryptor As ICryptoTransform = myAlg.CreateEncryptor

Dim encryptStream As CryptoStream = New CryptoStream(memStrmOut, encryptor, CryptoStreamMode.Write)

Dim writer As New StreamWriter(encryptStream)

writer.Write(inString)

writer.Flush()

encryptStream.FlushFinalBlock()

memStrmOut.Flush()

DescryText = Convert.ToBase64String(memStrmOut.GetBuffer(), 0, memStrmOut.Length)

encryptStream.Close()

Catch ex As Exception

DescryText = “”

End Try

Return DescryText

End Function

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim a As String = EncryptString(Me.TextBox1.Text, “P@S5w0r]>”, “Proyecto”)

Response.Cookies(“encryptcookie”).Value = a

End Sub

Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click

Me.TextBox2.Text = DecryptString(Request.Cookies(“encryptcookie”).Value, “P@S5w0r]>”, “Proyecto”)

End Sub

End Class