Example #1
1
        private Stream Decode()
        {
            Stream stream;

            if (Encoding != "base64")
                throw new Exception("TmxMapperPCL.Data: Only Base64-encoded data is supported.");

            var rawData = Convert.FromBase64String(Value);
            var memStream = new MemoryStream(rawData);

            if (Compression == "gzip")
                stream = new GZipInputStream(memStream);
            else if (Compression == "zlib")
                stream = new InflaterInputStream(memStream);
            else if (Compression != null)
                throw new Exception("TmxMapperPCL.Data: Unknown compression.");
            else
                stream = memStream;

            var outputStream = new MemoryStream();
            stream.CopyTo(outputStream);
            stream = outputStream;

            return stream;
        }
        public void CloseInflatorWithNestedUsing()
        {
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                string tempFile = Environment.TickCount.ToString();
                store.CreateDirectory(tempFile);

                tempFile = Path.Combine(tempFile, "SharpZipTest.Zip");
                using (IsolatedStorageFileStream diskFile = store.CreateFile(tempFile))
                using (DeflaterOutputStream deflator = new DeflaterOutputStream(diskFile))
                using (StreamWriter textWriter = new StreamWriter(deflator))
                {
                    textWriter.Write("Hello");
                    textWriter.Flush();
                }

                using (IsolatedStorageFileStream diskFile = store.OpenFile(tempFile, FileMode.Open))
                using (InflaterInputStream deflator = new InflaterInputStream(diskFile))
                using (StreamReader textReader = new StreamReader(deflator))
                {
                    char[] buffer = new char[5];
                    int readCount = textReader.Read(buffer, 0, 5);
                    Assert.AreEqual(5, readCount);

                    StringBuilder b = new StringBuilder();
                    b.Append(buffer);
                    Assert.AreEqual("Hello", b.ToString());

                }

                store.CreateFile(tempFile);
            }
        }
Example #3
0
        public static void Deserialize(Stream stream, PiaFile piaFile)
        {
            if (stream == null)
                throw new ArgumentNullException("Stream");

            if (piaFile == null)
                throw new ArgumentNullException("PiaFile");

            try
            {
                // Header
                var headerBytes = new Byte[48]; // Ignore 12 byte checksum
                stream.Read(headerBytes, 0, headerBytes.Length);
                var headerString = Encoding.Default.GetString(headerBytes);
                piaFile.Header = new PiaHeader(headerString);

                // Inflation
                string inflatedString;
                stream.Seek(60, SeekOrigin.Begin);

                using (var zStream = new InflaterInputStream(stream))
                {
                    var sr = new StreamReader(zStream, Encoding.Default);
                    inflatedString = sr.ReadToEnd();
                }

                // Nodes
                piaFile.Owner = piaFile;
                _deserializeNode(piaFile, inflatedString);
            }
            catch (Exception)
            {
                throw;
            }
        }
        public void Decompress(Stream source, Stream destination)
        {
            var inflater = new InflaterInputStream(source, new Inflater(true));

            var dataBuffer = new byte[CopyBufferSize];
            StreamUtils.Copy(inflater, destination, dataBuffer);
        }
        /// <summary>
        /// Expands (de-compresses) a string.
        /// </summary>
        /// <param name="value">The string to expanded.</param>
        /// <returns>The expanded string.</returns>
        public string ExpandString(string value)
        {
            // The input value must be non-null
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            var outputData = string.Empty;
            var inputData = Convert.FromBase64String(value);
            using (var inputStream = new MemoryStream(inputData))
            {
                using (var outputStream = new MemoryStream())
                {
                    // Zip the string
                    using (var zipStream = new InflaterInputStream(inputStream))
                    {
                        zipStream.IsStreamOwner = false;
                        StreamUtils.Copy(zipStream, outputStream, new byte[4096]);
                    }

                    // Convert to a string
                    outputData = UTF8Encoding.UTF8.GetString(outputStream.GetBuffer(), 0, Convert.ToInt32(outputStream.Length));
                }
            }

            // Return the compressed string
            return outputData;
        }
        public void CloseInflatorWithNestedUsing()
        {
            string tempFile = null;
            try {
                tempFile = Path.GetTempPath();
            } catch (SecurityException) {
            }

            Assert.IsNotNull(tempFile, "No permission to execute this test?");

            tempFile = Path.Combine(tempFile, "SharpZipTest.Zip");
            using (FileStream diskFile = File.Create(tempFile))
            using (DeflaterOutputStream deflator = new DeflaterOutputStream(diskFile))
            using (StreamWriter textWriter = new StreamWriter(deflator)) {
                textWriter.Write("Hello");
                textWriter.Flush();
            }

            using (FileStream diskFile = File.OpenRead(tempFile))
            using (InflaterInputStream deflator = new InflaterInputStream(diskFile))
            using (StreamReader textReader = new StreamReader(deflator)) {
                char[] buffer = new char[5];
                int readCount = textReader.Read(buffer, 0, 5);
                Assert.AreEqual(5, readCount);

                var b = new StringBuilder();
                b.Append(buffer);
                Assert.AreEqual("Hello", b.ToString());

            }

            File.Delete(tempFile);
        }
Example #7
0
 internal static byte[] Inflate(byte[] buffer)
 {
     InflaterInputStream inflaterStream = new InflaterInputStream(new MemoryStream(buffer));
     MemoryStream outputStream = new MemoryStream();
     inflaterStream.CopyTo(outputStream);
     return outputStream.ToArray();
 }
Example #8
0
        /// <summary>
        /// Decompresses an array of bytes.
        /// </summary>
        /// <param name="_pBytes">An array of bytes to be decompressed.</param>
        /// <returns>Decompressed bytes</returns>
        public static byte[] DeCompress(byte[] _pBytes)
        {
            InflaterInputStream inputStream = new InflaterInputStream(new MemoryStream(_pBytes));

            MemoryStream ms = new MemoryStream();
            Int32 mSize;

            byte[] mWriteData = new byte[4096];

            while (true)
            {
                mSize = inputStream.Read(mWriteData, 0, mWriteData.Length);
                if (mSize > 0)
                {
                    ms.Write(mWriteData, 0, mSize);
                }
                else
                {
                    break;
                }
            }

            inputStream.Close();
            return ms.ToArray();
        }
        public string Decompress(string compressedString)
        {
            var uncompressedString = string.Empty;
            var totalLength = 0;
            var inputAsBytes = Convert.FromBase64String(compressedString);;
            var writeData = new byte[4096];
            var inputStream = new InflaterInputStream(new MemoryStream(inputAsBytes));

            for(;;)
            {
                var size = inputStream.Read(writeData, 0, writeData.Length);

                if (size > 0)
                {
                    totalLength += size;
                    uncompressedString += Encoding.UTF8.GetString(writeData, 0, size);
                }
                else
                {
                    break;
                }
            }

            inputStream.Close();

            return uncompressedString;
        }
Example #10
0
    public Rectangle GetDimensions(Stream stream)
    {
        Stream inputStream = null;
        byte[] signature = new byte[8];
        byte[] rect = new byte[8];
        stream.Read(signature, 0, 8);
        if ("CWS" == System.Text.Encoding.ASCII.GetString(signature, 0, 3))
        {
            inputStream = new InflaterInputStream(stream);
        }
        else
        {
            inputStream = stream;
        }

        inputStream.Read(rect, 0, 8);
        int nbits = rect[0] >> 3;
        rect[0] = (byte)(rect[0] & 0x07);
        String bits = ByteArrayToBitString(rect);
        bits = bits.Remove(0, 5);
        int[] dims = new int[4];
        for (int i = 0; i < 4; i++)
        {
            char[] dest = new char[nbits];
            bits.CopyTo(0, dest, 0, bits.Length > nbits ? nbits : bits.Length);
            bits = bits.Remove(0, bits.Length > nbits ? nbits : bits.Length);
            dims[i] = BitStringToInteger(new String(dest)) / 20;
        }

        return new Rectangle(0, 0, dims[1] - dims[0], dims[3] - dims[2]);
    }
Example #11
0
        public static byte[] DecompressGzipBytes(byte[] Bytes)
        {
            ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputStream stream =
                new ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputStream(new MemoryStream(Bytes));

            MemoryStream memory = new MemoryStream();

            byte[] writeData = new byte[4096];
            int    size;

            while (true)
            {
                size = stream.Read(writeData, 0, writeData.Length);
                if (size > 0)
                {
                    memory.Write(writeData, 0, size);
                }
                else
                {
                    break;
                }
            }

            stream.Close();

            return(memory.ToArray());
        }
        public void TestInflateDeflate()
        {
            MemoryStream ms = new MemoryStream();
            Deflater deflater = new Deflater(6);
            DeflaterOutputStream outStream = new DeflaterOutputStream(ms, deflater);

            byte[] buf = new byte[1000000];
            System.Random rnd = new Random();
            rnd.NextBytes(buf);

            outStream.Write(buf, 0, buf.Length);
            outStream.Flush();
            outStream.Finish();

            ms.Seek(0, SeekOrigin.Begin);

            InflaterInputStream inStream = new InflaterInputStream(ms);
            byte[] buf2 = new byte[buf.Length];
            int    pos  = 0;
            while (true) {
                int numRead = inStream.Read(buf2, pos, 4096);
                if (numRead <= 0) {
                    break;
                }
                pos += numRead;
            }

            for (int i = 0; i < buf.Length; ++i) {
                Assertion.AssertEquals(buf2[i], buf[i]);
            }
        }
		void Inflate(MemoryStream ms, byte[] original, int level, bool zlib)
		{
			ms.Seek(0, SeekOrigin.Begin);
			
			Inflater inflater = new Inflater(!zlib);
			InflaterInputStream inStream = new InflaterInputStream(ms, inflater);
			byte[] buf2 = new byte[original.Length];

			int currentIndex  = 0;
			int count = buf2.Length;

			try
			{
				while (true) 
				{
					int numRead = inStream.Read(buf2, currentIndex, count);
					if (numRead <= 0) 
					{
						break;
					}
					currentIndex += numRead;
					count -= numRead;
				}
			}
			catch(Exception ex)
			{
				Console.WriteLine("Unexpected exception - '{0}'", ex.Message);
				throw;
			}

			if ( currentIndex != original.Length )
			{
				Console.WriteLine("Original {0}, new {1}", original.Length, currentIndex);
				Assert.Fail("Lengths different");
			}

			for (int i = 0; i < original.Length; ++i) 
			{
				if ( buf2[i] != original[i] )
				{
					string description = string.Format("Difference at {0} level {1} zlib {2} ", i, level, zlib);
					if ( original.Length < 2048 )
					{
						StringBuilder builder = new StringBuilder(description);
						for (int d = 0; d < original.Length; ++d)
						{
							builder.AppendFormat("{0} ", original[d]);
						}

						Assert.Fail(builder.ToString());
					}
					else
					{
						Assert.Fail(description);
					}
				}
			}
		}
Example #14
0
        public static byte[] Decompress(byte[] data, int final_size)
        {
            byte[] r = null;

            using (Stream s = new InflaterInputStream(new MemoryStream(data)))
                s.Read(r, 0, final_size);

            return r;
        }
Example #15
0
 public void Decompress(ArraySegment<byte> input, ArraySegment<byte> output)
 {
     using (var gz = new InflaterInputStream(new MemoryStream(input.Array, input.Offset, input.Count)))
     {
         int read = gz.Read(output.Array, output.Offset, output.Count);
         if (read != output.Count)
             throw new Exception("Short read!");
     }
 }
Example #16
0
        public static byte[] UncompressStream(Stream stream, int filesize, int memsize)
        {

            BinaryReader r = new BinaryReader(stream);
            long end = stream.Position + filesize;

            byte[] header = r.ReadBytes(2);

            if (checking) if (header.Length != 2)
                    throw new InvalidDataException("Hit unexpected end of file at " + stream.Position);

            bool useDEFLATE = true;
            byte[] uncompressedData = null;

            if (header[0] == 0x78)
            {
                useDEFLATE = true;
            }
            else if (header[1] == 0xFB)
            {
                useDEFLATE = false;
            }
            else
            {
                throw new InvalidDataException("Unrecognized compression format");
            }

            if (useDEFLATE)
            {
                byte[] data = new byte[filesize];
                stream.Position -= 2; // go back to header
                stream.Read(data, 0, filesize);
                using (MemoryStream source = new MemoryStream(data))
                {
                    using (InflaterInputStream decomp = new InflaterInputStream(source))
                    {
                        uncompressedData = new byte[memsize];
                        decomp.Read(uncompressedData, 0, memsize);
                    }
                }
            }
            else
            {
                uncompressedData = OldDecompress(stream, header[0]);
            }

            long realsize = uncompressedData.Length;

            if (checking) if (realsize != memsize)
                    throw new InvalidDataException(String.Format(
                        "Resource data indicates size does not match index at 0x{0}.  Read 0x{1}.  Expected 0x{2}.",
                        stream.Position.ToString("X8"), realsize.ToString("X8"), memsize.ToString("X8")));

            return uncompressedData;

        }
Example #17
0
 /// <summary>
 /// ��ѹ�ֽ�������
 /// </summary>
 /// <param name="val">��������ֽ�������</param>
 /// <returns>���ؽ�ѹ�������</returns>
 public byte[] Decompress(byte[] val)
 {
     if (val[0] == 1) {
         Inflater inflater = new Inflater(true);
         using (InflaterInputStream decompressStream = new InflaterInputStream(new MemoryStream(UnwrapData(val)), inflater)) {
             return ArrayHelper.ReadAllBytesFromStream(decompressStream);
         }
     }
     else
         return UnwrapData(val);
 }
        public static Stream Decompress(byte[] data)
        {
            var outputStream = new MemoryStream();

            using (var compressedStream = new MemoryStream(data))
                using (var inputStream = new ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputStream(compressedStream))
                {
                    inputStream.CopyTo(outputStream);
                    outputStream.Position = 0;
                    return(outputStream);
                }
        }
Example #19
0
        public static byte[] Decompress(byte[] data)
        {
            byte[] r = null;

            using (Stream s = new InflaterInputStream(new MemoryStream(data)))
            {
                byte[] b = new byte[8192];
                int count = s.Read(b, 0, b.Length);
                r = b.Take(count).ToArray();
            }

            return r;
        }
Example #20
0
 public byte[] Decode(byte[] input, int decompressedSize)
 {
     InflaterInputStream stream = new InflaterInputStream(new MemoryStream(input));
     byte[] data = new byte[4096];
     MemoryStream outStream = new MemoryStream();
     int size;
     while ((size = stream.Read(data, 0, data.Length)) > 0)
     {
         outStream.Write(data, 0, size);
     }
     outStream.Capacity = (int)outStream.Length;
     return outStream.GetBuffer();
 }
Example #21
0
 // Length = decompressed length
 public static byte[] Decompress(int Length, byte[] Data)
 {
     byte[] Output = new byte[Length];
     Stream s = new InflaterInputStream(new MemoryStream(Data));
     int Offset = 0;
     while(true)
     {
         int size = s.Read(Output, Offset, Length);
         if (size == Length) break;
         Offset += size;
         Length -= size;
     }
     return Output;
 }
Example #22
0
 public static byte[] DecompressZlib(byte[] input)
 {
     MemoryStream source = new MemoryStream(input);
     byte[] result = null;
     using (MemoryStream outStream = new MemoryStream())
     {
         using (InflaterInputStream inf = new InflaterInputStream(source))
         {
             inf.CopyTo(outStream);
         }
         result = outStream.ToArray();
     }
     return result;
 }
 public static int Uncompress(ref byte[] Data)
 {
     int maxsize = Data.Length * 10 + 300;
     if (maxsize > 50000) maxsize = 50000;
     byte[] outputData = new byte[maxsize];
     MemoryStream dataStream = new MemoryStream(Data);
     InflaterInputStream inflater = new InflaterInputStream(dataStream);
     //int res=descompresor.Read(packetsalida,0,packetsalida.Length);
     //if (res>0)
     int res;
     int resTotal = 0;
     MemoryStream uncompressedStream = new MemoryStream();
     do
     {
         if (inflater.Position == Data.Length) res = 0;
         else
             try
             {
                 res = inflater.Read(outputData, 0, outputData.Length);
             }
             catch
             {
                 res = 0;
             }
         if (res > 0)
         {
             uncompressedStream.Write(outputData, 0, res);
         }
         resTotal += res;
     }
     while (res > 0);
     if (resTotal == 0)
     {
         return 0;
     }
     else
     {
         inflater.Close();
         inflater = null;
         dataStream.Close();
         dataStream = null;
         Data = null;
         Data = new byte[resTotal];
         uncompressedStream.Seek(0, SeekOrigin.Begin);
         uncompressedStream.Read(Data, 0, resTotal);
         uncompressedStream.Close();
         uncompressedStream = null;
         return resTotal;
     }
 }
Example #24
0
 public static byte[] Decompress(string data)
 {
     byte[] array = null;
     if (data.StartsWith("ZipStream:"))
     {
         MemoryStream memoryStream = new MemoryStream(Convert.FromBase64String(data.Substring(10)));
         InflaterInputStream inflaterInputStream = new InflaterInputStream(memoryStream);
         BinaryReader binaryReader = new BinaryReader(memoryStream);
         int num = binaryReader.ReadInt32();
         array = new byte[num];
         inflaterInputStream.Read(array, 0, num);
         inflaterInputStream.Close();
         memoryStream.Close();
     }
     return array;
 }
    public static byte[] Decompress(string data)
    {
        byte[] output = null;
        if(data.StartsWith("ZipStream:"))
        {
            var m = new MemoryStream(Convert.FromBase64String(data.Substring(10)));
            var z = new InflaterInputStream(m);
            var br = new BinaryReader(m);
            var length = br.ReadInt32();
            output = new byte[length];
            z.Read(output, 0, length);
            z.Close();
            m.Close();

        }
        return output;
    }
Example #26
0
        public static void Main(string[] args)
        {
            var delimiter = new string('-', 10);

            var url = "https://google.com";
            Console.WriteLine("{0} sending request to {1} {0}", delimiter, url);
            var request = WebRequest.Create(url) as HttpWebRequest;

            request.Method = "GET";
            request.ContentType = "application/xml; charset=\"utf-8\"";
            request.UserAgent = "sandbox-compression";

            request.Headers.Add("accept-encoding", "gzip, deflate");

            using (var response = request.GetResponse() as HttpWebResponse)
            {
                var stream = response.GetResponseStream();

                Console.WriteLine("{0} HEADERS {0}", delimiter);
                Console.WriteLine(response.Headers.ToString().Trim());

                string encoding = "NO";
                Stream decompressionStream = null;
                if (response.ContentEncoding.IndexOf("gzip", StringComparison.InvariantCultureIgnoreCase) >=
                     0)
                {
                    decompressionStream = new GZipInputStream(stream);
                    encoding = "GZIP";
                }
                else if (response.ContentEncoding.IndexOf("deflate", StringComparison.InvariantCultureIgnoreCase) >= 0)
                {
                    decompressionStream = new InflaterInputStream(stream);
                    encoding = "DEFLATE";
                }

                Console.WriteLine("{0} {1} {0}", delimiter, encoding);

                var reader = new StreamReader(decompressionStream ?? stream);

                Console.WriteLine("{0} First 20 chars of response body {0}", delimiter);

                Console.WriteLine(reader.ReadToEnd().Substring(0, 20));
            }

            Console.ReadKey();
        }
Example #27
0
 public static void Decompress(ref GenericReader gr)
 {
     int uncompressedLength = gr.ReadInt32();
     byte[] output = new byte[gr.ReadInt32()];
     byte[] temp = gr.ReadBytes((int)gr.Remaining);
     gr.Close();
     Stream s = new InflaterInputStream(new MemoryStream(temp));
     int offset = 0;
     while (true)
     {
         int size = s.Read(output, offset, uncompressedLength);
         if (size == uncompressedLength) break;
         offset += size;
         uncompressedLength -= size;
     }
     gr = new GenericReader(new MemoryStream(output));
     //gr.BaseStream.Position = 0;
 }
Example #28
0
 public static GenericReader Decompress(GenericReader gr)
 {
     int uncompressedLength = gr.ReadInt32();
     byte[] input = gr.ReadBytes((int)gr.Remaining);
     byte[] output = new byte[uncompressedLength];
     gr.Close();
     InflaterInputStream istream = new InflaterInputStream(new MemoryStream(input));
     int offset = 0;
     while (true)
     {
         int size = istream.Read(output, offset, uncompressedLength);
         if (size == uncompressedLength)
             break;
         offset += size;
         uncompressedLength -= size;
     }
     return new GenericReader(new MemoryStream(output));
 }
        public string Inflate(byte[] gzBuffer)
        {
            using (var ms = new MemoryStream())
            {
                var msgLength = BitConverter.ToInt32(gzBuffer, 0);
                ms.Write(gzBuffer, 4, gzBuffer.Length - 4);

                var buffer = new byte[msgLength];

                ms.Position = 0;
                using (var zipStream = new InflaterInputStream(ms, new Inflater()))
                {
                    zipStream.Read(buffer, 0, buffer.Length);
                }

                return Encoding.UTF8.GetString(buffer);
            }
        }
Example #30
0
 public byte[] Decompress( byte[] bytes )
 {
     Stream stream = new InflaterInputStream( new MemoryStream( bytes ) );
     MemoryStream memory = new MemoryStream();
     int totalLength = 0;
     byte[] writeData = new byte[4096];
     while ( true )
     {
         int size = stream.Read( writeData, 0, writeData.Length );
         if ( size > 0 )
         {
             totalLength += size;
             memory.Write( writeData, 0, size );
         }
         else
             break;
     }
     stream.Close();
     return memory.ToArray();
 }
Example #31
0
 public static byte[] Decompress(byte[] bytes)
 {
     InflaterInputStream stream = new InflaterInputStream(new MemoryStream(bytes));
     MemoryStream memory = new MemoryStream();
     Byte[] writeData = new byte[4096];
     int size;
     while (true)
     {
         size = stream.Read(writeData, 0, writeData.Length);
         if (size > 0)
         {
             memory.Write(writeData, 0, size);
         }
         else
         {
             break;
         }
     }
     stream.Close();
     return memory.ToArray();
 }
        public static bool Verify(string licenseString)
        {
            if (string.IsNullOrEmpty(licenseString) || !CanDecode(licenseString))
                return false;

            byte[] licenseData = Convert.FromBase64String(GetLicenceContent(licenseString));
            Console.WriteLine(Encoding.GetEncoding("UTF-32BE").GetString(licenseData.Take(4).ToArray()));
            var length = (((licenseData[0] & 0xff) << 24) | ((licenseData[1] & 0xff) << 16) | ((licenseData[2] & 0xff) << 8) | (licenseData[3] & 0xff));
            var license = licenseData.Skip(4).Take(length).ToArray();
            var sign = licenseData.Skip(length + 4).ToArray();
            byte[] unzipedData;
            using (MemoryStream inStream = new MemoryStream(license.Skip(5).ToArray()))
            using (InflaterInputStream zip = new InflaterInputStream(inStream))
            using (MemoryStream outStream = new MemoryStream())
            {
                zip.CopyTo(outStream);
                unzipedData = outStream.ToArray();
            }
            Console.WriteLine(Encoding.ASCII.GetString(unzipedData));
            return VerifyDsaMessage(Convert.FromBase64String(PublicKey), license, ConvertToP1363Signature(sign));
        }