Пример #1
0
        public void CanDecompressNormalObjectStream()
        {
            var bytes = File.ReadAllBytes(GetNthFilename());

            // The 7th object is encoded with no flate parameters.
            var obj7 = GetOffset(bytes, "7 0 obj");

            var streamPosition = GetOffset(bytes, "stream", obj7.end);

            var endStreamPosition = GetOffset(bytes, "endstream", streamPosition.end);

            var streamBytes = BytesBetween(streamPosition.end + 1, endStreamPosition.start - 1, bytes);

            var decodedBytes = new List <int>();

            using (var memo = new MemoryStream(streamBytes))
            {
                // Skip the first 2 header bytes, C#'s DeflateStream can't deal with them.
                memo.ReadByte();
                memo.ReadByte();

                using (var str = new DeflateStream(memo, CompressionMode.Decompress))
                {
                    var x = str.ReadByte();
                    while (x != -1)
                    {
                        decodedBytes.Add(x);
                        x = str.ReadByte();
                    }
                }
            }
        }
Пример #2
0
        public HttpWebResponse GetData(HttpWebRequest httpWebRequest, out string responseText)
        {
            ServicePointManager.Expect100Continue = false; //Resolve http 417 issue

            HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();

            Encoding encoding = GetEncoding(httpWebResponse.ContentType);

            using (Stream outStream = httpWebResponse.GetResponseStream())
            {
                string contentEncoding = httpWebResponse.ContentEncoding;

                if (contentEncoding.StartsWith("gzip"))
                {
                    MemoryStream ms = new MemoryStream();

                    using (Stream stream = new GZipStream(outStream, CompressionMode.Decompress))
                    {
                        int bit = stream.ReadByte();

                        while (bit > -1)
                        {
                            ms.WriteByte((byte)bit);
                            bit = stream.ReadByte();
                        }

                        responseText = encoding.GetString(ms.ToArray());
                    }
                }
                else if (contentEncoding.StartsWith("deflate"))
                {
                    MemoryStream ms = new MemoryStream();

                    using (Stream stream = new DeflateStream(outStream, CompressionMode.Decompress))
                    {
                        int bit = stream.ReadByte();

                        while (bit > -1)
                        {
                            ms.WriteByte((byte)bit);
                            bit = stream.ReadByte();
                        }

                        responseText = encoding.GetString(ms.ToArray());
                    }
                }
                else
                {
                    using (StreamReader sr = new StreamReader(outStream, encoding))
                    {
                        responseText = sr.ReadToEnd();
                    }
                }
            }

            return(httpWebResponse);
        }
Пример #3
0
        /// <summary>
        ///
        /// </summary>
        public static byte[] ApplyPatch(byte[] dol, string filePath)
        {
            using (FileStream s = new FileStream(filePath, FileMode.Open))
                using (DeflateStream r = new DeflateStream(s, CompressionMode.Decompress))
                {
                    // header check
                    if (r.ReadByte() != 0x44 || r.ReadByte() != 0x4F || r.ReadByte() != 0x4C || r.ReadByte() != 0x50)
                    {
                        return(dol);
                    }

                    while (true)
                    {
                        var offset = (r.ReadByte() & 0xFF) | ((r.ReadByte() & 0xFF) << 8) | ((r.ReadByte() & 0xFF) << 16) | ((r.ReadByte() & 0xFF) << 24);
                        var length = (r.ReadByte() & 0xFF) | ((r.ReadByte() & 0xFF) << 8) | ((r.ReadByte() & 0xFF) << 16) | ((r.ReadByte() & 0xFF) << 24);

                        if (offset == -1 && length == -1)
                        {
                            break;
                        }

                        for (int i = 0; i < length; i++)
                        {
                            dol[offset + i] = (byte)r.ReadByte();
                        }
                    }
                }
            return(dol);
        }
Пример #4
0
        private static byte[] DecryptToBytes(SymmetricAlgorithm aes, byte[] cipherBytes)
        {
            var iv = new byte[16];

            Buffer.BlockCopy(cipherBytes, 0, iv, 0, iv.Length);

            var buffer = new List <byte>();

            try
            {
                using (var memoryStream = new MemoryStream(cipherBytes, iv.Length, cipherBytes.Length - iv.Length))
                    using (var decryptor = aes.CreateDecryptor(aes.Key, iv))
                        using (var cryptStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                            using (var compressStream = new DeflateStream(cryptStream, CompressionMode.Decompress))
                            {
                                int item;
                                while ((item = compressStream.ReadByte()) != -1)
                                {
                                    buffer.Add((byte)item);
                                }
                            }
            }
            catch (CryptographicException error)
            {
                throw new CryptographicException("Decryption key can not decrypt this text", error);
            }

            return(buffer.ToArray());
        }
Пример #5
0
        public unsafe void Uncompress(int index)
        {
            /*var e = Entries[index];
             * Seek(e.Offset);*/
            (int length, int extra, bool patcher) = SeekByEntryIndex(index);
            byte[] buffer = ReadArray(length);
            int    clen   = length;
            int    dlen   = Entries[index].DecompressedLength;

            byte[] decbuffer = new byte[dlen];
            using (MemoryStream ms = new MemoryStream(buffer))
            {
                ms.Seek(2, SeekOrigin.Begin);
                using (DeflateStream stream = new DeflateStream(ms, CompressionMode.Decompress))
                {
                    for (int i = 0; i < dlen; i++)
                    {
                        decbuffer[i] = (byte)stream.ReadByte();
                    }
                }
            }

            fixed(byte *ptr = decbuffer)
            {
                _ptr      = ptr;
                _position = 0;
                _length   = decbuffer.Length;
            }
        }
Пример #6
0
        // implementation borrowed from Google's Java API.
        public static XmlDocument UnpackRequest(string packedText)
        {
            // convert from Base64
            byte[] compressedBytes = Convert.FromBase64String(packedText);

            DeflateStream inflateStream = new DeflateStream(new MemoryStream(compressedBytes), CompressionMode.Decompress, false);

            byte[] xmlMessageBytes = new byte[20000];
            int    c;
            int    resultLength = 0;

            while ((c = inflateStream.ReadByte()) >= 0)
            {
                if (resultLength >= 20000)
                {
                    throw new Exception("didn't allocate enough space to hold decompressed data");
                }
                xmlMessageBytes[resultLength++] = (byte)c;
            }

            string result = Encoding.UTF8.GetString(xmlMessageBytes, 0, resultLength);

            XmlDocument doc = new XmlDocument();

            doc.LoadXml(result);

            return(doc);
        }
Пример #7
0
        public static string Decode(string str)
        {
            string dest = "";

            using (var mms = new MemoryStream(str.Select(e => (byte)e).ToArray()))
                using (DeflateStream CompressedStream = new DeflateStream(mms, CompressionMode.Decompress))
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        // MemoryStream に展開します
                        while (true)
                        {
                            int rb = CompressedStream.ReadByte();
                            // 読み終わったとき while 処理を抜けます
                            if (rb == -1)
                            {
                                break;
                            }
                            // メモリに展開したデータを読み込みます
                            ms.WriteByte((byte)rb);
                        }
                        dest = Encoding.Unicode.GetString(ms.ToArray());
                    }
                }
            return(dest);
        }
Пример #8
0
        public override int ReadByte()
        {
            int result = 0;

            if (this.CanRead == true)
            {
                result = _deflateStream.ReadByte();

                // Check if the end of the stream has been reached
                if (result == -1)
                {
                    this.ReadCRC();
                }
                else
                {
                    _adler32.Update(Convert.ToByte(result));
                }
            }
            else
            {
                throw new InvalidOperationException();
            }

            return(result);
        }
Пример #9
0
        public byte[] Decompress(byte[] byteArray_DeflateCompressedData)
        {
            MemoryStream memoryStream_CompressedData = new MemoryStream(byteArray_DeflateCompressedData, 0, byteArray_DeflateCompressedData.Length);

            memoryStream_DecompressedData.SetLength(0);

            memoryStream_CompressedData.Position = 0;

            DeflateStream deflateStream_obj = new DeflateStream(memoryStream_CompressedData, CompressionMode.Decompress, true);

            int int_DecompressedByte = 0;

            for (; ;)
            {
                int_DecompressedByte = deflateStream_obj.ReadByte();

                if (int_DecompressedByte == -1)
                {
                    break;
                }

                memoryStream_DecompressedData.WriteByte((byte)int_DecompressedByte);
            }

            deflateStream_obj.Flush();
            deflateStream_obj.Close();

            memoryStream_CompressedData.Close();

            memoryStream_DecompressedData.SetLength(memoryStream_DecompressedData.Position);

            return(memoryStream_DecompressedData.ToArray());
        }
        /// <summary>
        /// Returns the embedded source for specified document.
        /// </summary>
        /// <param name="document">The document to read source of.</param>
        /// <returns>
        /// default(<see cref="ArraySegment{T}"/>) if the document doesn't have embedded source,
        /// otherwise byte array segment containing the source.
        /// </returns>
        public static ArraySegment <byte> GetEmbeddedSource(this ISymUnmanagedDocument document)
        {
            if (document == null)
            {
                throw new ArgumentNullException(nameof(document));
            }

            Marshal.ThrowExceptionForHR(document.GetSourceLength(out int length));
            if (length == 0)
            {
                return(default(ArraySegment <byte>));
            }

            if (length < sizeof(int))
            {
                throw new InvalidDataException();
            }

            var blob = new byte[length];

            Marshal.ThrowExceptionForHR(document.GetSourceRange(0, 0, int.MaxValue, int.MaxValue, length, out int bytesRead, blob));
            if (bytesRead < sizeof(int) || bytesRead > blob.Length)
            {
                throw new InvalidDataException();
            }

            int uncompressedLength = BitConverter.ToInt32(blob, 0);

            if (uncompressedLength == 0)
            {
                return(new ArraySegment <byte>(blob, sizeof(int), bytesRead - sizeof(int)));
            }

            var uncompressedBytes = new byte[uncompressedLength];

            var compressed = new MemoryStream(blob, sizeof(int), bytesRead - sizeof(int));

            using (var decompressor = new DeflateStream(compressed, CompressionMode.Decompress))
            {
                int position = 0;

                while (true)
                {
                    int bytesDecompressed = decompressor.Read(uncompressedBytes, position, uncompressedBytes.Length - position);
                    if (bytesDecompressed == 0)
                    {
                        break;
                    }

                    position += bytesDecompressed;
                }

                if (position != uncompressedBytes.Length || decompressor.ReadByte() != -1)
                {
                    throw new InvalidDataException();
                }

                return(new ArraySegment <byte>(uncompressedBytes));
            }
        }
Пример #11
0
        static void Main()
        {
            FileStream source      = File.OpenRead(@"D:\archive.dfl");
            FileStream destination = File.Create(@"D:\text_deflate.txt");

            DeflateStream deCompressor = new DeflateStream(source, CompressionMode.Decompress);

            int theByte = deCompressor.ReadByte();

            while (theByte != -1)
            {
                destination.WriteByte((byte)theByte);
                theByte = deCompressor.ReadByte();
            }

            deCompressor.Close();
        }
Пример #12
0
        /// <summary>
        /// Decompresses (inflates) bytes from input stream.
        /// </summary>
        /// <remarks>
        /// Stream marker is being set at +<code>numOfBytes</code> position of the stream.
        /// </remarks>
        /// <param name="buf">Input byte buffer stream.</param>
        /// <param name="numOfBytes">The number of bytes to be read.</param>
        /// <returns>new <c>ByteBuffer</c> with the inflated block of data.</returns>
        /// <exception cref="IOException">When an error occurs while reading or inflating the buffer.</exception>
        Stream Inflate(Stream buf, int numOfBytes)
        {
            if (buf.Length - buf.Position < numOfBytes)
            {
                throw new MatlabIOException("Compressed buffer length miscalculated!");
            }

#if false
            // test code!
            byte[] byteBuffer = new byte[numOfBytes];
            long   pos        = buf.Position;
            int    n          = buf.Read(byteBuffer, 0, numOfBytes);
            buf.Position = pos;
            File.WriteAllBytes("DeflatedMatlabData.bin", byteBuffer);
#endif

            try
            {
                // skip CRC (at end) and zip format (0x789C at begin)
                buf.Position += 2;
                numOfBytes   -= 6;

                var compressedStream = new MemoryStream();
                int data;
                do
                {
                    data = buf.ReadByte();
                    if (data != -1)
                    {
                        compressedStream.WriteByte((byte)(data & 0x000000FF));
                    }
                }while (data != -1 && compressedStream.Length < numOfBytes);

                // skip CRC
                buf.Position += 4;
                compressedStream.Position = 0;
                var decompressedStream = new MemoryStream();
                using (var df = new DeflateStream(compressedStream, CompressionMode.Decompress))
                {
                    do
                    {
                        data = df.ReadByte();
                        if (data != -1)
                        {
                            decompressedStream.WriteByte((byte)(data & 0x000000FF));
                        }
                    }while (data != -1);
                }
                decompressedStream.Position = 0;
                return(decompressedStream);
            }
            catch (IOException e)
            {
                throw new MatlabIOException("Could not decompress data: " + e);
            }
        }
Пример #13
0
        // internal for testing
        internal static unsafe ImmutableArray <byte> DecodeEmbeddedPortablePdbDebugDirectoryData(AbstractMemoryBlock block)
        {
            byte[] decompressed;

            const int headerSize = 2 * sizeof(int);

            var headerReader = new BlobReader(block.Pointer, headerSize);

            if (headerReader.ReadUInt32() != PortablePdbVersions.DebugDirectoryEmbeddedSignature)
            {
                throw new BadImageFormatException(SR.UnexpectedEmbeddedPortablePdbDataSignature);
            }

            int decompressedSize = headerReader.ReadInt32();

            try
            {
                decompressed = new byte[decompressedSize];
            }
            catch
            {
                throw new BadImageFormatException(SR.DataTooBig);
            }

            var compressed = new ReadOnlyUnmanagedMemoryStream(block.Pointer + headerSize, block.Size - headerSize);
            var deflate    = new DeflateStream(compressed, CompressionMode.Decompress, leaveOpen: true);

            if (decompressedSize > 0)
            {
                int actualLength;

                try
                {
                    actualLength = deflate.TryReadAll(decompressed, 0, decompressed.Length);
                }
                catch (InvalidDataException e)
                {
                    throw new BadImageFormatException(e.Message, e.InnerException);
                }

                if (actualLength != decompressed.Length)
                {
                    throw new BadImageFormatException(SR.SizeMismatch);
                }
            }

            // Check that there is no more compressed data left,
            // in case the decompressed size specified in the header is smaller
            // than the actual decompressed size of the data.
            if (deflate.ReadByte() != -1)
            {
                throw new BadImageFormatException(SR.SizeMismatch);
            }

            return(ImmutableByteArrayInterop.DangerousCreateFromUnderlyingArray(ref decompressed));
        }
Пример #14
0
        protected override sealed int Read()
        {
            if (_hasPeeked)
            {
                _hasPeeked = false;
                return(_peekedChar);
            }

            return(_compressedStream.ReadByte());
        }
Пример #15
0
        /// <summary>
        /// Decompressed a zlib-compressed movie atom.
        /// </summary>
        /// <param name="compressedData">the zlib-compressed data</param>
        /// <param name="uncompressedSize">the original size of the movie atom</param>
        /// <returns>the decompressed movie atom bytes</returns>
        private static byte[] DecompressZlib(byte[] compressedData, uint uncompressedSize)
        {
            byte[] b2 = new byte[uncompressedSize];

            Stream stream;

            if (compressedData[0] == 0x78 && compressedData[1] == 0x9C)
            {
                // Skip 2-byte zlib header
                stream = new MemoryStream(compressedData, 2, compressedData.Length - 2);
            }
            else
            {
                stream = new MemoryStream(compressedData);
            }

            using (stream)
            {
                // TODO in the data compression atom you can find what
                // lossless data compression algorithm was used to compress
                // the movie resource.
                using (DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress))
                {
                    try
                    {
                        int pos = 0;
                        while (deflateStream.CanRead && pos < b2.Length)
                        {
                            b2[pos++] = (byte)deflateStream.ReadByte();
                        }
                    }
                    catch (InvalidDataException e)
                    {
                        Console.WriteLine(e.ToString());
                    }
                }
            }

            // Dump decompressed data to console out
            for (int i = 0; i < b2.Length; i++)
            {
                Console.Write(" {0:X2}", b2[i]);

                if ((i % 16) == 15)
                {
                    Console.Write(" | ");
                    for (int j = i - 15; j <= i; j++)
                    {
                        Console.Write("{0}", Char.IsControl((char)b2[j]) ? '.' : (char)b2[j]);
                    }
                    Console.WriteLine();
                }
            }
            return(b2);
        }
        internal static unsafe ImmutableArray <byte> DecodeEmbeddedPortablePdbDebugDirectoryData(AbstractMemoryBlock block)
        {
            byte[] decompressed;

            var headerReader = block.GetReader();

            if (headerReader.ReadUInt32() != PortablePdbVersions.DebugDirectoryEmbeddedSignature)
            {
                throw new BadImageFormatException("UnexpectedEmbeddedPortablePdbDataSignature");
            }

            int decompressedSize = headerReader.ReadInt32();

            try
            {
                decompressed = new byte[decompressedSize];
            }
            catch
            {
                throw new BadImageFormatException("DataTooBig");
            }

            var compressed = new ReadOnlyUnmanagedMemoryStream(headerReader.CurrentPointer, headerReader.RemainingBytes);
            var deflate    = new DeflateStream(compressed, CompressionMode.Decompress, leaveOpen: true);

            if (decompressedSize > 0)
            {
                int actualLength;

                try
                {
                    actualLength = deflate.TryReadAll(decompressed, 0, decompressed.Length);
                }
                catch (InvalidDataException e)
                {
                    throw new BadImageFormatException(e.Message, e.InnerException);
                }

                if (actualLength != decompressed.Length)
                {
                    throw new BadImageFormatException("SizeMismatch");
                }
            }

            // Check that there is no more compressed data left,
            // in case the decompressed size specified in the header is smaller
            // than the actual decompressed size of the data.
            if (deflate.ReadByte() != -1)
            {
                throw new BadImageFormatException("SizeMismatch");
            }

            return(new ImmutableArray <byte>(decompressed));
        }
Пример #17
0
        public DeflateDataSource(DataSource Source)
        {
            MemoryStream  MemoryStream  = new MemoryStream(Source.Read(0, Source.Size));
            DeflateStream DeflateStream = new DeflateStream(MemoryStream, CompressionMode.Decompress);

            List <byte> Decompressed = new List <byte>();

            try
            {
                int Byte = DeflateStream.ReadByte();
                while (Byte != -1)
                {
                    Decompressed.Add((byte)Byte);
                    Byte = DeflateStream.ReadByte();
                }
            }
            catch { }
            this.Data = Decompressed.ToArray();

            DeflateStream.Close();
        }
Пример #18
0
        public IEnumerable <Track> Decode(string input)
        {
            var tracks = new List <Track>();

            if (input[0] != '1')
            {
                throw new FormatException("Code is not a version 1 share code.");
            }

            try
            {
                byte[] bytes = Convert.FromBase64String(input.Substring(1));
                using (var ms = new MemoryStream(bytes))
                    using (var stream = new DeflateStream(ms, CompressionMode.Decompress))
                    {
                        int col = stream.ReadByte();

                        while (col != -1)
                        {
                            int row       = stream.ReadByte();
                            var direction = (TrackDirection)stream.ReadByte();

                            tracks.Add(new Track(null)
                            {
                                Column    = col,
                                Row       = row,
                                Direction = direction
                            });

                            col = stream.ReadByte();
                        }
                    }

                return(tracks);
            }
            catch
            {
                throw new FormatException("Code is not valid.");
            }
        }
Пример #19
0
 public static string DecompressString(byte[] _bytes)
 {
     using (MemoryStream ms = new MemoryStream(_bytes))
     {
         using (DeflateStream ds = new DeflateStream(ms, CompressionMode.Decompress))
         {
             using (MemoryStream resStream = new MemoryStream())
             {
                 int b = ds.ReadByte();
                 while (b > 0)
                 {
                     resStream.WriteByte((byte)b);
                     b = ds.ReadByte();
                 }
                 byte[] buf = new byte[resStream.Position];
                 resStream.Seek(0L, SeekOrigin.Begin);
                 resStream.Read(buf, 0, buf.Length);
                 return(new string(UTF8Encoding.UTF8.GetChars(buf)));
             }    //using resStream
         }        //using ds
     }            //using ms
 }
Пример #20
0
    public void Read(BinaryReader Serialized)
    {
        BinaryReader __FromSerialize;         /* variable to hold decompressed     serialized binary data */

        using (MemoryStream __MemoryStreamIn =
                   new MemoryStream((byte[])Serialized.ReadBytes(Convert.ToInt32(Serialized.BaseStream.Length))))
        {
            using (DeflateStream __DecompressStream =
                       new DeflateStream(__MemoryStreamIn, CompressionMode.Decompress))
            {
                using (MemoryStream __MemoryStreamOut = new MemoryStream())
                {
                    for (int __Byte = __DecompressStream.ReadByte(); __Byte != -1;
                         __Byte = __DecompressStream.ReadByte())
                    {
                        __MemoryStreamOut.WriteByte((byte)__Byte);
                    }

                    __FromSerialize = new BinaryReader(__MemoryStreamOut);


                    __FromSerialize.BaseStream.Position = 0;

                    int __CountDoubles = __FromSerialize.ReadInt32();

                    if (__CountDoubles > -1)
                    {
                        this.ValueList = new List <Double>(__CountDoubles);

                        for (int __Index = 0; __Index < __CountDoubles; __Index++)
                        {
                            this.ValueList.Add(__FromSerialize.ReadDouble());
                        }
                    }
                }
            }
        }
    }
Пример #21
0
        private byte[] Decompress(byte[] input)
        {
            try
            {
                using (var memoryStream = new MemoryStream(input))
                {
                    // The first 2 bytes are the header which DelfateStream does not support.
                    memoryStream.ReadByte();
                    memoryStream.ReadByte();

                    using (var deflate = new DeflateStream(memoryStream, CompressionMode.Decompress))
                    {
                        var bytes = new List <byte>();

                        var x = deflate.ReadByte();
                        while (x != -1)
                        {
                            bytes.Add((byte)x);
                            x = deflate.ReadByte();
                        }

                        var result = new byte[bytes.Count];

                        for (var i = 0; i < bytes.Count; i++)
                        {
                            result[i] = bytes[i];
                        }

                        return(result);
                    }
                }
            }
            catch (Exception ex)
            {
                log?.Error("Could not decode the input using the deflate stream. Input was: " + input, ex);
                throw;
            }
        }
Пример #22
0
 private byte[] DeflaterDecompress(byte[] toDecompress)
 {
     //decompression
     using (MemoryStream decompressedStream = new MemoryStream()) {
         using (MemoryStream compressedStream = new MemoryStream(toDecompress)) {
             using (DeflateStream deflater = new DeflateStream(compressedStream, CompressionMode.Decompress)) {
                 int c = 0;
                 while ((c = deflater.ReadByte()) != -1)
                 {
                     decompressedStream.WriteByte((byte)c);
                 }
             }
         }
         return(decompressedStream.ToArray());
     }
 }
Пример #23
0
        /// <summary>
        /// Decompresses (inflates) bytes from input stream.
        /// </summary>
        /// <remarks>
        /// Stream marker is being set at +<code>numOfBytes</code> position of the stream.
        /// </remarks>
        /// <param name="buf">Input byte buffer stream.</param>
        /// <param name="numOfBytes">The number of bytes to be read.</param>
        /// <returns>new <c>ByteBuffer</c> with the inflated block of data.</returns>
        /// <exception cref="IOException">When an error occurs while reading or inflating the buffer.</exception>
        private Stream Inflate(Stream buf, int numOfBytes)
        {
            if (buf.Length - buf.Position < numOfBytes)
            {
                throw new MatlabIOException("Compressed buffer length miscalculated!");
            }

            try
            {
                // skip CRC (at end) and zip format (0x789C at begin)
                buf.Position += 2;
                numOfBytes   -= 6;

                MemoryStream compressedStream = new MemoryStream();
                int          data;
                do
                {
                    data = buf.ReadByte();
                    if (data != -1)
                    {
                        compressedStream.WriteByte((byte)(data & 0x000000FF));
                    }
                } while (data != -1 && compressedStream.Length < numOfBytes);

                // skip CRC
                buf.Position += 4;
                compressedStream.Position = 0;
                MemoryStream decompressedStream = new MemoryStream();
                using (DeflateStream df = new DeflateStream(compressedStream, CompressionMode.Decompress))
                {
                    do
                    {
                        data = df.ReadByte();
                        if (data != -1)
                        {
                            decompressedStream.WriteByte((byte)(data & 0x000000FF));
                        }
                    } while (data != -1);
                }
                decompressedStream.Position = 0;
                return(decompressedStream);
            }
            catch (IOException e)
            {
                throw new MatlabIOException("Could not decompress data: " + e);
            }
        }
Пример #24
0
        public override bool IsNbtDocument()
        {
            bool   result;
            Stream stream;
            long   position;

            stream = _originalStream ?? _stream;

            if (stream.CanSeek)
            {
                position = stream.Position;
            }
            else
            {
                position = -1;
            }

            if (stream.IsGzipCompressed())
            {
                using (Stream decompressionStream = new GZipStream(stream, CompressionMode.Decompress, true))
                {
                    result = decompressionStream.ReadByte() == (int)TagType.Compound;
                }
            }
            else if (stream.IsDeflateCompressed())
            {
                using (Stream decompressionStream = new DeflateStream(stream, CompressionMode.Decompress, true))
                {
                    result = decompressionStream.ReadByte() == (int)TagType.Compound;
                }
            }
            else if (stream.ReadByte() == (int)TagType.Compound)
            {
                result = true;
            }
            else
            {
                result = false;
            }

            if (stream.CanSeek)
            {
                stream.Position = position;
            }

            return(result);
        }
Пример #25
0
        public void Bug44994_InflateByteByByte()
        {
            int byteCount = 0;

            using (var fileStream = File.OpenRead(Path.Combine("Test", "compressed.bin")))
            {
                using (var deflateStream = new DeflateStream(fileStream, CompressionMode.Decompress, false))
                {
                    while (deflateStream.ReadByte() != -1)
                    {
                        byteCount++;
                    }
                }
            }

            Assert.AreEqual(125387, byteCount);
        }
Пример #26
0
        public static string Decrypt(string text, string key)
        {
            AesCryptoServiceProvider aes = new AesCryptoServiceProvider();

            aes.BlockSize = 128;
            aes.KeySize   = key.Length * 8;
            aes.Key       = Encoding.UTF8.GetBytes(key);
            aes.Mode      = CipherMode.CBC;
            aes.Padding   = PaddingMode.PKCS7;
            var s = text.Substring(text.Length - 24, 24);
            var b = Convert.FromBase64String(s);

            aes.IV = b;

            var buf = Convert.FromBase64String(text.Remove(text.Length - 24, 24));

            byte[] dst = null;
            using (ICryptoTransform decrypt = aes.CreateDecryptor())
            {
                dst = decrypt.TransformFinalBlock(buf, 0, buf.Length);
            }

            using (var ms = new MemoryStream(dst))
            {
                using (var ms2 = new MemoryStream())
                    using (var cs = new DeflateStream(ms, CompressionMode.Decompress))
                    {
                        while (true)
                        {
                            var br = cs.ReadByte();
                            if (br == -1)
                            {
                                break;
                            }
                            ms2.WriteByte((byte)br);
                        }
                        dst = ms2.ToArray();
                    }
            }

            return(Encoding.Unicode.GetString(dst));
        }
Пример #27
0
        static void Deflate_NoRepetition()
        {
            using (Stream s = File.Create("compressed.bin"))
                using (Stream ds = new DeflateStream(s, CompressionMode.Compress))
                    for (byte i = 0; i < 100; i++)
                    {
                        ds.WriteByte(i);
                    }

            Console.WriteLine($"Size on disk: {new FileInfo("compressed.bin").Length}");

            using (Stream s = File.OpenRead("compressed.bin"))
                using (Stream ds = new DeflateStream(s, CompressionMode.Decompress))
                    for (byte i = 0; i < 100; i++)
                    {
                        Console.WriteLine(ds.ReadByte());
                    }                                     // Writes 0 to 99

            File.Delete("compressed.bin");
        }
Пример #28
0
 static void FixedBufferDecompress(byte[] data, ref byte[] destArray)
 {
     using (var compressedStream = new MemoryStream(data))
         using (var zipStream = new DeflateStream(compressedStream, CompressionMode.Decompress))
             using (var resultStream = new MemoryStream())
             {
                 try
                 {
                     int idx     = 0;
                     int byteVal = -1;
                     do
                     {
                         byteVal        = zipStream.ReadByte();
                         destArray[idx] = (byte)byteVal;
                         idx++;
                     } while (byteVal > -1 && idx < destArray.Length);
                 }
                 catch { }
             }
 }
Пример #29
0
 public byte[] DeflaterDecompress(byte[] toDecompress)
 {
     byte[] result;
     using (MemoryStream memoryStream = new MemoryStream())
     {
         using (MemoryStream memoryStream2 = new MemoryStream(toDecompress))
         {
             using (DeflateStream deflateStream = new DeflateStream(memoryStream2, CompressionMode.Decompress))
             {
                 int num;
                 while ((num = deflateStream.ReadByte()) != -1)
                 {
                     memoryStream.WriteByte((byte)num);
                 }
             }
         }
         result = memoryStream.ToArray();
     }
     return(result);
 }
Пример #30
0
        /// <exception cref="IOException"/>
        /// <exception cref="ObjectDisposedException"/>
        /// <exception cref="InvalidDataException"/>
        private void ReadBlockIntoBuffer(int index)
        {
            EnsureBufferInitialised();

            _buffer_size = blockUncompSizes[index];
            _stream.Seek(blockOffsets[index], SeekOrigin.Begin);
            if (blockIsCompressed[index])
            {
                using DeflateStream deflateStream = new DeflateStream(_stream, CompressionMode.Decompress, true);
                deflateStream.Read(_buffer, 0, _buffer_size);
                if (deflateStream.ReadByte() != -1)
                {
                    throw new InvalidDataException(Strings.InvalidData_Segs);
                }
            }
            else
            {
                _stream.Read(_buffer, 0, _buffer_size);
            }
        }
Пример #31
0
        public void Roundtrip_Write_ReadByte()
        {
            byte[] data = new byte[1024 * 10];
            new Random(42).NextBytes(data);

            var compressed = new MemoryStream();
            using (var compressor = new DeflateStream(compressed, CompressionMode.Compress, true))
            {
                compressor.Write(data, 0, data.Length);
            }
            compressed.Position = 0;

            using (var decompressor = new DeflateStream(compressed, CompressionMode.Decompress, true))
            {
                for (int i = 0; i < data.Length; i++)
                    Assert.Equal(data[i], decompressor.ReadByte());
            }
        }