I am trying to encrypt a string using the code below. The issue is I get this error and I have no clue (I'm just learning about encryption) what to do or even where to look. The SharedKey and the IV have been supplied as Hex values. The SharedKey is 64 bytes and the IV is 32 bytes.
System.Security.Cryptography.CryptographicException: 'Specified initialization vector (IV) does not match the block size for this algorithm.'
Public Function Encrypt(ByVal strValue As String) As String
'Create instance of a Rijndael Managed object
Dim aes As New RijndaelManaged
'Set appropriate values of object
aes.Padding = PaddingMode.PKCS7
aes.KeySize = 256
aes.Mode = CipherMode.CBC
'Create streams to work with encryption process
Dim msEncrypt As New MemoryStream()
'SharedKey = "64 byte string"
'IV = "32 byte string"
Dim SharedKey As Byte() = Encoding.GetEncoding(1252).GetBytes(strSharedKey)
Dim IV As Byte() = Encoding.GetEncoding(1252).GetBytes(strIV)
Dim csEncrypt As New CryptoStream(msEncrypt, aes.CreateEncryptor(SharedKey, IV), CryptoStreamMode.Write)
'Convert string value to byte array
Dim toEncrypt As Byte() = Encoding.GetEncoding(1252).GetBytes(strValue)
toEncrypt = Encoding.Convert(Encoding.GetEncoding(1252), Encoding.UTF8, toEncrypt)
'Perform encryption
csEncrypt.Write(toEncrypt, 0, toEncrypt.Length)
csEncrypt.FlushFinalBlock()
'Return Base64 string
Return Convert.ToBase64String(msEncrypt.ToArray())
'Dim u As System.Text.UnicodeEncoding = System.Text.Encoding.Unicode
'Dim a As System.Text.ASCIIEncoding = System.Text.Encoding.ASCII
'Return a.GetByteCount(SharedKey) '64 bytes
End Function
For CBC mode (and most other modes) the IV length must be the same as the block length. By default with the .NET CLR RijndaelManaged cipher, the block length is 128 bits (16 bytes). You can set this with
aes.BlockSize = 256
Which would allow a 32 byte IV, but also use blocks of 32 bytes.
Also, your comments suggest that you are using a 64 byte (512 bit) key. That should be a 32 byte (256 bit) key.
These are what I used. Whether or not the returned value is correct, I have no idea yet.
Public Function Encrypt(ByVal strValue As String) As String
'Create instance of a Rijndael Managed object
Dim aes As New RijndaelManaged
'Set appropriate values of object
aes.Padding = PaddingMode.PKCS7
aes.KeySize = 256
aes.Mode = CipherMode.CBC
'Create streams to work with encryption process
Dim msEncrypt As New MemoryStream()
Dim SharedKey As Byte()
'SharedKey = ""
'IV = ""
SharedKey = StringToByteArray(strSharedKey)
Dim IV As Byte()
IV = StringToByteArray(strIV)
Dim csEncrypt As New CryptoStream(msEncrypt, aes.CreateEncryptor(SharedKey, IV), CryptoStreamMode.Write)
'Convert string value to byte array
Dim toEncrypt As Byte() = Encoding.GetEncoding(1252).GetBytes(strValue)
toEncrypt = Encoding.Convert(Encoding.GetEncoding(1252), Encoding.UTF8, toEncrypt)
'Perform encryption
csEncrypt.Write(toEncrypt, 0, toEncrypt.Length)
csEncrypt.FlushFinalBlock()
'Return Base64 string
Return Convert.ToBase64String(msEncrypt.ToArray())
End Function
Function StringToByteArray(text As String) As Byte()
Dim bytes As Byte() = New Byte(text.Length \ 2 - 1) {}
For i As Integer = 0 To text.Length - 1 Step 2
bytes(i \ 2) = Byte.Parse(text(i).ToString() & text(i + 1).ToString(), System.Globalization.NumberStyles.HexNumber)
Next
Return bytes
End Function
Any other ideas would be very helpful
Related
i've found this function for VB.net and i used in an .aspx page and works.
Private Sub LoadImageFromURL(URL As String, ByRef Img As Drawing.Bitmap)
Const BYTESTOREAD As Integer = 10000
Dim myRequest As WebRequest = WebRequest.Create(URL)
Dim myResponse As WebResponse = myRequest.GetResponse()
Dim ReceiveStream As Stream = myResponse.GetResponseStream()
Dim br As New BinaryReader(ReceiveStream)
Dim memstream As New MemoryStream()
Dim bytebuffer As Byte() = New Byte(BYTESTOREAD - 1) {}
Dim BytesRead As Integer = br.Read(bytebuffer, 0, BYTESTOREAD)
While BytesRead > 0
memstream.Write(bytebuffer, 0, BytesRead)
BytesRead = br.Read(bytebuffer, 0, BYTESTOREAD)
End While
Img = New Drawing.Bitmap(memstream)
End Sub
I would like to limit the loading of a remote imagebased on:
1) Image size limit in Bytes
2) Max Dimension of the pic x,y
3) Accepted image types (jpg, png)
I'm not so expert on image manipulation so I ask for a little help to improve the function if is possible and to enable some sort of protection on the image URL tio avoid malicious use.
EDIT: I must use the function on a .aspx page
Thanks
I transformed into a function to validate the url and works.
Don't know if i can make it lighter and faster or if there is a better solution to do that.
Public Function ChkImageFromURL(URL As String) As Boolean
Dim myRequest As WebRequest = WebRequest.Create(URL)
myRequest.Method = WebRequestMethods.Http.Head
Dim myResponse As WebResponse = myRequest.GetResponse()
Dim ImageLen As Integer = myResponse.ContentLength
Dim ImageType As String = myResponse.ContentType
If ( Lcase(ImageType) <> "image/jpeg" AND Lcase(ImageType) <> "image/png" ) Or ImageLen > 300000 Then
return false
Else
return true
End if
End Function
I am totally lost. I build a Universal App (VB.net) which is consuming a web service on my (Azure Website Vb.net).
My Universal APP (UA) is sending userdata (Username an EmployeeNR) to a webservice and the Webservice is checking that data.
With TripleDES I encrypted the EmployeeNr and Username in the Universal and send it to the WebService. Now i am struggling how to decrypt the TripleDES on my WebService.
In the Universal App I work with Windows.Security.Cryptography which is not available on the Webservice site (asp.net).
I can only use System.Security.Cryptography.
I can encrypt and decrypt on Windows App site.
I also can encrpyt and decrypt on the Web Service site.
But if I pass an encrypted String form Win App to Web Service. Decryption is not working.
Problem is: On both sides, I use the same STRING, same Key and TripleDES encryption, but the result is different.
MY Encryption side - Windows Universal APP
Function myencrptor(ByVal Plaintext As String, ByVal mykey As String) As String
Dim crypt As SymmetricKeyAlgorithmProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.TripleDesCbcPkcs7)
Dim PlainTextbuffer As IBuffer = CryptographicBuffer.ConvertStringToBinary(Plaintext, BinaryStringEncoding.Utf8)
Dim mykeybuffer As IBuffer = CryptographicBuffer.ConvertStringToBinary(mykey, BinaryStringEncoding.Utf8)
Dim magickey As CryptographicKey = crypt.CreateSymmetricKey(mykeybuffer)
Dim signed As IBuffer = CryptographicEngine.Encrypt(magickey, PlainTextbuffer, Nothing)
Dim verschlüsselt As String = CryptographicBuffer.EncodeToBase64String(signed)
Return verschlüsselt
End Function
My Server Side
Partial Class regal_appsync_Default
Inherits System.Web.UI.Page
Public NotInheritable Class Simple3Des
Private xTripleDES As New TripleDESCryptoServiceProvider
Sub New(ByVal key As String)
' Initialize the crypto provider.
xTripleDES.Key = TruncateHash(key, xTripleDES.KeySize \ 8)
xTripleDES.IV = TruncateHash("", xTripleDES.BlockSize \ 8)
End Sub
Private Function TruncateHash(ByVal key As String, ByVal length As Integer) As Byte()
Dim sha1 As New SHA1CryptoServiceProvider
' Hash the key.
Dim keyBytes() As Byte = System.Text.Encoding.UTF8.GetBytes(key)
Dim hash() As Byte = sha1.ComputeHash(keyBytes)
' Truncate or pad the hash.
ReDim Preserve hash(length - 1)
Return hash
End Function
Public Function EncryptData(ByVal plaintext As String) As String
' Convert the plaintext string to a byte array.
Dim plaintextBytes() As Byte = System.Text.Encoding.UTF8.GetBytes(plaintext)
' Create the stream.
Dim ms As New System.IO.MemoryStream
' Create the encoder to write to the stream.
Dim encStream As New CryptoStream(ms,
xTripleDES.CreateEncryptor(),
System.Security.Cryptography.CryptoStreamMode.Write)
' Use the crypto stream to write the byte array to the stream.
encStream.Write(plaintextBytes, 0, plaintextBytes.Length)
encStream.FlushFinalBlock()
' Convert the encrypted stream to a printable string.
Return Convert.ToBase64String(ms.ToArray)
End Function
Public Function DecryptData(ByVal encryptedtext As String) As String
' Convert the encrypted text string to a byte array.
Dim encryptedBytes() As Byte = Convert.FromBase64String(encryptedtext)
' Create the stream.
Dim ms As New System.IO.MemoryStream
' Create the decoder to write to the stream.
Dim decStream As New CryptoStream(ms, xTripleDES.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write)
' Use the crypto stream to write the byte array to the stream.
decStream.Write(encryptedBytes, 0, encryptedBytes.Length)
decStream.FlushFinalBlock()
' Convert the plaintext stream to a string.
Return System.Text.Encoding.UTF8.GetString(ms.ToArray)
End Function
End Class
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Lbl1.Text = myEncoding(Txt1.Text)
End Sub
Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Lbl1.Text = myDecoding(Lbl1.Text)
End Sub
Function myEncoding(ByVal plainText As String) As String
Dim wrapper As New Simple3Des("012345678901234567891234")
Dim cipherText As String = wrapper.EncryptData(plainText)
Return cipherText
End Function
Function myDecoding(ByVal cipherText As String) As String
' DecryptData throws if the wrong password is used.
Dim wrapper As New Simple3Des("012345678901234567891234")
Try
Dim plainText As String = wrapper.DecryptData(cipherText)
Return plainText
Catch ex As System.Security.Cryptography.CryptographicException
Return "problem"
End Try
End Function
End Class
looking forward to any helpful tips!
best wishes
hendrik
I am trying to access a page where I need to log into the website and pass a a list of parameters. I appear to be able to log into the site (if I change the log in details I get a 401 unauthorised error) but then I get a 400 bad request error. The code is a bit hashed together so I know something is wrong but don't know where.
EDITED CODE
Public Sub TestConn()
Dim customeremailaddress As String = HttpUtility.UrlEncode("r.test#test.com")
Dim customername As String = HttpUtility.UrlEncode("Ryan")
Dim referenceid As String = HttpUtility.UrlEncode("ordertest123")
Dim languagecode As String = HttpUtility.UrlEncode("1043")
Dim expirydays As String = HttpUtility.UrlEncode("30")
Dim UserName As String = "testusername"
Dim password As String = "testpassword"
Dim siteCredentials As New NetworkCredential(UserName, password)
Dim URLAuth As String = "http://service.someurl.com/process.xml"
Dim postString As String = String.Format("customeremailaddress={0}&customername={1}&referenceid={2}&languagecode={3}&expirydays={4}", customeremailaddress, customername, referenceid, languagecode, expirydays)
Dim postBytes As Byte() = Encoding.UTF8.GetBytes(postString)
Const contentType As String = "application/x-www-form-urlencoded"
System.Net.ServicePointManager.Expect100Continue = False
Dim cookies As New CookieContainer()
Dim webRequest__1 As HttpWebRequest = TryCast(WebRequest.Create(URLAuth), HttpWebRequest)
webRequest__1.Method = "POST"
webRequest__1.ContentType = contentType
webRequest__1.CookieContainer = cookies
webRequest__1.ContentLength = postBytes.Length
webRequest__1.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1"
webRequest__1.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
webRequest__1.Referer = "http://service.someurl.com/process.xml"
webRequest__1.Credentials = siteCredentials
Try
Dim requestStream As Stream = webRequest__1.GetRequestStream()
requestStream.Write(postBytes, 0, postBytes.Length)
Dim responseReader As New StreamReader(webRequest__1.GetResponse().GetResponseStream())
Dim responseData As String = responseReader.ReadToEnd()
responseReader.Close()
webRequest__1.GetResponse().Close()
Catch ex As Exception
Lbl_ConnTest_error.Text = ex.Message
End Try
End Sub
You need to send the bytes of the postString not the string itself:
Dim postBytes As Byte() = Encoding.UTF8.GetBytes(postString)
...
webRequest__1.ContentLength = postBytes.Length
...
Dim requestStream As Stream = webRequest__1.GetRequestStream()
requestStream.Write(postBytes, 0, postBytes.Length)
More information here.
Can anyone give me an example for encrypt and decrypt an image using .net with asp.net
I want this encryption to the image when I save it into sql server as binary data.
Include these name spaces
using System.IO;
using System.Security.Cryptography;
For Encryption create below function:
private void EncryptFile(string inputFile, string outputFile)
{
try
{
string password = #"myKey123"; // Your Key Here
UnicodeEncoding UE = new UnicodeEncoding();
byte[] key = UE.GetBytes(password);
string cryptFile = outputFile;
FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create);
RijndaelManaged RMCrypto = new RijndaelManaged();
CryptoStream cs = new CryptoStream(fsCrypt,
RMCrypto.CreateEncryptor(key, key),
CryptoStreamMode.Write);
FileStream fsIn = new FileStream(inputFile, FileMode.Open);
int data;
while ((data = fsIn.ReadByte()) != -1)
cs.WriteByte((byte)data);
fsIn.Close();
cs.Close();
fsCrypt.Close();
}
catch
{
MessageBox.Show("Encryption failed!", "Error");
}
}
For Decryption create below function :
private void DecryptFile(string inputFile, string outputFile)
{
{
string password = #"myKey123"; // Your Key Here
UnicodeEncoding UE = new UnicodeEncoding();
byte[] key = UE.GetBytes(password);
FileStream fsCrypt = new FileStream(inputFile, FileMode.Open);
RijndaelManaged RMCrypto = new RijndaelManaged();
CryptoStream cs = new CryptoStream(fsCrypt,
RMCrypto.CreateDecryptor(key, key),
CryptoStreamMode.Read);
FileStream fsOut = new FileStream(outputFile, FileMode.Create);
int data;
while ((data = cs.ReadByte()) != -1)
fsOut.WriteByte((byte)data);
fsOut.Close();
cs.Close();
fsCrypt.Close();
}
}
You can call like this
EncryptFile(#"D:\OriginalImage.png", #"D:\VizioEncrypted.png"); //To Encrypt
DecryptFile(#"D:\VizioEncrypted.png", #"D:\VizioDecrypted.png"); //To Decrypt
This will help
Finally I found the solution for this problem.
I will add the code for helping who need that.
Encryption method:
Public Function EncryptStream(ByVal input As Byte()) As Byte()
Dim rijn As New RijndaelManaged()
Dim encrypted As Byte()
Dim key As Byte() = New Byte() {&H22, &HC0, &H6D, &HCB, &H23, &HA6, _
&H3, &H1B, &H5A, &H1D, &HD3, &H9F, _
&H85, &HD, &HC1, &H72, &HED, &HF4, _
&H54, &HE6, &HBA, &H65, &HC, &H22, _
&H62, &HBE, &HF3, &HEC, &H14, &H81, _
&HA8, &HA}
'32
Dim IV As Byte() = New Byte() {&H43, &HB1, &H93, &HB, &H1A, &H87, _
&H52, &H62, &HFB, &H8, &HD, &HC0, _
&HCA, &H40, &HC2, &HDB}
'16
'Get an encryptor.
Dim encryptor As ICryptoTransform = rijn.CreateEncryptor(key, IV)
'Encrypt the data.
Dim msEncrypt As New MemoryStream()
Dim csEncrypt As New CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)
'Write all data to the crypto stream and flush it.
csEncrypt.Write(input, 0, input.Length)
csEncrypt.FlushFinalBlock()
'Get encrypted array of bytes.
encrypted = msEncrypt.ToArray()
Return encrypted
End Function
Decryption Method:
Public Function DecryptStream(ByVal input As Byte()) As Byte()
Dim rijn As New RijndaelManaged()
Dim decrypted As Byte()
Dim key As Byte() = New Byte() {&H22, &HC0, &H6D, &HCB, &H23, &HA6, _
&H3, &H1B, &H5A, &H1D, &HD3, &H9F, _
&H85, &HD, &HC1, &H72, &HED, &HF4, _
&H54, &HE6, &HBA, &H65, &HC, &H22, _
&H62, &HBE, &HF3, &HEC, &H14, &H81, _
&HA8, &HA}
'32
Dim IV As Byte() = New Byte() {&H43, &HB1, &H93, &HB, &H1A, &H87, _
&H52, &H62, &HFB, &H8, &HD, &HC0, _
&HCA, &H40, &HC2, &HDB}
'16
'Get a decryptor that uses the same key and IV as the encryptor.
Dim decryptor As ICryptoTransform = rijn.CreateDecryptor(key, IV)
'Now decrypt the previously encrypted message using the decryptor
' obtained in the above step.
Dim msDecrypt As New MemoryStream(input)
Dim csDecrypt As New CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)
decrypted = New Byte(input.Length - 1) {}
'Read the data out of the crypto stream.
csDecrypt.Read(decrypted, 0, decrypted.Length)
Return decrypted
End Function
I need to encrypt and decrypt a querystring in ASP.NET.
The querystring might look something like this:
http://www.mysite.com/report.aspx?id=12345&year=2008
How do I go about encrypting the entire querystring so that it looks something like the following?
http://www.mysite.com/report.aspx?crypt=asldjfaf32as98df8a
And then, of course, how to I decrypt it? What's the best encryption to use for something like this? TripleDES?
Here is a way to do it in VB From: http://www.devcity.net/Articles/47/1/encrypt_querystring.aspx
Wrapper for the encryption code: Pass your querystring parameters into this, and change the key!!!
Private _key as string = "!#$a54?3"
Public Function encryptQueryString(ByVal strQueryString As String) As String
Dim oES As New ExtractAndSerialize.Encryption64()
Return oES.Encrypt(strQueryString, _key)
End Function
Public Function decryptQueryString(ByVal strQueryString As String) As String
Dim oES As New ExtractAndSerialize.Encryption64()
Return oES.Decrypt(strQueryString, _key)
End Function
Encryption Code:
Imports System
Imports System.IO
Imports System.Xml
Imports System.Text
Imports System.Security.Cryptography
Public Class Encryption64
Private key() As Byte = {}
Private IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}
Public Function Decrypt(ByVal stringToDecrypt As String, _
ByVal sEncryptionKey As String) As String
Dim inputByteArray(stringToDecrypt.Length) As Byte
Try
key = System.Text.Encoding.UTF8.GetBytes(Left(sEncryptionKey, 8))
Dim des As New DESCryptoServiceProvider()
inputByteArray = Convert.FromBase64String(stringToDecrypt)
Dim ms As New MemoryStream()
Dim cs As New CryptoStream(ms, des.CreateDecryptor(key, IV), _
CryptoStreamMode.Write)
cs.Write(inputByteArray, 0, inputByteArray.Length)
cs.FlushFinalBlock()
Dim encoding As System.Text.Encoding = System.Text.Encoding.UTF8
Return encoding.GetString(ms.ToArray())
Catch e As Exception
Return e.Message
End Try
End Function
Public Function Encrypt(ByVal stringToEncrypt As String, _
ByVal SEncryptionKey As String) As String
Try
key = System.Text.Encoding.UTF8.GetBytes(Left(SEncryptionKey, 8))
Dim des As New DESCryptoServiceProvider()
Dim inputByteArray() As Byte = Encoding.UTF8.GetBytes( _
stringToEncrypt)
Dim ms As New MemoryStream()
Dim cs As New CryptoStream(ms, des.CreateEncryptor(key, IV), _
CryptoStreamMode.Write)
cs.Write(inputByteArray, 0, inputByteArray.Length)
cs.FlushFinalBlock()
Return Convert.ToBase64String(ms.ToArray())
Catch e As Exception
Return e.Message
End Try
End Function
End Class
Encryption in C# using AES encryption-
protected void Submit(object sender, EventArgs e)
{
string name = HttpUtility.UrlEncode(Encrypt(txtName.Text.Trim()));
string technology = HttpUtility.UrlEncode(Encrypt(ddlTechnology.SelectedItem.Value));
Response.Redirect(string.Format("~/CS2.aspx?name={0}&technology={1}", name, technology));
}
AES Algorithm Encryption and Decryption functions
private string Encrypt(string clearText)
{
string EncryptionKey = "hyddhrii%2moi43Hd5%%";
byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
}
clearText = Convert.ToBase64String(ms.ToArray());
}
}
return clearText;
}
private string Decrypt(string cipherText)
{
string EncryptionKey = "hyddhrii%2moi43Hd5%%";
cipherText = cipherText.Replace(" ", "+");
byte[] cipherBytes = Convert.FromBase64String(cipherText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.Close();
}
cipherText = Encoding.Unicode.GetString(ms.ToArray());
}
}
return cipherText;
}
To Decrypt
lblName.Text = Decrypt(HttpUtility.UrlDecode(Request.QueryString["name"]));
lblTechnology.Text = Decrypt(HttpUtility.UrlDecode(Request.QueryString["technology"]));
I can't give you a turn key solution off the top of my head, but you should avoid TripleDES since it is not as secure as other encryption methods.
If I were doing it, I'd just take the entire URL (domain and querystring) as a URI object, encrypt it with one of the built-in .NET libraries and supply it as the crypt object. When I need to decrypt it, do so, then create a new URI object, which will let you get everything back out of the original querystring.
I was originally going to agree with Joseph Bui on the grounds that it would be more processor efficient to use the POST method instead, web standards dictate that if the request is not changing data on the server, the GET method should be used.
It will be much more code to encrypt the data than to just use POST.
Here's a sort of fancy version of the decrypt function from Brian's example above that you could use if you were only going to use this for the QueryString as it returns a NameValueCollection instead of a string. It also contains a slight correction as Brian's example will break without
stringToDecrypt = stringToDecrypt.Replace(" ", "+")
if there are any 'space' characters in the string to decrypt:
Public Shared Function DecryptQueryString(ByVal stringToDecrypt As String, ByVal encryptionKey As String) As Collections.Specialized.NameValueCollection
Dim inputByteArray(stringToDecrypt.Length) As Byte
Try
Dim key() As Byte = System.Text.Encoding.UTF8.GetBytes(encryptionKey.Substring(0, encryptionKey.Length))
Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}
Dim des As New DESCryptoServiceProvider()
stringToDecrypt = stringToDecrypt.Replace(" ", "+")
inputByteArray = Convert.FromBase64String(stringToDecrypt)
Dim ms As New MemoryStream()
Dim cs As New CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write)
cs.Write(inputByteArray, 0, inputByteArray.Length)
cs.FlushFinalBlock()
Dim encoding As System.Text.Encoding = System.Text.Encoding.UTF8
Dim decryptedString As String = encoding.GetString(ms.ToArray())
Dim nameVals() As String = decryptedString.Split(CChar("&"))
Dim queryString As New Collections.Specialized.NameValueCollection(nameVals.Length)
For Each nameValPair As String In nameVals
Dim pair() As String = nameValPair.Split(CChar("="))
queryString.Add(pair(0), pair(1))
Next
Return queryString
Catch e As Exception
Throw New Exception(e.Message)
End Try
End Function
I hope you find this useful!
Why are you trying to encrypt your query string? If the data is sensitive, you should be using SSL. If you are worried about someone looking over the user's shoulder, use form POST instead of GET.
I think it is pretty likely that there is a better solution for your fundamental problem than encrypting the query string.