Encrypting in ASP.NET - 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));
}
}
}
}

Related

Datatype of encrypted password

I want to encrypt my password and store to my DB, SQL Server 2008 R2.
For that I took the password from text box and encrypted using proper function and want to store in back end.
Tell me which datatype I have to use for encrypted password column.
Namespace:
using System.Security.Cryptography;
Encrypt Function:
public static string Encrypt(string Message)
{
string Password = Message;
byte[] Results;
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Password));
TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
TDESAlgorithm.Key = TDESKey;
TDESAlgorithm.Mode = CipherMode.ECB;
TDESAlgorithm.Padding = PaddingMode.PKCS7;
byte[] DataToEncrypt = UTF8.GetBytes(Message);
try
{
ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor();
Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length);
}
finally
{
TDESAlgorithm.Clear();
HashProvider.Clear();
}
return Convert.ToBase64String(Results);
}
Decrypt Function:
public static string Decrypt(string Message)
{
string Password = Message;
byte[] Results;
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Password));
TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
TDESAlgorithm.Key = TDESKey;
TDESAlgorithm.Mode = CipherMode.ECB;
TDESAlgorithm.Padding = PaddingMode.PKCS7;
byte[] DataToDecrypt = Convert.FromBase64String(Message);
try
{
ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();
Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);
}
finally
{
TDESAlgorithm.Clear();
HashProvider.Clear();
}
return UTF8.GetString(Results);
}
How to use??
For Encrypt:
string encryptpassword=Encrypt(txtPassword.Text.Trim());
For Decrypt:
string decryptpassword=Decrypt(txtPassword.Text.Trim());
NOTE : txtPassword is a textbox where you can enter a password

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

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

Compression and encryption SOAP - ASP.NET web service

I need advice. I zip and crypt SOAP message on web service and client side.
Client is winforms app.
If I only crypt SOAP message, it works good.
If I only zip SOAP message it also works good.
I use SOAP extension on crypt and zip SOAP.
I use AES - Advanced Encryption Standard - Rijndael and on compresion I use SharpZipLib from http://sourceforge.net/projects/sharpdevelop/.
The problem is I send dataset on client.
Firstly I zip and secondly encrypt SOAP on web service side.
Send on client.
On client side I load XML from stream. But it finish with this error :
Data at the root level is invalid. Line 1, position 2234.
Here is the code, where I load XML from stream:
var doc = new XmlDocument();
using (var reader = new XmlTextReader(inputStream))
{
doc.Load(reader);
}
Any advice ? Thank you...
Here are methods on web service side which zip and crypt SOAP :
//encrypt string
private static string EncryptString(string #string, string initialVector, string salt, string password,
string hashAlgorithm, int keySize, int passwordIterations)
{
byte[] initialVectorBytes = Encoding.ASCII.GetBytes(initialVector);
byte[] saltValueBytes = Encoding.ASCII.GetBytes(salt);
byte[] plainTextBytes = Encoding.UTF8.GetBytes(#string);
var derivedPassword = new PasswordDeriveBytes(password, saltValueBytes, hashAlgorithm, passwordIterations);
byte[] keyBytes = derivedPassword.GetBytes(keySize / 8);
var symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initialVectorBytes);
using (var memStream = new MemoryStream())
{
var cryptoStream = new CryptoStream(memStream, encryptor, CryptoStreamMode.Write);
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
var serializer = new XmlSerializer(typeof(byte[]));
var sb = new StringBuilder();
TextWriter writer = new StringWriter(sb);
serializer.Serialize(writer, memStream.ToArray());
writer.Flush();
var doc = new XmlDocument();
doc.LoadXml(sb.ToString());
if (doc.DocumentElement != null) return doc.DocumentElement.InnerXml;
}
return "";
}
//zip string
private static byte[] ZipArray(string stringToZip)
{
byte[] inputByteArray = Encoding.UTF8.GetBytes(stringToZip);
var ms = new MemoryStream();
// SharpZipLib.Zip,
var zipOut = new ZipOutputStream(ms);
var zipEntry = new ZipEntry("ZippedFile");
zipOut.PutNextEntry(zipEntry);
zipOut.SetLevel(7);
zipOut.Write(inputByteArray, 0, inputByteArray.Length);
zipOut.Finish();
zipOut.Close();
return ms.ToArray();
}
//zip and encrypt SOAP
public virtual Stream OutSoap(string[] soapElement, Stream inputStream)
{
#region Load XML from SOAP
var doc = new XmlDocument();
using (XmlReader reader = XmlReader.Create(inputStream))
{
doc.Load(reader);
}
var nsMan = new XmlNamespaceManager(doc.NameTable);
nsMan.AddNamespace("soap",
"http://schemas.xmlsoap.org/soap/envelope/");
#endregion Load XML from SOAP
#region Zip SOAP
XmlNode bodyNode = doc.SelectSingleNode(#"//soap:Body", nsMan);
bodyNode = bodyNode.FirstChild.FirstChild;
while (bodyNode != null)
{
if (bodyNode.InnerXml.Length > 0)
{
// Zip
byte[] outData = ZipArray(bodyNode.InnerXml);
bodyNode.InnerXml = Convert.ToBase64String(outData);
}
bodyNode = bodyNode.NextSibling;
}
#endregion Zip SOAP
#region Crypt SOAP
foreach (string xPathQuery in soapElement)
{
XmlNodeList nodesToEncrypt = doc.SelectNodes(xPathQuery, nsMan);
if (nodesToEncrypt != null)
foreach (XmlNode nodeToEncrypt in nodesToEncrypt)
{
//Encrypt
nodeToEncrypt.InnerXml = EncryptString(nodeToEncrypt.InnerXml,
user.IV, user.Salt, user.Password, user.HashType,
user.KeySize, user.PasswordIterations);
}
}
#endregion Crypt SOAP
inputStream.Position = 0;
var settings = new XmlWriterSettings { Encoding = Encoding.UTF8 };
using (XmlWriter writer = XmlWriter.Create(inputStream, settings))
{
doc.WriteTo(writer);
return inputStream;
}
}
Here is a code on client side which decrypt and uzip SOAP :
//decrypt string
private static string DecryptString(string #string, string initialVector, string salt, string password,
string hashAlgorithm, int keySize, int passwordIterations)
{
byte[] initialVectorBytes = Encoding.ASCII.GetBytes(initialVector);
byte[] saltValueBytes = Encoding.ASCII.GetBytes(salt);
byte[] cipherTextBytes = Convert.FromBase64String(#string);
var derivedPassword = new PasswordDeriveBytes(password, saltValueBytes, hashAlgorithm, passwordIterations);
byte[] keyBytes = derivedPassword.GetBytes(keySize / 8);
var symmetricKey = new RijndaelManaged { Mode = CipherMode.CBC };
ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initialVectorBytes);
using (var memStream = new MemoryStream(cipherTextBytes))
{
var cryptoStream = new CryptoStream(memStream, decryptor, CryptoStreamMode.Read);
var plainTextBytes = new byte[cipherTextBytes.Length];
int byteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
return Encoding.UTF8.GetString(plainTextBytes, 0, byteCount);
}
}
//unzip string
private static byte[] UnzipArray(string stringToUnzip)
{
byte[] inputByteArray = Convert.FromBase64String(stringToUnzip);
var ms = new MemoryStream(inputByteArray);
var ret = new MemoryStream();
// SharpZipLib.Zip
var zipIn = new ZipInputStream(ms);
var theEntry = zipIn.GetNextEntry();
var buffer = new Byte[2048];
int size = 2048;
while (true)
{
size = zipIn.Read(buffer, 0, buffer.Length);
if (size > 0)
{
ret.Write(buffer, 0, size);
}
else
{
break;
}
}
return ret.ToArray();
}
public virtual Stream InSoap(Stream inputStream, string[] soapElement)
{
#region Load XML from SOAP
var doc = new XmlDocument();
using (var reader = new XmlTextReader(inputStream))
{
doc.Load(reader);
}
var nsMan = new XmlNamespaceManager(doc.NameTable);
nsMan.AddNamespace("soap",
"http://schemas.xmlsoap.org/soap/envelope/");
#endregion Load XML from SOAP
#region Decrypt SOAP
foreach (string xPathQuery in soapElement)
{
XmlNodeList nodesToEncrypt = doc.SelectNodes(xPathQuery, nsMan);
if (nodesToEncrypt != null)
foreach (XmlNode nodeToEncrypt in nodesToEncrypt)
{
nodeToEncrypt.InnerXml = DecryptString(nodeToEncrypt.InnerXml, saltPhrase, passwordPhrase, initialVector,
hashAlgorithm, passwordIterations, keySize);
}
}
#endregion Decrypt SOAP
#region UnZip SOAP
XmlNode node = doc.SelectSingleNode("//soap:Body", nsMan);
node = node.FirstChild.FirstChild;
while (node != null)
{
if (node.InnerXml.Length > 0)
{
byte[] outData = UnzipArray(node.InnerXml);
string sTmp = Encoding.UTF8.GetString(outData);
node.InnerXml = sTmp;
}
node = node.NextSibling;
}
#endregion UnZip SOAP
var retStream = new MemoryStream();
doc.Save(retStream);
return retStream;
}
strong text
I'm not sure why your unencrypted xml won't parse, but I think you're first step should be to dump the decrypted data to the terminal to see exactly what text you're getting back. Perhaps the process corrupts your data somehow, or you have an encoding issue.
Alternatively, you could configure your server to use https and gzip compression to achieve the same goal. You won't loose any security with this approach and this is by far the more standard way to do things. You can also have a look at MS's support for the WS-Security standard

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