Anand
Anand

Reputation: 853

Decode and unzip a Base64 encoded and Gziped compressed text

I am trying to read a text from XML node. The text is base 64 encrypted and Gzip compressed. I am trying in the following ways:

1. XmlNodeList nodeDebugs = xmlDoc.GetElementsByTagName("Debugs");

2.     if (nodeDebugs != null)
3.        {

4.            for (int i = 0; i < nodeDebugs.Count; i++)
5.             {
6.                 XmlNodeList childNodes = nodeDebugs.Item(i).ChildNodes;
7.                 String nodeName = childNodes.Item(i).Name;
8.                 if (nodeName == "Debug")
9.                 {  

10.                 byte[] compressed = System.Text.Encoding.UTF8.GetBytes(childNodes.Item(i).InnerText.Trim());

11.  using (var uncompressed = new MemoryStream())
12.  using (var inStream = new MemoryStream(compressed))
13.  using (var outStream = new GZipStream(inStream, CompressionMode.Decompress))
14.  {
15.      outStream .CopyTo(uncompressed);
16.      Console.WriteLine(Encoding.UTF8.GetString(uncompressed.ToArray()));
17.  }

Getting error at Line no 15, as "the magic number in gzip header is not correct." Any help to resolve this issue is much appreciated. Thanks a lot in advance.

Upvotes: 1

Views: 2486

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500425

This is the problem, I suspect:

byte[] compressed = System.Text.Encoding.UTF8.GetBytes(childNodes.Item(i).InnerText.Trim());

You said that your data is compressed and then base64-encoded... but your code doesn't use base64 anywhere, which is a massive warning sign. I suspect you want:

string text = childNodes.Item(i).InnerText.Trim();
byte[] compressed = Convert.FromBase64String(text);

If that doesn't work, you should check each step of the transformation - you should have the same data during encoding and decoding, just in the reverse order. See my blog post about diagnosing reversible data transformations for more details - but hopefully the change above will fix it anyway.

Upvotes: 2

Related Questions