Encryption and decryption without special character - asp.net

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

Related

How to make AesEncrypterHandler encrypt the same way as Aes does

I am trying to use AesCryptoServiceProvider to achieve the same encryption mechanism as Aes.
Here is my AesCryptoServiceProvider version of it:
public string version1(string plainText, string encryptionKey, string initializationVector)
{
AesCryptoServiceProvider provider = new AesCryptoServiceProvider
{
BlockSize = 128,
Padding = PaddingMode.PKCS7,
Key = Convert.FromBase64String(encryptionKey),
IV = Encoding.UTF8.GetBytes(initializationVector)
};
byte[] buffer = Encoding.ASCII.GetBytes(plainText);
byte[] encrypted = provider.CreateEncryptor().TransformFinalBlock(buffer, 0, buffer.Length);
return Convert.ToBase64String(encrypted);
}
And here is the Aes version of it:
public string version2(string plainText, string encryptionKey, string initializationVector)
{
byte[] clearBytes = Encoding.UTF8.GetBytes(plainText);
byte[] encryptedBytes;
byte[] iv = Encoding.UTF8.GetBytes(initializationVector);
using (Aes aes = Aes.Create())
{
aes.BlockSize = 128;
aes.Padding = PaddingMode.PKCS7;
aes.Key = Convert.FromBase64String(encryptionKey);
aes.IV = iv;
using (MemoryStream ms = new MemoryStream())
using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
encryptedBytes = ms.ToArray();
}
}
byte[] ivEncryptedBytes = new byte[iv.Length + encryptedBytes.Length];
Buffer.BlockCopy(iv, 0, ivEncryptedBytes, 0, iv.Length);
Buffer.BlockCopy(encryptedBytes, 0, ivEncryptedBytes, iv.Length, encryptedBytes.Length);
return Convert.ToBase64String(ivEncryptedBytes);
}
When I encrypt the same string using version1 and version2 they came out to be different. Any idea on how these two methods are different and how I can make version1 produces the same encrypted string as version2? (p.s. I am rather new to encryption so sorry if the answer is obvious) Thanks!
As #MichaelFehr pointed out, version2 only has the initialization vector and the encrypted bytes concatenated together before converting the bytes back to string. I have tested that if I concatenate the string the same way as version2 in version1, the result string will become the same.

System.Security.Cryptography.CryptographicException: Specified key is not a valid size for this algorithm

With an AES key that I retrieve from a Key Vault I'm trying to decrypt a blob file. But I keep getting:
System.Security.Cryptography.CryptographicException: Specified key is
not a valid size for this
I'm trying to reverse engineer a python decrypt situation and this suggests to me that the value I'm retrieving from the key vault is a hex string or at least should be stored as hexstrings in a bytearray.
Python:
aes_key= bytes.fromhex(aes_key)
So because I get it from my configuration with var keyStringValue = _configuration.GetValue<string>("the-key-i-want"); I first convert to a bytearray to be able to convert it to hexstring. And then put it in a bytearray again.
//Where I convert my Keyvault keyStringValue to a hexString encoded bytearray
byte[] tempBytes = utf8.GetBytes(keyStringValue);
var hexString = BitConverter.ToString(tempBytes);
hexString = hexString.Replace("-", "").ToLower();
int NumberChars = hexString.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
bytes[i / 2] = Convert.ToByte(hexString.Substring(i, 2), 16);
byte[] pass = bytes;
I pass the pass variable to my decrypt function which looks like this:
var crypto = new AesCryptographyService();
var decryptedData = crypto.Decrypt(postSplitByteArray, pass, iv)
And finally my decrypt:
public class AesCryptographyService
{ public byte[] Decrypt(byte[] data, byte[] key, byte[] iv)
{
using var aes = Aes.Create();
aes.Padding = PaddingMode.Zeros;
aes.Mode = CipherMode.CBC;
aes.Key = key;
aes.IV = iv;
using (var decryptor = aes.CreateDecryptor(aes.Key, aes.IV))
{
return PerformCryptography(data, decryptor);
}
}
private byte[] PerformCryptography(byte[] data, ICryptoTransform cryptoTransform)
{
using (var ms = new MemoryStream())
using (var cryptoStream = new CryptoStream(ms, cryptoTransform, CryptoStreamMode.Write))
{
cryptoStream.Write(data, 0, data.Length);
cryptoStream.FlushFinalBlock();
return ms.ToArray();
}
}
The hexstring is 128 characters long. And the resultant bytearray 64. Now I know that the array should only be 32 bytes big. But I can't see the point of just cutting my key to size. Nor do I get a properly decrypted result. This bugs me since the python function seems to be doing the same as I am.
cipher = AES.new(aes256_key, AES.MODE_CBC, iv)
decrypted_data = cipher.decrypt(encrypted_data).decode('utf-8')
PS. I verified with an online converter that the conversion from string to hexstring is going well.
The solution was to not first convert my string into a bytearray and then do a hexstring conversion.
The string in the keyvault was already a "hexstring"
So getting rid of this.
byte[] tempBytes = utf8.GetBytes(keyStringValue);
var hexString = BitConverter.ToString(tempBytes);
hexString = hexString.Replace("-", "").ToLower();
And from
var keyStringValue = _configuration.GetValue<string>("the-key-i-want")
pass that to the hexstring conversion
private static byte[] FromHex(string keyStringValue)
{
int NumberChars = keyStringValue.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
bytes[i / 2] = Convert.ToByte(keyStringValue.Substring(i, 2), 16);
return bytes;
}
And Bob is your uncle.

Bouncy castle light weight api encryption for j2me - Given final block not properly padded

i have used sha256 for secret key generation and took first 16 digit for AES 128 encryption. i am getting correct encrypted and decrypted data when it is 16 or below 16 string. if it is above 16 char string i am getting 16 char with some unwanted characters. (Eg: abcdefghijklmnop5#�D�!�&M�\~C��) can anybody help me to sort this issue. please see below for code.
i have encrypted using j2me code and tried to decrypt using the given online aes crypto site (http://aesencryption.net/). i guess it is having some padding issue but i am not able to figure it out.
public static String getSHA256(String key) {
SHA256Digest digester = new SHA256Digest();
byte[] retValue = new byte[digester.getDigestSize()];
digester.update(key.getBytes(), 0, key.length());
digester.doFinal(retValue,0);
byteToStr = new String(Hex.encode(retValue));
System.out.println("byteToStr === " + byteToStr);
byteToStr = byteToStr.substring(0, 16);
System.out.println("byteToStr after subString === " + byteToStr);
return byteToStr;
}
public static byte[] cipherData(BufferedBlockCipher cipher, byte[] data)
throws Exception {
int minSize = cipher.getOutputSize(data.length);
System.out.println("min Size = "+minSize);
byte[] outBuf = new byte[minSize];
int length1 = cipher.processBytes(data, 0, data.length, outBuf, 0);
int length2 = cipher.doFinal(outBuf, length1);
System.out.println("length1 = "+length1 +"/ length2 = "+length2);
int actualLength = length1 + length2;
System.out.println("actualLength = "+actualLength);
byte[] result = new byte[actualLength];
System.arraycopy(outBuf, 0, result, 0, result.length);
return result;
}
public static byte[] decrypt(byte[] cipher, byte[] key/* , byte[] iv */)
throws Exception {
/*
* PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher( new
* CBCBlockCipher(new AESEngine())); CipherParameters ivAndKey = new
* ParametersWithIV(new KeyParameter(key), iv); aes.init(false,
* ivAndKey); return cipherData(aes, cipher);
*/
BufferedBlockCipher decryptCipher = new PaddedBufferedBlockCipher(
new CBCBlockCipher(new AESEngine()));
KeyParameter keyDecrypt = new KeyParameter(key);
decryptCipher.init(false, keyDecrypt);
return cipherData(decryptCipher, cipher);
}
public static byte[] encrypt(byte[] plain, byte[] key/* , byte[] iv */)
throws Exception {
/*
* PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher( new
* CBCBlockCipher(new AESEngine())); CipherParameters ivAndKey = new
* ParametersWithIV(new KeyParameter(key), iv);
*/
BufferedBlockCipher encryptCipher = new PaddedBufferedBlockCipher(
new CBCBlockCipher(new AESEngine()));
KeyParameter keyEncrypt = new KeyParameter(key);
encryptCipher.init(true, keyEncrypt);
return cipherData(encryptCipher, plain);
}
public static String encryptMe(String plain) {
byte[] plainStr = plain.getBytes();
byte[] keyStr = getSHA256(key).getBytes();
// byte[] ivStr = iv.getBytes();//
System.out.println("key str = "+Strings.fromByteArray(keyStr));
try {
byte[] encBytes = encrypt(plainStr, keyStr/*
* , ivStr
*/);
strEncResult= Base64.toBase64String(encBytes);
//byte[] encbase = Base64.encode(encBytes);
//strEncResult = new String(encbase,"ISO-8859-1");
} catch (Exception e) {
e.printStackTrace();
}
return strEncResult;
}
public static String decryptMe(String cipherText) {
try {
byte[] dcrByte = Base64.decode(cipherText);
byte[] dec = decrypt(dcrByte, getSHA256(key).getBytes()/*
* ,iv.getBytes
* ()
*/);
strDcrResult = Strings.fromByteArray(dec);
//strDcrResult = new String(dec,"ISO-8859-1");
} catch (Exception e) {
e.printStackTrace();
}
return strDcrResult;
}

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

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

Resources