How can I encrypt a querystring in asp.net? - 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.

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

Encryption and decryption without special character

I want to encrypt mail id. The encrypted mail id should not contain special characters.
I send mail from console app. In console app I encode the mail id and attach it in link that will perform my click counts. In the web app I am decoding the mail id passed. So if encrypted mail id contains special character it is disturbing my link.
I am using following:
string EncryptedEmailId;
string EncryptionKey = "MAKV2SPBNI99212";
byte[] EmailIdEncrypt = Encoding.Unicode.GetBytes(InvEmail);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdbEncrypt = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdbEncrypt.GetBytes(32);
encryptor.IV = pdbEncrypt.GetBytes(16);
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
csEncrypt.Write(EmailIdEncrypt, 0, EmailIdEncrypt.Length);
csEncrypt.Close();
}
EncryptedEmailId = Convert.ToBase64String(msEncrypt.ToArray());
}
}
individualContent = individualContent.Replace("[MailId]", EncryptedEmailId);
With the hint given by Nipun I got the answer.
a) Convert String to Hex
public static string ConvertStringToHex(String input, System.Text.Encoding encoding)
{
Byte[] stringBytes = encoding.GetBytes(input);
StringBuilder sbBytes = new StringBuilder(stringBytes.Length * 2);
foreach (byte b in stringBytes)
{
sbBytes.AppendFormat("{0:X2}", b);
}
return sbBytes.ToString();
}
b) Convert Hex to String
public static string ConvertHexToString(String hexInput, System.Text.Encoding encoding)
{
int numberChars = hexInput.Length;
byte[] bytes = new byte[numberChars / 2];
for (int i = 0; i < numberChars; i += 2)
{
bytes[i / 2] = Convert.ToByte(hexInput.Substring(i, 2), 16);
}
return encoding.GetString(bytes);
}
Sample usage code
string testString = "MIKA#?&^";
string hex = ConvertStringToHex(testString, System.Text.Encoding.Unicode);
string normal = ConvertHexToString(hex, System.Text.Encoding.Unicode);
Debug.Assert(testString.CompareTo(normal) == 0, "They are not identical");
Have a look at: http://www.nullskull.com/faq/834/convert-string-to-hex-and-hex-to-string-in-net.aspx
You will need to try different Algo for the same
Try anyof the below methods and see if it works for you?
This won't be working you as you are using Console App, but can try other one.
string EncryptedText = FormsAuthentication.HashPasswordForStoringInConfigFile("YourPlainText", "MD5");
Or, you may use the following encryption and decryption algorithm:
using System.IO;
using System.Text;
using System.Security.Cryptography;
/// <summary>
/// Summary description for Pass
/// </summary>
public class CryptoSystem
{
public string plainText;
public string passPhrase = "Pas5pr#se";
public string saltValue = "s#1tValue";
public string hashAlgorithm = "MD5";
public int passwordIterations = 2;
public string initVector = "#1B2c3D4e5F6g7H8";
public int keySize = 256;
public string Encrypt(string plainText)
{
byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations);
byte[] keyBytes = password.GetBytes(keySize / 8);
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] cipherTextBytes = memoryStream.ToArray();
memoryStream.Close();
cryptoStream.Close();
string cipherText = Convert.ToBase64String(cipherTextBytes);
return cipherText;
}
public string Decrypt(string cipherText)
{
byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations);
byte[] keyBytes = password.GetBytes(keySize / 8);
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
byte[] plainTextBytes = new byte[cipherTextBytes.Length];
int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
memoryStream.Close();
cryptoStream.Close();
string plainText = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
return plainText;
}
}
Try out Hexadecimal as well
http://www.string-functions.com/string-hex.aspx
To code follow this link
Convert string to hex-string in C#
byte[] ba = Encoding.Default.GetBytes("sample");
var hexString = BitConverter.ToString(ba);

Asp.net code not working for implementing rijndael encryption, decryption?

I'm reading a book entitled beginning asp.net security from wrox and I'm in this part where it shows a code snippet for using rijndael the problem this example is not included in the downloadable source codes. I decided to seek (professional)help here in the forums.
It would be awesome if you try and test it as well and hopefully give an example(codes) on how I could implement it.
Here is the code:
public class EncryptionRijndael
{
public EncryptionRijndael()
{
//
// TODO: Add constructor logic here
//
}
public static byte[] GenerateRandomBytes(int length)
{
byte[] key = new byte[length];
RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider();
provider.GetBytes(key);
return key;
}
public void GetKeyAndIVFromPasswordAndSalt(string password, byte[] salt,SymmetricAlgorithm symmetricAlgorithm,ref byte[] key, ref byte[] iv)
{
Rfc2898DeriveBytes rfc2898DeriveBytes =
new Rfc2898DeriveBytes(password, salt);
key =
rfc2898DeriveBytes.GetBytes(symmetricAlgorithm.KeySize / 8);
iv =
rfc2898DeriveBytes.GetBytes(symmetricAlgorithm.BlockSize / 8);
}
public static byte[] Encrypt(byte[] clearText, byte[] key, byte[] iv)
{
// Create an instance of our encyrption algorithm.
RijndaelManaged rijndael = new RijndaelManaged();
// Create an encryptor using our key and IV
ICryptoTransform transform = rijndael.CreateEncryptor(key, iv);
// Create the streams for input and output
MemoryStream outputStream = new MemoryStream();
CryptoStream inputStream = new CryptoStream(
outputStream,
transform,
CryptoStreamMode.Write);
// Feed our data into the crypto stream.
inputStream.Write(clearText, 0, clearText.Length);
// Flush the crypto stream.
inputStream.FlushFinalBlock();
// And finally return our encrypted data.
return outputStream.ToArray();
}
static byte[] Decrypt(byte[] cipherText, byte[] key, byte[] iv)
{
// Create an instance of our encyrption algorithm.
RijndaelManaged rijndael = new RijndaelManaged();
// Create an decryptor using our key and IV ;
ICryptoTransform transform = rijndael.CreateDecryptor(key, iv);
// Create the streams for input and output
MemoryStream outputStream = new MemoryStream();
CryptoStream inputStream = new CryptoStream(outputStream,transform,CryptoStreamMode.Write);
// Feed our data into the crypto stream.
inputStream.Write(cipherText, 0, cipher.Length);
// Flush the crypto stream.
inputStream.FlushFinalBlock();
// And finally return our decrypted data.
return outputStream.ToArray();
}
}
Sir/Ma'am your answers would be of great help. Thank you++
(it would be awesome if you could show me how to call encrypt and decrypt properly)
I have found that it is best to create a class to wrap your credentials and a separate one to do the encryption. Here is what I created... sorry it's in vb instead of c#:
Public Class SymmetricEncryptionCredentials
Private _keyIterations As Integer
Public ReadOnly Property ivString As String
Get
Return Convert.ToBase64String(Me.iv)
End Get
End Property
Public ReadOnly Property saltString() As String
Get
Return Convert.ToBase64String(Me.salt)
End Get
End Property
Public ReadOnly Property keyIterations As Integer
Get
Return _keyIterations
End Get
End Property
Private Property keyPassword() As String
Private Property salt() As Byte()
Private ReadOnly Property key() As Security.Cryptography.Rfc2898DeriveBytes
Get
Return New Security.Cryptography.Rfc2898DeriveBytes(keyPassword, salt, keyIterations)
End Get
End Property
Private Property iv() As Byte()
''' <summary>
''' Creates a set of encryption credentials based on the
''' provided key, ivPassword, and salt string.
''' </summary>
''' <param name="keyPassword">The Secret key used for encryption</param>
''' <param name="salt">The salt string (not secret) from which the salt
''' bytes are derived.</param>
''' <remarks></remarks>
Public Sub New(ByVal keyPassword As String, ByVal salt As String, ByVal iv As String, ByVal keyIterations As Integer)
Me.keyPassword = keyPassword
Me.iv = Convert.FromBase64String(iv)
Me.salt = Convert.FromBase64String(salt)
_keyIterations = keyIterations
End Sub
''' <summary>
''' Creates a new set of encryption credentials based on the
''' provided key, while making a ivPassword and salt.
''' </summary>
''' <param name="keyPassword">The Secret key used for encryption</param>
''' <remarks>Creates a new set of encryption credentials based on the
''' provided key password, while making a ivPassword and salt.</remarks>
Public Sub New(ByVal keyPassword As String, ByVal keyIterations As Integer)
Me.keyPassword = keyPassword
Me.iv = Passwords.GetRandomPassword(16, 16)
Me.salt = Passwords.GetRandomPassword()
_keyIterations = keyIterations
End Sub
''' <summary>
''' Creates a new set of encryption credentials based on the
''' provided key, while making a ivPassword and salt. Uses
''' default PBKDF iteration count.
''' </summary>
''' <param name="keyPassword">The Secret key used for encryption</param>
''' <remarks>Creates a new set of encryption credentials based on the
''' provided key password, while making a ivPassword and salt.</remarks>
Public Sub New(ByVal keyPassword As String)
Me.New(keyPassword, AppSettings("defaultKeyPBKDFIterations"))
End Sub
''' <summary>
''' Gets an AES Encryptor with key derived from RFC2898.
''' </summary>
''' <returns></returns>
''' <remarks></remarks>
Public Function GetAESEncryptor() As Security.Cryptography.ICryptoTransform
Dim aes As New Security.Cryptography.AesManaged
aes.KeySize = 256
aes.Key = Me.key.GetBytes(aes.KeySize / 8)
aes.IV = Me.iv
Return aes.CreateEncryptor()
End Function
Public Function GetAESDecryptor() As Security.Cryptography.ICryptoTransform
Dim aes As New Security.Cryptography.AesManaged
aes.KeySize = 256
aes.Key = Me.key.GetBytes(aes.KeySize / 8)
aes.IV = Me.iv
Return aes.CreateDecryptor
End Function
End Class
Public Class SymmetricEncryption
Public Shared Function Encrypt(ByVal unencryptedValue As String, creds As SymmetricEncryptionCredentials) As String
Dim inBytes() As Byte = System.Text.Encoding.UTF8.GetBytes(unencryptedValue)
Dim outBytes() As Byte
Using outStream As New IO.MemoryStream()
Using encryptStream As New System.Security.Cryptography.CryptoStream(outStream, creds.GetAESEncryptor, Security.Cryptography.CryptoStreamMode.Write)
encryptStream.Write(inBytes, 0, inBytes.Length)
encryptStream.FlushFinalBlock()
outBytes = outStream.ToArray
encryptStream.Close()
End Using
outStream.Close()
End Using
Dim outString As String = Convert.ToBase64String(outBytes)
Return outString
End Function
Public Shared Function Decrypt(ByVal encryptedValue As String, creds As SymmetricEncryptionCredentials) As String
Dim inBytes() As Byte = Convert.FromBase64String(encryptedValue)
Dim outString As String
Using outStream As New IO.MemoryStream
Using decryptionStream As New System.Security.Cryptography.CryptoStream(outStream, creds.GetAESDecryptor, Security.Cryptography.CryptoStreamMode.Write)
decryptionStream.Write(inBytes, 0, inBytes.Length)
decryptionStream.FlushFinalBlock()
Dim outBytes() As Byte = outStream.ToArray
outString = System.Text.Encoding.UTF8.GetString(outBytes)
decryptionStream.Close()
End Using
outStream.Close()
End Using
Return outString
End Function
End Class
Public Class Passwords
Public Shared Function GetRandomPassword(minLength As Integer, maxlength As Integer) As Byte()
' *** 1. Get how long the password will be
Dim rand As New Random
Dim passLength As Integer = rand.Next(minLength, maxlength)
' *** 2. Create an array of Bytes to hold the
' random numbers used to make the string's chars
Dim passBytes(passLength - 1) As Byte
' *** 3. Fill the array with random bytes.
Dim rng As New Security.Cryptography.RNGCryptoServiceProvider
rng.GetBytes(passBytes)
Return passBytes
End Function
Public Shared Function GetRandomPassword() As Byte()
Return GetRandomPassword(12, 32)
End Function
End Class

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));
}
}
}
}

Encrypt and Decrypt Image .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

Resources