Read Multiple Objects from Stream with Newtonsoft.Json - json.net

According to Reading multiple JSON objects on a JSON-RPC connection it shall be possible to send multiple requests one after another.
My problem is how to parse the requests with Newtonsoft.Json?
The JsonSerializer reads obviously more bytes than neccessary for deserializing the first request. The following snippet shows the problem:
class JsonRpcRequest
{
public int? id;
public string jsonrpc;
public string method;
public object #params;
}
class AddParam
{
public int a;
public int b;
}
static void Main(string[] args)
{
var p = new AddParam()
{
a = 100,
b = 200,
};
var request = new JsonRpcRequest()
{
jsonrpc = "2.0",
method = "Add",
#params = p,
};
var stream = new MemoryStream();
var reader = new StreamReader(stream);
var writer = new StreamWriter(stream);
var ser = new JsonSerializer();
request.id = 100;
ser.Serialize(writer, request);
writer.Flush();
// stream.Position is 68
request.id = 101;
ser.Serialize(writer, request);
writer.Flush();
// stream.Position is 136
stream.Position = 0;
// Stream holds
// {"id":100,"jsonrpc":"2.0","method":"Add","params":{"a":100,"b":200}}{"id":101,"jsonrpc":"2.0","method":"Add","params":{"a":100,"b":200}}
var r1 = ser.Deserialize(reader, typeof(JsonRpcRequest));
// r1 holds first Request
// But stream.Position is already 136
var r2 = ser.Deserialize(reader, typeof(JsonRpcRequest));
// r2 is null !!!???
}

Related

app crashes when trying to send multiple fcm messages programmatically

i am trying to create a messaging app using xamarin.forms. i created a send button and added the following code:
private async void send_Clicked(object sender, EventArgs e)
{
await Task.Run(() => SendNotification(token, "title", message.Text));
}
and the sendnotification is as follows:
public string SendNotification(string DeviceToken, string title, string msg)
{
var result = "-1";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers.Add(string.Format("Authorization: key={0}", serverKey));
httpWebRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
httpWebRequest.Method = "POST";
var payload = new
{
//to= "/topics/klm",
to = DeviceToken,
//to = "egjLx6VdFS0:APA91bGQMSSRq_wCzywNC01zJi4FBtHXrXuL-p4vlkl3a3esdH8lxo7mQZUBlrTi7h-6JXx0GrJbwc9Vx6M5Q4OV_3CArcdlP0XMBybervQvfraWvqCgaa75gu9SVzjY4V_qd36JGg4A",
priority = "high",
content_available = true,
data = new
{
text = msg,
},
};
var serializer = new JsonSerializer();
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = JsonConvert.SerializeObject(payload);
streamWriter.Write(json);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
}
this is private string webAddr = "https://fcm.googleapis.com/fcm/send";
when i click send the first time, i receive the message perfectly, when i hit send the second time, the app freezes then crashes and asks me if i want to close the app or wait. why is this happening? thanks in advance

PDF Signature - Embed separatly signed hash problem

I am currently working on a web application (1) which allows sending the hash of a pdf file to another application (2). The application (2) returns a signed hash.
With a console application I managed to correctly sign the file but the problem is that we need to have the hash before the Makesignature.SignDetached (*****) function
code
static void Main(string[] args)
{
string unsignedPdf = "c:\\temp\\spec.pdf";
string signedPdf = "c:\\temp\\specSigned5.pdf";
Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[1];
byte[] bytes = Convert.FromBase64String("certificate here");
var cert = new X509Certificate2(bytes);
chain[0] = new Org.BouncyCastle.X509.X509CertificateParser().ReadCertificate(cert.GetRawCertData());
using (PdfReader reader = new PdfReader(unsignedPdf))
{
using (FileStream os = File.OpenWrite(signedPdf))
{
PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '\0');
PdfSignatureAppearance appearance = stamper.SignatureAppearance;
appearance.SetVisibleSignature(new Rectangle(100, 250, 250, 400), 1, "digigo2");
appearance.Reason = "Reason";
appearance.Location = "Location";
appearance.SignDate = DateTime.Now;
appearance.Certificate = chain[0];
IExternalSignature signature = new RemoteSignature();
MakeSignature.SignDetached(appearance, signature, chain, null, null, null, 0, CryptoStandard.CADES);
}
}
}
class RemoteSignature : IExternalSignature
{
public virtual byte[] Sign(byte[] message)
{
IDigest messageDigest = DigestUtilities.GetDigest(GetHashAlgorithm());
byte[] messageHash = DigestAlgorithms.Digest(messageDigest, message);
Console.WriteLine(Convert.ToBase64String(messageHash));
Console.ReadKey();
// i send the hash to the application B and i get
// the signed hash and i save it in c:/temp/signedhash.txt
string SighHashFile = "c:/temp/signedhash.txt";
string signature = File.ReadAllText(SighHashFile);
byte[] signedBytes = Convert.FromBase64String(signature);
return signedBytes;
}
public virtual String GetHashAlgorithm()
{
return "SHA-256";
}
public virtual String GetEncryptionAlgorithm()
{
return "RSA";
}
}
I tried using the MakeSignature.SignDeferred () function but the signature is still wrong
code
static void Main(string[] args)
{
string unsignedPdf = "c:/temp/spec.pdf";
string tempPdf = "c:/temp/temp.pdf";
string signedPdf = "c:/temp/Signed.pdf";
string signatureFieldName = "test";
Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[1];
byte[] bytes = Convert.FromBase64String("certificate here");
var cert = new X509Certificate2(bytes);
chain[0] = new Org.BouncyCastle.X509.X509CertificateParser().ReadCertificate(cert.GetRawCertData());
string sByte = GetBytesToSign(unsignedPdf, tempPdf, signatureFieldName, chain[0]);
Console.WriteLine(sByte);
Console.ReadLine();
// i send the hash to the application B and i get
// the signed hash and i save it in c:/temp/signedhash.txt
string SighHashFile = "c:/temp/signedhash.txt";
string signature = File.ReadAllText(SighHashFile);
EmbedSignature(tempPdf, signedPdf, signatureFieldName, signature);
}
public static string GetBytesToSign(string unsignedPdf, string tempPdf, string signatureFieldName, Org.BouncyCastle.X509.X509Certificate chain)
{
if (File.Exists(tempPdf))
File.Delete(tempPdf);
using (PdfReader reader = new PdfReader(unsignedPdf))
{
using (FileStream os = File.OpenWrite(tempPdf))
{
PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '\0');
PdfSignatureAppearance appearance = stamper.SignatureAppearance;
appearance.SetVisibleSignature(new Rectangle(36, 748, 250, 400), 1, signatureFieldName);
appearance.Reason = "Reason";
appearance.Location = "Location";
appearance.SignDate = DateTime.Now;
appearance.Certificate = chain;
IExternalSignatureContainer external = new ExternalBlankSignatureContainer(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
MakeSignature.SignExternalContainer(appearance, external, 8192);
byte[] hash = DigestAlgorithms.Digest(appearance.GetRangeStream(), "SHA256");
return Convert.ToBase64String(hash);
}
}
}
public static void EmbedSignature(string tempPdf, string signedPdf, string signatureFieldName, string signature)
{
byte[] signedBytes = Convert.FromBase64String(signature);
using (PdfReader reader = new PdfReader(tempPdf))
{
using (FileStream os = File.OpenWrite(signedPdf))
{
IExternalSignatureContainer external = new MyExternalSignatureContainer(signedBytes);
MakeSignature.SignDeferred(reader, signatureFieldName, os, external);
}
}
}
private class MyExternalSignatureContainer : IExternalSignatureContainer
{
private readonly byte[] signedBytes;
public MyExternalSignatureContainer(byte[] signedBytes)
{
this.signedBytes = signedBytes;
}
public void ModifySigningDictionary(PdfDictionary signDic)
{
}
public byte[] Sign(Stream data)
{
return signedBytes;
}
}
Invalid signature

RSA Signature port from Java to C#

I have this method that is in Java, what would be the same code in C#. I am struggling with what the C# code would be to do this
private String signSHA256RSA(String input) throws Exception
{
byte[] b1 = Base64.getDecoder().decode(privKey);
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(b1);
KeyFactory kf = KeyFactory.getInstance("RSA");
Signature privateSignature = Signature.getInstance("SHA256withRSA");
privateSignature.initSign(kf.generatePrivate(spec));
privateSignature.update(input.getBytes(StandardCharsets.UTF_8));
return byteArrayToHex(privateSignature.sign());
}
This is how I solved this in the end.
I used this 3rd party library https://github.com/huysentruitw/pem-utils
Then I just used this code
private static string SignSHA256RSA(string itemToSign)
{
var bytes = Encoding.UTF8.GetBytes(itemToSign);
using (var stream = File.OpenRead(#"C:\PrivateKey.pem"))
using (var reader = new PemReader(stream))
{
var rsaParameters = reader.ReadRsaKey();
byte[] hv = SHA256.Create().ComputeHash(bytes);
RSACryptoServiceProvider prov = new RSACryptoServiceProvider();
RSAParameters rsp = new RSAParameters();
prov.ImportParameters(rsaParameters);
RSAPKCS1SignatureFormatter rf = new RSAPKCS1SignatureFormatter(prov);
rf.SetHashAlgorithm("SHA256");
byte[] signature = rf.CreateSignature(hv);
var finalHex = BitConverter.ToString(signature).Replace("-", string.Empty).ToLowerInvariant();
return finalHex;
}
}
With .NET standard 2.1 you need a little helper to decode the private key from Base64 encoded DER file.
using System;
using System.Security.Cryptography;
using System.Buffers.Binary;
using System.Text;
namespace Demo
{
class Program
{
const string DerPrivateKey = "MIIBywIBAAJhALkPdKoBJJg8t0Qg7VhyomS+PpKNMzn0NQ/P3zt55uAmLKenUV9xbMhW1SQRUbTEDdDUlfIiBMCzNAxB5od2IrhP4+/nKmUNsIoxOdwL0j//X74xalv9137T+y4ubLzVhwIDAQABAmAScdvq5dpD4ilR/QYq/qH48I1EBhbI+/Id9VYGk4vTY3qn6yFNJfz1qtHrml5OagvbBQLyPwjwxSumkzGelauqr4NvpOirK18v3xzhlsSmys6JZ5nILG16JByXxJjvziECMQDluHUNOCElxIbIrFOTVBaiqs4Iw9b/UJ7Wf7GglFk4pS00wjSnuDMDqGjyb4tgQ3UCMQDOOxdcSs2CPLrppT463NMqDoGide33X4s5y67E9v44IMTKuOwIXoDzgTcoGmeJwYsCMQDWUZRrA93xFXxGRngmsMH5e2+Dv+qbAsVeC35V+XGQJpKZcUKc4348wGdBIA4hfm0CMQCllxDkzDNDFZxHKqVTAiiTpl40olhWvmK+H2vPPztUugsJc34iIi+MVf6BtuHX3I0CMEDuG1uewuwcgHxWTGMnvSqQjkwtTUI0It6c8PTf8URGtoHx7HNl/wKoGGgXLTRY1w==";
static void Main(string[] args)
{
var signature = SignSHA256RSA(base64Key: DerPrivateKey, input: "Hello world!");
System.Console.WriteLine("Signature (HEX): " + signature);
}
private static string SignSHA256RSA(string base64Key, string input)
{
// Load key with the little DER helper
var rsa = LoadRSAKey(derPrivateKey: Convert.FromBase64String(DerPrivateKey));
// Sign
var inputBytes = Encoding.UTF8.GetBytes(input);
var signatureBytes = rsa.SignData(inputBytes, 0, inputBytes.Length, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
// Convert signature to hex
var signatureHex = BitConverter.ToString(signatureBytes).Replace("-", string.Empty);
return signatureHex;
}
private static RSA LoadRSAKey(ReadOnlySpan<byte> derPrivateKey)
{
// Expect sequence
if (AsnHelper.GetTag(derPrivateKey[0]) != 16)
throw new FormatException($"unexpected tag");
// Read sequence length
derPrivateKey = derPrivateKey.Slice(1);
if (!AsnHelper.TryReadLength(derPrivateKey, out var length, out var bytesRead))
throw new FormatException($"unexpected length");
var sequence = AsnHelper.ReadSequence(derPrivateKey.Slice(bytesRead, length));
// https://www.hanselman.com/blog/DecodingAnSSHKeyFromPEMToBASE64ToHEXToASN1ToPrimeDecimalNumbers.aspx
var rsaParameters = new RSAParameters
{
Modulus = sequence[1].RawData,
Exponent = sequence[2].RawData,
D = sequence[3].RawData,
P = sequence[4].RawData,
Q = sequence[5].RawData,
DP = sequence[6].RawData,
DQ = sequence[7].RawData,
InverseQ = sequence[8].RawData,
};
var rsa = RSA.Create();
rsa.ImportParameters(rsaParameters);
return rsa;
}
}
/// <summary>
/// Quick helper: only works on specific key format
///
/// https://en.wikipedia.org/wiki/X.690#BER_encoding
/// </summary>
internal static class AsnHelper
{
public static int GetTag(byte value) => value & 0b11111;
public static AsnEncodedDataCollection ReadSequence(ReadOnlySpan<byte> source)
{
var sequence = new AsnEncodedDataCollection();
while (!source.IsEmpty)
{
var tag = GetTag(source[0]);
if (tag != 2)
throw new FormatException("only support integer");
source = source.Slice(1);
if (!TryReadLength(source, out var length, out var bytesRead))
throw new FormatException("invalid length");
source = source.Slice(bytesRead);
var value = new AsnEncodedData(source.Slice(0, length).ToArray());
source = source.Slice(length);
sequence.Add(value);
}
return sequence;
}
public static bool TryReadLength(ReadOnlySpan<byte> source, out int length, out int bytesRead)
{
length = 0;
bytesRead = 0;
const byte MultiByteMarker = 0x80;
bytesRead = 1;
if ((source[0] & MultiByteMarker) == 0)
{
length = source[0];
return true;
}
int lengthLength = source[0] & 0x7F;
bytesRead += lengthLength;
if (lengthLength == 2)
{
length = BinaryPrimitives.ReadInt16BigEndian(source.Slice(1));
return true;
}
return false;
}
}
}
For testing, I generate a key with the following:
openssl genrsa 768 | openssl rsa -outform der | base64 -w 0
C#.Net code framework: 4.6,
It worked for me.
private string SignSHA256RSA(string itemToSign)
{
string filePath = Server.MapPath("Merchant_private_key_test.pem");
var bytes = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(itemToSign);
var sha256 = new SHA256CryptoServiceProvider();
byte[] rgbHash = sha256.ComputeHash(bytes);
StreamReader sr = new StreamReader(filePath);
PemReader pr = new PemReader(sr);
RsaPrivateCrtKeyParameters KeyPair = (RsaPrivateCrtKeyParameters)pr.ReadObject();
RSA rsa = DotNetUtilities.ToRSA(KeyPair);
string xmlRsa = rsa.ToXmlString(true);
RSACryptoServiceProvider key = new RSACryptoServiceProvider();
key.FromXmlString(xmlRsa);
RSAPKCS1SignatureFormatter formatter = new RSAPKCS1SignatureFormatter(key);
formatter.SetHashAlgorithm("SHA256");
byte[] inArray = formatter.CreateSignature(rgbHash);
return Convert.ToBase64String(inArray);
}

how to parse xml string from Post method response?

I have a xml string that return from Post method:
private static void GetResponseCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
HttpStatusCode rcode = response.StatusCode;
var stream = new GZipInputStream(response.GetResponseStream());
using (StreamReader reader = new StreamReader(stream))
{
responseString = reader.ReadToEnd();
}
response.Close();
}
The responseString is the string I want to parse, using parseXmlString class below. However I can't call the method parseXmlString directly because of the static. How can I pass the responseString to the parseXmlString method to have them parse out and bind to the listBox. Or anyway to have the same result would be great.
void parseXmlString()
{
byte[] byteArray = Encoding.UTF8.GetBytes(responseString);
MemoryStream str = new MemoryStream(byteArray);
str.Position = 0;
XDocument xdoc = XDocument.Load(str);
var data = from query in xdoc.Descendants("tracks").Elements("item")
select new searchResult
{
artist = (string)query.Element("artist"),
album = (string)query.Element("album"),
track = (string)query.Element("track"),
// artistA = (string)query.Element("artists").Element("artist"),
};
// ListBox lb = new ListBox();
listBox1.ItemsSource = data;
var data1 = from query in xdoc.Descendants("artists").Elements("item")
select new searchResult
{
artistA = (string)query.Element("artist"),
};
listBox2.ItemsSource = data1;
}
Your approach is inversed logic. You know that you can have return values on methods, right?-)
What you need to do is let your ParseXmlString method take the responseString as a parameter, and let it return the created IEnumerable, like this:
private IEnumerable<SearchResult> ParseXmlString(responseString)
{
XDocument xdoc = XDocument.Load(responseString);
var data =
from query in xdoc.Descendants("tracks").Elements("item")
select new SearchResult
{
Artist = (string)query.Element("artist"),
Album = (string)query.Element("album"),
Track = (string)query.Element("track"),
};
return
from query in xdoc.Descendants("artists").Elements("item")
select new SearchResult
{
ArtistA = (string)query.Element("artist"),
};
}
And change your async code handling, to perform a callback to your UI thread, when it's done reading out the responseString.
Then, on your UI thread, you would do:
// This being your method to get the async response
GetResponseAsync(..., responseString =>
{
var searchResults = ParseXmlString(responseString);
listBox2.ItemsSource = searchResults;
})
You can see this answer, if you need some basic understanding of callbacks: Callbacks in C#

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