Visual Studio .NET - Is there an easy way to encrypt and decrypt a querystring

Asked By Paddy Mac on 12-Dec-06 06:14 AM

Hi, I want to use querystrings to pass parameters from one page to another.  Some of these parameters are used in a SqlDataSource for a gridview.

I need these parameters to be encrypted.  What is the easiest way to do this?

Thanks,

Paddy


see here-- - Peter Bromberg replied to Paddy Mac on 12-Dec-06 06:23 AM

encrypt decrypt querystring - mv ark replied to Paddy Mac on 12-Dec-06 06:36 AM

This code sample uses Base64 - http://www.devcity.net/PrintArticle.aspx?ArticleID=47

Extremely Simple TripleDES Encryption/Decryption with Base64 Encoding/Decoding.

K Pravin Kumar Reddy replied to Paddy Mac on 12-Dec-06 06:44 AM

Extremely Simple TripleDES Encryption/Decryption with Base64 Encoding/Decoding.

A friend of mine needed a way to store some values in a configuration file that is somewhat sensitive (coming from a web service using WSE2 with encryption).  I thought about using DP-API, however, he needed the ability to use the same config file for all users.  The first thing that came to mind was to use TripleDES in a similar manner as when I worked on http://www.radioshack.com/ e-Commerce site.  Basically, I used a third party component that would encrypt and decrypt the strings (password, credit card, etc.) and then use a crude homemade Base64 type function to convert the string so that special characters (specifically, the ASCII 0 - NULL) wouldn't interfere with the OLEDB functions.

I knew that the encryption/decryption and Base64 functionality is part of the BCL... so I did some googling for a sample.  I came across a pretty http://www.dotnet247.com/247reference/msgs/24/121749.aspx that was written in C#.  Alas, my friend needed the code in VB.NET (well, of course he did ;-) ).  Here is an even more simplified version of the code I found.

Private Function TripleDESEncode(ByVal value As String, ByVal key As String) As String

  Dim des As New Security.Cryptography.TripleDESCryptoServiceProvider

  des.IV = New Byte(7) {}

  Dim pdb As New Security.Cryptography.PasswordDeriveBytes(key, New Byte(-1) {})

  des.Key = pdb.CryptDeriveKey("RC2", "MD5", 128, New Byte(7) {})

  Dim ms As New IO.MemoryStream((value.Length * 2) - 1)

  Dim encStream As New Security.Cryptography.CryptoStream(ms, des.CreateEncryptor(), Security.Cryptography.CryptoStreamMode.Write)

  Dim plainBytes As Byte() = Text.Encoding.UTF8.GetBytes(value)

  encStream.Write(plainBytes, 0, plainBytes.Length)

  encStream.FlushFinalBlock()

  Dim encryptedBytes(CInt(ms.Length - 1)) As Byte

  ms.Position = 0

  ms.Read(encryptedBytes, 0, CInt(ms.Length))

  encStream.Close()

  Return Convert.ToBase64String(encryptedBytes)

End Function

 

Public Function TripleDESDecode(ByVal value As String, ByVal key As String) As String

  Dim des As New Security.Cryptography.TripleDESCryptoServiceProvider

  des.IV = New Byte(7) {}

  Dim pdb As New Security.Cryptography.PasswordDeriveBytes(key, New Byte(-1) {})

  des.Key = pdb.CryptDeriveKey("RC2", "MD5", 128, New Byte(7) {})

  Dim encryptedBytes As Byte() = Convert.FromBase64String(value)

  Dim ms As New IO.MemoryStream(value.Length)

  Dim decStream As New Security.Cryptography.CryptoStream(ms, des.CreateDecryptor(), Security.Cryptography.CryptoStreamMode.Write)

  decStream.Write(encryptedBytes, 0, encryptedBytes.Length)

  decStream.FlushFinalBlock()

  Dim plainBytes(CInt(ms.Length - 1)) As Byte

  ms.Position = 0

  ms.Read(plainBytes, 0, CInt(ms.Length))

  decStream.Close()

  Return Text.Encoding.UTF8.GetString(plainBytes)

End Function

Basically, I just wanted two simple functions that would take a string and a private key value and encrypt it using TripleDES and Base64 Encode it.  When I wanted to decode the value, just pass it to another function that would reverse the process using the same private key.  This code is completely self-contained, just drop into a existing form, class or module and use.  Here's an example of the functions being used from a console application:

<STAThread()> _

Sub Main()

 

  Dim key As String = "a1B@c3D$"

 

  Dim original As String = "This is a test, blah, blah, blah."

  Console.WriteLine("Original" & vbCrLf & "-----------------")

  Console.WriteLine(original & vbCrLf)

  Dim encrypted As String = TripleDESEncode(original, key)

  Console.WriteLine("Encrypted" & vbCrLf & "-----------------")

  Console.WriteLine(encrypted & vbCrLf)

  Dim decrypted As String = TripleDESDecode(encrypted, key)

  Console.WriteLine("Decrypted" & vbCrLf & "-----------------")

  Console.WriteLine(decrypted & vbCrLf)

 

  Console.ReadLine()

 

End Sub

When using this, be sure to use a key that conforms to same sort of rules you would want for passwords.  Also, if you intend to use this sort of functionality within your code, where the key is stored within the project, but sure to use one of the many obfuscaters that are available that can encrypt the strings within the executable.  If you use an obfuscater that does not have that functionality, then use some other mechanism to obfuscate this key value.

reference

http://addressof.com/blog/archive/2004/10/19/997.aspx

encrypt and decrypt a querystring - K Pravin Kumar Reddy replied to Paddy Mac on 12-Dec-06 06:48 AM
Default1.aspx code behind

Controls:
-Button
-Textbox
 
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim oEs As New Encryption64
        Dim strQueryString As String
        strQueryString = oEs.Encrypt(TextBox1.Text, "12345678")
        Response.Redirect("default2.aspx?id=" & strQueryString)
    End Sub
 
Default2.aspx code behind

Controls:
-Label

 
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim strQueryString As String
        strQueryString = Request.QueryString("id")
        Dim oEs As New Encryption64
        Label1.Text = oEs.Decrypt(strQueryString.Replace(" ", "+"), "12345678")
    End Sub

 
Hope that helps you in your project.

reference

http://forums.asp.net/thread/1283917.aspx

Query string..... - Ravichandran K replied to Paddy Mac on 12-Dec-06 08:27 AM
    'Function to encode the string
Function TamperProofStringEncode(ByVal value As String, _
ByVal key As String) As String
Dim mac3des As New System.Security.Cryptography.MACTripleDES()
Dim md5 As New System.Security.Cryptography.MD5CryptoServiceProvider()
mac3des.Key = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(key))
Return Convert.ToBase64String( _
System.Text.Encoding.UTF8.GetBytes(value)) & "-"c & _
Convert.ToBase64String(mac3des.ComputeHash( _
System.Text.Encoding.UTF8.GetBytes(value)))
End Function

'Function to decode the string
'Throws an exception if the data is corrupt
Function TamperProofStringDecode(ByVal value As String, _
ByVal key As String) As String
Dim dataValue As String = ""
Dim calcHash As String = ""
Dim storedHash As String = ""

Dim mac3des As New System.Security.Cryptography.MACTripleDES()
Dim md5 As New System.Security.Cryptography.MD5CryptoServiceProvider()
mac3des.Key = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(key))

Try
dataValue = System.Text.Encoding.UTF8.GetString( _
Convert.FromBase64String(value.Split("-"c)(0)))
storedHash = System.Text.Encoding.UTF8.GetString(_
Convert.FromBase64String(value.Split("-"c)(1)))
calcHash = System.Text.Encoding.UTF8.GetString( _
mac3des.ComputeHash(System.Text.Encoding.UTF8.GetBytes(dataValue)))

If storedHash <> calcHash Then
'Data was corrupted

Throw New ArgumentException("Hash value does not match")
'This error is immediately caught below
End If
Catch ex As Exception
Throw New ArgumentException("Invalid TamperProofString")
End Try

Return dataValue

End Function

/////Optionally you can create two simple helper functions. The following are the two functions and their usage.

Private TamperProofKey As String = 
ConfigurationSettings.AppSettings("TamperProofKey")
'or ... TamperProofKey As String = "YourUglyHardCodedKeyLike-alksfjlkasjfl3425"

Function QueryStringEncode(ByVal value As String) As String
Return HttpUtility.UrlEncode(TamperProofStringEncode(value, TamperProofKey))
End Function

Function QueryStringDecode(ByVal value As String) As String
Return TamperProofStringDecode(value, TamperProofKey)
End Function


<A href='yourpage.aspx?Data=<%= 
QueryStringEncode("Your Data String") %>'>HyperLink Text</A>



DataString = QueryStringDecode(Request.QueryString("Data"))
 
see this link also:

http://www.codeproject.com/aspnet/TamperProofQueryString.asp