Encrypt and Decrypt Image .net - asp.net

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

Related

AES string encryption "Invalid IV block size"

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

Passing values to an XML file

I have a web application that sends the contents of a form to another site. This other i can pass the log in information without issue and the page authenticates alright but I don't know how to pass an array of information that is required at the other end. The array contain setting names and their respective setting values. I have this working in PHP but don't know how to do it in ASP.net
In PHP I use this for the array:
$aParams = array(
'customeremailaddress' => 'mr.test#test.com',
'customername' => 'mr test',
'exlibrisfile' => '#/ePubs/Ex-Libris.png'
);
And to send the array:
curl_setopt($rCurl, CURLOPT_POSTFIELDS, $aParams);
Here is the VB code I have ended up with that returns a 400 bad request error:
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)
webRequest__1.ContentLength = postBytes.Length
Dim requestStream As Stream = webRequest__1.GetRequestStream()
requestStream.Write(postBytes, 0, postBytes.Length)
The complete code:
Public Sub TestConn()
Dim customeremailaddress As String = "mr.test#test.com"
Dim customername As String = "mr test"
Dim referenceid As String = "ordertest123"
Dim languagecode As String = "1043"
Dim expirydays As String = "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
Dim requestStream As Stream = webRequest__1.GetRequestStream()
requestStream.Write(postBytes, 0, postBytes.Length)
Dim requestWriter As New StreamWriter(webRequest__1.GetRequestStream())
Dim responseReader As New StreamReader(webRequest__1.GetResponse().GetResponseStream())
Dim responseData As String = responseReader.ReadToEnd()
responseReader.Close()
webRequest__1.GetResponse().Close()
End sub
This is my code to post data to another url.
Text is the form url-econded string.
Hope this can help
C#
private string PostData(string text)
{
WebRequest request = WebRequest.Create(url);
request.Method = "POST";
byte[] byteArray = Encoding.UTF8.GetBytes(text);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
using(WebResponse response = request.GetResponse())
using (Stream dataStream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(dataStream))
{
return reader.ReadToEnd();
}
}
VB.NET
Private Function PostData(text As String) As String
Dim request As WebRequest = WebRequest.Create(url)
request.Method = "POST"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(text)
request.ContentType = "application/x-www-form-urlencoded"
request.ContentLength = byteArray.Length
Using dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
End Using
Using response As WebResponse = request.GetResponse()
Using dataStream As Stream = response.GetResponseStream()
Using reader As New StreamReader(dataStream)
Return reader.ReadToEnd()
End Using
End Using
End Using
End Function

Combine multiple byte array images into one

I can create an image on the server from a byte array stored in the database. But how do I combine each byte array into one image. Basically I want to stack them on top of each other (they are all 1366px width and 618px height) and then save that to a png image. I will then get that image from the server and return to the web page (which I can do now for one image). Hope you can help.
This code in asp.net web forms creates an image which i return the filename as a return in a webmethod function back to the browser.
Public Shared Function Base64ToImage(ByVal base64String As String, ByVal id As String) As String
'http://www.dailycoding.com/Posts/convert_image_to_base64_string_and_base64_string_to_image.aspx
' Convert Base64 String to byte[]
Dim sFileName As String = String.Empty
Try
Dim imageBytes As Byte() = Convert.FromBase64String(base64String)
Dim ms As New MemoryStream(imageBytes, 0, imageBytes.Length)
' Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length)
Dim image__1 As Image = Image.FromStream(ms, True)
sFileName = "img_" & id & ".png"
Dim sPath As String = HttpContext.Current.Server.MapPath("images\")
image__1.Save(sPath & sFileName, System.Drawing.Imaging.ImageFormat.Png)
Catch ex As Exception
End Try
'
Return sFileName
End Function
I have tried this, looping through the records and then trying to combine them with sourcecopy but I can't get it to combine them?
Public Shared Function Base64ToImage2(ByVal dt As DataTable) As String
' Convert Base64 String to byte[]
Dim sFileName As String = String.Empty
Dim base64String As String, id As String
'if first record create image
'on 2nd or greater in dt then combine images
Try
Dim iCount As Integer = 0
Dim image__1 As Image = Nothing
Dim compositeImage As Image = Nothing
Dim sPath As String = String.Empty
If dt.Rows.Count > 0 Then
For Each myRow As DataRow In dt.Rows
'getImage = getImage() & Base64ToImage(myRow("image_data").ToString(), myRow("id").ToString()) & "|"
If iCount = 0 Then
Dim imageBytes As Byte() = Convert.FromBase64String(myRow("image_data").ToString())
Dim ms As New MemoryStream(imageBytes, 0, imageBytes.Length)
' Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length)
image__1 = System.Drawing.Image.FromStream(ms)
'sFileName = "img_1.png"
'sPath = HttpContext.Current.Server.MapPath("images\")
'image__1.Save(sPath & sFileName, System.Drawing.Imaging.ImageFormat.Png)
'compositeImage = New Bitmap(image__1.Width, image__1.Height)
Else
Dim imageBytes As Byte() = Convert.FromBase64String(myRow("image_data").ToString())
Dim ms2 As New MemoryStream(imageBytes, 0, imageBytes.Length)
' Convert byte[] to Image
ms2.Write(imageBytes, 0, imageBytes.Length)
Dim image__2 As Image = System.Drawing.Image.FromStream(ms2)
Dim g As Graphics = Graphics.FromImage(image__1)
g.CompositingMode = CompositingMode.SourceCopy
g.DrawImage(image__2, 0, image__1.Height)
sFileName = "img_1.png"
'sPath = HttpContext.Current.Server.MapPath("images\")
'image__2.Save(sPath & sFileName, System.Drawing.Imaging.ImageFormat.Png)
End If
iCount = iCount + 1
Next myRow
End If
'sFileName = "img_1.png"
'Dim sPath As String = HttpContext.Current.Server.MapPath("images\")
'compositeImage.Save(sPath & sFileName, System.Drawing.Imaging.ImageFormat.Png)
Catch ex As Exception
End Try
'
Return sFileName
End Function
Solved! After a ton of searching and reading I was able to combine png images into one! Each image is created from a memory stream and then appended to a bitmap with NewRectangle which is the key. Once I loop through the records from the database, I have one image which is downloaded to the client in a webmethod return. The width and height are pulled from the client to the webmethod and passed into the function so the image is scaled to fit the browser inner dimensions (to avoid any scrollbars).
JS on the client for the dimensions:
mywidth = window.innerWidth
myheight = window.innerHeight
The code to convert the base64 byte image is as follows...
Public Shared Function Base64ToImage2(ByVal dt As DataTable, ByVal Image_Width As String, ByVal Image_Height As String) As String
Dim sFileName As String = String.Empty
Dim sPath As String = HttpContext.Current.Server.MapPath("images\")
Dim myimage As Image = Nothing
' Create a new bitmap object 400 pixels wide by 60 pixels high
Dim objBitmap As New Bitmap(CInt(Image_Width), CInt(Image_Height))
'' Create a graphics object from the bitmap
Dim objGraphic As Graphics = Graphics.FromImage(objBitmap)
'if first record create image
'on 2nd or greater in dt then combine images
Try
If dt.Rows.Count > 0 Then
For Each myRow As DataRow In dt.Rows
Dim imageBytes As Byte() = Convert.FromBase64String(myRow("image_data").ToString())
Dim ms As New MemoryStream(imageBytes, 0, imageBytes.Length)
' Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length)
myimage = System.Drawing.Image.FromStream(ms)
objGraphic.DrawImage(myimage, New Rectangle(0, 0, CInt(Image_Width), CInt(Image_Height)))
Next myRow
sFileName = "img_1.png"
objBitmap.Save(sPath & sFileName, System.Drawing.Imaging.ImageFormat.Png)
End If
Catch ex As Exception
End Try
'
Return sFileName
End Function
In case someone else is looking for something similar in C# where you're trying to load an image source with the result, here's the code:
private void LoadImage()
{
string src = string.empty;
byte[] mergedImageData = new byte[0];
mergedImageData = MergeTwoImageByteArrays(watermarkByteArray, backgroundImageByteArray);
src = "data:image/png;base64," + Convert.ToBase64String(mergedImageData);
MyImage.ImageUrl = src;
}
private byte[] MergeTwoImageByteArrays(byte[] imageBytes, byte[] imageBaseBytes)
{
byte[] mergedImageData = new byte[0];
using (var msBase = new MemoryStream(imageBaseBytes))
{
System.Drawing.Image imgBase = System.Drawing.Image.FromStream(msBase);
Graphics gBase = Graphics.FromImage(imgBase);
using (var msInfo = new MemoryStream(imageBytes))
{
System.Drawing.Image imgInfo = System.Drawing.Image.FromStream(msInfo);
Graphics gInfo = Graphics.FromImage(imgInfo);
gBase.DrawImage(imgInfo, new Point(0, 0));
//imgBase.Save(Server.MapPath("_____testImg.png"), ImageFormat.Png);
MemoryStream mergedImageStream = new MemoryStream();
imgBase.Save(mergedImageStream, ImageFormat.Png);
mergedImageData = mergedImageStream.ToArray();
mergedImageStream.Close();
}
}
return mergedImageData;
}

Encrypting in ASP.NET

I have a VBScript script which I would like to run in ASP.NET, is there anyone who can help on rewriting this function in ASP.NET , C# , so that it returns the same algorithm of encryption? This was an ASP.NET Encryption function, converted for Classic ASP usage, but I need to get it working on the ASP.NET code.. How would this code look like in ASP.NET considering its using an ASP.NET Encryption method?
Public Function EncryptAES(ByVal sIn As String, ByVal sKey As String) As String
Dim AES As New RijndaelManaged
Dim ahashMD5 As New MD5CryptoServiceProvider()
AES.Key = ahashMD5.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(sKey))
AES.Mode = CipherMode.ECB
Dim AESEncrypt As ICryptoTransform = AES.CreateEncryptor()
Dim aBuffer As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(sIn)
Return Convert.ToBase64String(AESEncrypt.TransformFinalBlock(aBuffer, 0, aBuffer.Length))
End Function
Public Function DecryptAES(ByVal sOut As String, ByVal sKey As String) As String
Dim dAES As New RijndaelManaged
Dim dahashMD5 As New MD5CryptoServiceProvider()
dAES.Key = dahashMD5.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(sKey))
dAES.Mode = CipherMode.ECB
Dim dAESDecrypt As ICryptoTransform = dAES.CreateDecryptor()
sOut = Replace(sOut, " ", "+", 1, -1, CompareMethod.Text)
Dim daBuffer As Byte() = Convert.FromBase64String(sOut)
Return System.Text.ASCIIEncoding.ASCII.GetString(dAESDecrypt.TransformFinalBlock(daBuffer, 0, daBuffer.Length))
End Function
I have a Classic ASP script
Man, this is pure .NET code. So converting .NET to .NET hardly makes sense.
If you want to convert this VB.NET code to C#, here's how it would look like:
public string EncryptAES(string sIn, string sKey)
{
RijndaelManaged AES = new RijndaelManaged();
MD5CryptoServiceProvider ahashMD5 = new MD5CryptoServiceProvider();
AES.Key = ahashMD5.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(sKey));
AES.Mode = CipherMode.ECB;
ICryptoTransform AESEncrypt = AES.CreateEncryptor();
byte[] aBuffer = System.Text.ASCIIEncoding.ASCII.GetBytes(sIn);
return Convert.ToBase64String(AESEncrypt.TransformFinalBlock(aBuffer, 0, aBuffer.Length));
}
public string DecryptAES(string sOut, string sKey)
{
RijndaelManaged dAES = new RijndaelManaged();
MD5CryptoServiceProvider dahashMD5 = new MD5CryptoServiceProvider();
dAES.Key = dahashMD5.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(sKey));
dAES.Mode = CipherMode.ECB;
ICryptoTransform dAESDecrypt = dAES.CreateDecryptor();
sOut = sOut.Replace(" ", "+");
byte[] daBuffer = Convert.FromBase64String(sOut);
return System.Text.ASCIIEncoding.ASCII.GetString(dAESDecrypt.TransformFinalBlock(daBuffer, 0, daBuffer.Length));
}
You can always use the Telerik Code Converter.
Find below.
public string EncryptAES(string sIn, string sKey)
{
RijndaelManaged AES = new RijndaelManaged();
MD5CryptoServiceProvider ahashMD5 = new MD5CryptoServiceProvider();
AES.Key = ahashMD5.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(sKey));
AES.Mode = CipherMode.ECB;
ICryptoTransform AESEncrypt = AES.CreateEncryptor();
byte[] aBuffer = System.Text.ASCIIEncoding.ASCII.GetBytes(sIn);
return Convert.ToBase64String(AESEncrypt.TransformFinalBlock(aBuffer, 0, aBuffer.Length));
}
public string DecryptAES(string sOut, string sKey)
{
RijndaelManaged dAES = new RijndaelManaged();
MD5CryptoServiceProvider dahashMD5 = new MD5CryptoServiceProvider();
dAES.Key = dahashMD5.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(sKey));
dAES.Mode = CipherMode.ECB;
ICryptoTransform dAESDecrypt = dAES.CreateDecryptor();
sOut = Strings.Replace(sOut, " ", "+", 1, -1, CompareMethod.Text);
byte[] daBuffer = Convert.FromBase64String(sOut);
return System.Text.ASCIIEncoding.ASCII.GetString(dAESDecrypt.TransformFinalBlock(daBuffer, 0, daBuffer.Length));
}
You can use this tool to convert your VB.Net code to C#.
As #Darin Dimitrov pointed out this is definitely VB.Net which is definitely NOT VBScript/VB6/ASP Classic
Unfortunately conversion tools don't fix problems with code. All those disposable objects are giving me panic attacks.
public string EncryptAES(string sIn, string sKey)
{
using (var secure = new RijndaelManaged())
{
using (var ahashMd5 = new MD5CryptoServiceProvider())
{
secure.Key = ahashMd5.ComputeHash(Encoding.ASCII.GetBytes(sKey));
secure.Mode = CipherMode.ECB;
using (ICryptoTransform aesEncrypt = secure.CreateEncryptor())
{
byte[] aBuffer = Encoding.ASCII.GetBytes(sIn);
return Convert.ToBase64String(
aesEncrypt.TransformFinalBlock(
aBuffer, 0, aBuffer.Length));
}
}
}
}
public string DecryptAES(string sOut, string sKey)
{
using (var secure = new RijndaelManaged())
{
using (var dahashMd5 = new MD5CryptoServiceProvider())
{
secure.Key = dahashMd5.ComputeHash(Encoding.ASCII.GetBytes(sKey));
secure.Mode = CipherMode.ECB;
using (ICryptoTransform dAesDecrypt = secure.CreateDecryptor())
{
sOut = sOut.Replace(" ", "+");
byte[] daBuffer = Convert.FromBase64String(sOut);
return Encoding.ASCII.GetString(
dAesDecrypt.TransformFinalBlock(
daBuffer, 0, daBuffer.Length));
}
}
}
}

How can I encrypt a querystring in asp.net?

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.

Resources