Win32 API doesn't provide DEFLATE Compressor/Decompressor. Apparently Win32 API does provide a "MSZIP" compressor/decompressor which is an extension of the DEFLATE algorithm, so logically you should be able to use it to decompress DEFLATE compressed buffers. Meanwhile as per MDN docs the COMPRESS_ALGORITHM_XPRESS_HUFF refers to "XPRESS compression algorithm with Huffman encoding" ( Source ). Whereas Zlib uses DEFLATE and DEFLATE uses a combination of LZ77 and Huffman coding ( Source ). Also Note that Zlib compressed buffers also contain some header data that Zlib knows how to read and then decode the data which is Zlib specific, so make sure you handle that. These are some libraries related to Zlib and DEFLATE: https://github.com/ebiggers/libdeflate https://github.com/vurtun/lib https://github.com/jibsen/tinf And Mark Adler is not on Reddit as far as I am aware but he has contact information on the Zlib's website. Answer from MisterEmbedded on reddit.com
🌐
SourceForge
gnuwin32.sourceforge.net β€Ί packages β€Ί zlib.htm
zlib for Windows
(LZW can double or triple the file size in extreme cases.) zlib's memory footprint is also independent of the input data and can be reduced, if necessary, at some cost in compression. ... You can also download the files from the GnuWin32 files page. You can monitor new releases of the port of this package. ... MS-Windows 95 / 98 / ME / NT / 2000 / XP with msvcrt.dll.
🌐
Python
docs.python.org β€Ί 3 β€Ί library β€Ί zlib.html
zlib β€” Compression compatible with gzip
+40 to +47 = 32 + (8 to 15): Uses the low 4 bits of the value as the window size logarithm, and automatically accepts either the zlib or gzip format. When decompressing a stream, the window size must not be smaller than the size originally used to compress the stream; using a too-small value may result in an error exception.
Discussions

Zlib uncompression for an idiot? | MajorGeeks.Com Support Forums
I want to uncompress a ZLIB-compressed file, without any programming skill. Could some of you give me exact help? More on forums.majorgeeks.com
🌐 forums.majorgeeks.com
September 25, 2010
compression - How to uncompress zlib data in UNIX? - Unix & Linux Stack Exchange
Unfortunately I don't see any option to uncompress such raw data in gzip man page, and the zlib package does not contain any executable utility. ... There are many additional answers here: stackoverflow.com/questions/3178566/deflate-command-line-tool ... It is also possible to decompress it using ... More on unix.stackexchange.com
🌐 unix.stackexchange.com
September 20, 2011
c - file compression using zlib - Stack Overflow
You cannot use gzip by itself to store multiple files. For a Windows application, I would recommend libzip for multiple files, which encodes and decodes .zip files. libzip uses zlib for the compression and decompression part. More on stackoverflow.com
🌐 stackoverflow.com
compression - zlib decompression in python - Stack Overflow
Have you tried to decompress the failing files with any other zlib-reading software? With what results? Please clarify what you have to work with: Does "Am I hosed?" mean that you don't have access to the original data? How did it get from a stream to a file? What guarantee do you have that the data was not mangled in transmission? UPDATE Some observations based on partial clarifications published in your self-answer: You are using Windows... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Reddit
reddit.com β€Ί r/c_programming β€Ί how to deflate zlib compressed buffer using win32 compression api?
r/C_Programming on Reddit: How to deflate zlib compressed buffer using Win32 compression API?
March 27, 2024 -

I'm porting a png loader to Win32 from OSX. On OSX/iOS I was able to use the system provided compression api to deflate the zlib compressed data based on the number of PNG IDAT chunks using both buffer based (when # IDAT chunks == 1) and stream based (when # IDAT Chunks > 1) api calls. I simply push past the two bytes in the zlib header and feed the compressed buffer and size of the buffer (less the two header bytes) to the OSX API call.

Now I am attempting to do the same using the Win32 compression API in buffer mode with the same buffer read from a PNG file with only 1 IDAT chunk:

//  Create an MSZIP decompressor.
    Success = CreateDecompressor(
        COMPRESS_ALGORITHM_MSZIP,       //  Compression Algorithm
        NULL,                           //  Optional allocation routine
        &Decompressor);                 //  Handle

    if (!Success)
    {
        wprintf(L"Cannot create a decompressor: %d.\n", GetLastError());
        goto done;
    }

    //  Query decompressed buffer size.
    Success = Decompress(
        Decompressor,                //  Compressor Handle
        src_buf,                     //  Compressed data
        src_size,                    //  Compressed data size
        NULL,                        //  Buffer set to NULL
        0,                           //  Buffer size set to 0
        &DecompressedBufferSize);    //  Decompressed Data size

However, I always get error 605 (ERROR_BAD_COMPRESSION_BUFFER) after calling Decompress no matter which compression algorithm I use.

  1. What is the appropriate Win32 compression algorithm to use for zlib deflate?

  2. How does this API expect the zlib wrapped compressed buffer to be formatted/passed as input?

  3. Anything else? Does the compressed input buffer need to be writeable or something like that?

  4. Is Mark Adler on Reddit?

Edit: Replaced COMPRESS_ALGORITHM_XPRESS_HUFF initially posted in code above with COMPRESS_ALGORITHM_MSZIP to indicate confusion about RFC 1951 per comment below.

🌐
GitHub
github.com β€Ί kevin-cantwell β€Ί zlib
GitHub - kevin-cantwell/zlib: A command-line utility for quickly compressing or decompressing zlib data. Β· GitHub
USAGE: zlib [global options] command [command options] [arguments...] VERSION: 0.0.0 COMMANDS: help, h Shows a list of commands or help for one command GLOBAL OPTIONS: -d, --decompress Decompresses the input instead of compressing the output.
Starred by 48 users
Forked by 4 users
Languages Β  Go
Win32 API doesn't provide DEFLATE Compressor/Decompressor. Apparently Win32 API does provide a "MSZIP" compressor/decompressor which is an extension of the DEFLATE algorithm, so logically you should be able to use it to decompress DEFLATE compressed buffers. Meanwhile as per MDN docs the COMPRESS_ALGORITHM_XPRESS_HUFF refers to "XPRESS compression algorithm with Huffman encoding" ( Source ). Whereas Zlib uses DEFLATE and DEFLATE uses a combination of LZ77 and Huffman coding ( Source ). Also Note that Zlib compressed buffers also contain some header data that Zlib knows how to read and then decode the data which is Zlib specific, so make sure you handle that. These are some libraries related to Zlib and DEFLATE: https://github.com/ebiggers/libdeflate https://github.com/vurtun/lib https://github.com/jibsen/tinf And Mark Adler is not on Reddit as far as I am aware but he has contact information on the Zlib's website. Answer from MisterEmbedded on reddit.com
🌐
MajorGeeks
forums.majorgeeks.com β€Ί threads β€Ί zlib-uncompression-for-an-idiot.223640
Zlib uncompression for an idiot? | MajorGeeks.Com Support Forums
September 25, 2010 - I want to uncompress a ZLIB-compressed file, without any programming skill. Could some of you give me exact help?
🌐
zlib
zlib.net
zlib Home Site
zlib was written by Jean-loup Gailly (compression) and Mark Adler (decompression). ... Address findings of the 7ASecurity audit of zlib. Check for negative lengths in crc32_combine functions. Copy only the initialized window contents in inflateCopy.
Find elsewhere
🌐
Code Beautify
codebeautify.org β€Ί zlib-decompress-online
Zlib Decompress Online to Zlib Decode Text
Zlib to Decompress Online works well on Windows, MAC, Linux, Chrome, Firefox, Edge, and Safari.
🌐
zlib
zlib.net β€Ί manual.html
zlib 1.3.1 Manual
In addition, the current implementation of deflate will use at most the window size minus 262 bytes of the provided dictionary. Upon return of this function, strm->adler is set to the Adler-32 value of the dictionary; the decompressor may later use this value to determine which dictionary has been used by the compressor.
🌐
CRAN
cran.r-project.org β€Ί web β€Ί packages β€Ί zlib β€Ί zlib.pdf pdf
zlib: Compression and Decompression
October 18, 2023 - Compression method, default is zlib$DEFLATED. ... Window bits, default is zlib$MAX_WBITS.
🌐
STMicroelectronics Community
community.st.com β€Ί stmicroelectronics community β€Ί discussions β€Ί product forums β€Ί stm32 mcus software development tools β€Ί stm32cubeide (mcus) β€Ί decompressing a file from zlib library
decompressing a file from zlib library | Community
February 21, 2022 - I wasn't sure of what would be the extension of the compressed file so I've added ".z" at the end which the windows do recognise as a compressed file but 7zip cannot decompress. When using the inflate() function it returns Z_DATA_ERROR (-3) ... This topic has been closed for replies. ... Typically when building/validating this stuff you'd build PC side pack/unpack programs using ZLIB, prove you got all the logic right, perhaps test on the unpacked equivalent to your 3MB to 26KB case, and make sure it's not outlandish.
🌐
Openmv
docs.openmv.io β€Ί openmv micropython β€Ί openmv micropython libraries β€Ί zlib β€” zlib compression & decompression
zlib β€” zlib compression & decompression - OpenMV MicroPython 1.28 documentation
Decompresses data into a bytes object. The wbits parameter works the same way as for zlib.compress() with the following additional valid values: 0: Automatically determine the window size from the zlib header (data must be in zlib format).
Top answer
1 of 4
36

According to RFC 1950 , the difference between the "OK" 0x789C and the "bad" 0x78DA is in the FLEVEL bit-field:

  FLEVEL (Compression level)
     These flags are available for use by specific compression
     methods.  The "deflate" method (CM = 8) sets these flags as
     follows:

        0 - compressor used fastest algorithm
        1 - compressor used fast algorithm
        2 - compressor used default algorithm
        3 - compressor used maximum compression, slowest algorithm

     The information in FLEVEL is not needed for decompression; it
     is there to indicate if recompression might be worthwhile.

"OK" uses 2, "bad" uses 3. So that difference in itself is not a problem.

To get any further, you might consider supplying the following information for each of compressing and (attempted) decompressing: what platform, what version of Python, what version of the zlib library, what was the actual code used to call the zlib module. Also supply the full traceback and error message from the failing decompression attempts. Have you tried to decompress the failing files with any other zlib-reading software? With what results? Please clarify what you have to work with: Does "Am I hosed?" mean that you don't have access to the original data? How did it get from a stream to a file? What guarantee do you have that the data was not mangled in transmission?

UPDATE Some observations based on partial clarifications published in your self-answer:

You are using Windows. Windows distinguishes between binary mode and text mode when reading and writing files. When reading in text mode, Python 2.x changes '\r\n' to '\n', and changes '\n' to '\r\n' when writing. This is not a good idea when dealing with non-text data. Worse, when reading in text mode, '\x1a' aka Ctrl-Z is treated as end-of-file.

To compress a file:

# imports and other superstructure left as a exercise
str_object1 = open('my_log_file', 'rb').read()
str_object2 = zlib.compress(str_object1, 9)
f = open('compressed_file', 'wb')
f.write(str_object2)
f.close()

To decompress a file:

str_object1 = open('compressed_file', 'rb').read()
str_object2 = zlib.decompress(str_object1)
f = open('my_recovered_log_file', 'wb')
f.write(str_object2)
f.close()

Aside: Better to use the gzip module which saves you having to think about nasssties like text mode, at the cost of a few bytes for the extra header info.

If you have been using 'rb' and 'wb' in your compression code but not in your decompression code [unlikely?], you are not hosed, you just need to flesh out the above decompression code and go for it.

Note carefully the use of "may", "should", etc in the following untested ideas.

If you have not been using 'rb' and 'wb' in your compression code, the probability that you have hosed yourself is rather high.

If there were any instances of '\x1a' in your original file, any data after the first such is lost -- but in that case it shouldn't fail on decompression (IOW this scenario doesn't match your symptoms).

If a Ctrl-Z was generated by zlib itself, this should cause an early EOF upon attempted decompression, which should of course cause an exception. In this case you may be able to gingerly reverse the process by reading the compressed file in binary mode and then substitute '\r\n' with '\n' [i.e. simulate text mode without the Ctrl-Z -> EOF gimmick]. Decompress the result. Edit Write the result out in TEXT mode. End edit

UPDATE 2 I can reproduce your symptoms -- with ANY level 1 to 9 -- with the following script:

import zlib, sys
fn = sys.argv[1]
level = int(sys.argv[2])
s1 = open(fn).read() # TEXT mode
s2 = zlib.compress(s1, level)
f = open(fn + '-ct', 'w') # TEXT mode
f.write(s2)
f.close()
# try to decompress in text mode
s1 = open(fn + '-ct').read() # TEXT mode
s2 = zlib.decompress(s1) # error -5
f = open(fn + '-dtt', 'w')
f.write(s2)
f.close()

Note: you will need a use a reasonably large text file (I used an 80kb source file) to ensure that the decompression result will contain a '\x1a'.

I can recover with this script:

import zlib, sys
fn = sys.argv[1]
# (1) reverse the text-mode write
# can't use text-mode read as it will stop at Ctrl-Z
s1 = open(fn, 'rb').read() # BINARY mode
s1 = s1.replace('\r\n', '\n')
# (2) reverse the compression
s2 = zlib.decompress(s1)
# (3) reverse the text mode read
f = open(fn + '-fixed', 'w') # TEXT mode
f.write(s2)
f.close()

NOTE: If there is a '\x1a' aka Ctrl-Z byte in the original file, and the file is read in text mode, that byte and all following bytes will NOT be included in the compressed file, and thus can NOT be recovered. For a text file (e.g. source code), this is no loss at all. For a binary file, you are most likely hosed.

Update 3 [following late revelation that there's an encryption/decryption layer involved in the problem]:

The "Error -5" message indicates that the data that you are trying to decompress has been mangled since it was compressed. If it's not caused by using text mode on the files, suspicion obviously(?) falls on your decryption and encryption wrappers. If you want help, you need to divulge the source of those wrappers. In fact what you should try to do is (like I did) put together a small script that reproduces the problem on more than one input file. Secondly (like I did) see whether you can reverse the process under what conditions. If you want help with the second stage, you need to divulge the problem-reproduction script.

2 of 4
4

I was looking for

python -c 'import sys,zlib;sys.stdout.write(zlib.decompress(sys.stdin.read()))'

wrote it myself; based on answers of zlib decompression in python

🌐
Filext
filext.com β€Ί file-extension β€Ί ZLIB
ZLIB File Extension - What is it? How to open a ZLIB file?
Usage: Common in systems that require fast decompression and are embedded in other software tools. Details: They are not full-fledged archives but raw compressed streams often used by applications. FilExt.com tip: For more technical details and specifications, refer to the official website at zlib.net. You need a suitable software like zlib to open a ZLIB file. Without proper software you will receive a Windows ...
🌐
CircuitPython
docs.circuitpython.org β€Ί en β€Ί latest β€Ί shared-bindings β€Ί zlib
zlib – zlib decompression functionality β€” Adafruit CircuitPython 1 documentation
This module allows to decompress binary data compressed with DEFLATE algorithm (commonly used in zlib library and gzip archiver). Compression is not yet implemented. ... Return decompressed data as bytes. wbits is DEFLATE dictionary window size used during compression (8-15, the dictionary ...
🌐
Narkive
nug.xojo.narkive.com β€Ί O3Xpwcab β€Ί zlib-on-windows
zLib on Windows?
I do some zip decompression using Charles zLib module. The code is Β· soft declare function zlibuncompress lib zlibPath alias "uncompress" (dest as Ptr, ByRef destLen as UInt32, source as CString, sourceLen as Uint32) as Integer ... pLastErrorCode = zlibuncompress(m, destLength, input, LenB(input)) It works fine on a Mac but on Windows (XP) it does not work due to a FunctionNotFoundException.
Top answer
1 of 3
133

To decompress a gzip format file with zlib, call inflateInit2 with the windowBits parameter as 16+MAX_WBITS, like this:

inflateInit2(&stream, 16+MAX_WBITS);

If you don't do this, zlib will complain about a bad stream format. By default, zlib creates streams with a zlib header, and on inflate does not recognise the different gzip header unless you tell it so. Although this is documented starting in version 1.2.1 of the zlib.h header file, it is not in the zlib manual. From the header file:

windowBits can also be greater than 15 for optional gzip decoding. Add 32 to windowBits to enable zlib and gzip decoding with automatic header detection, or add 16 to decode only the gzip format (the zlib format will return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is a crc32 instead of an adler32.

2 of 3
129

python

zlib library supports:

  • RFC 1950 (zlib compressed format)
  • RFC 1951 (deflate compressed format)
  • RFC 1952 (gzip compressed format)

The python zlib module will support these as well.

choosing windowBits

But zlib can decompress all those formats:

  • to (de-)compress deflate format, use wbits = -zlib.MAX_WBITS
  • to (de-)compress zlib format, use wbits = zlib.MAX_WBITS
  • to (de-)compress gzip format, use wbits = zlib.MAX_WBITS | 16

See documentation in http://www.zlib.net/manual.html#Advanced (section inflateInit2)

examples

test data:

>>> deflate_compress = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)
>>> zlib_compress = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS)
>>> gzip_compress = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)
>>> 
>>> text = '''test'''
>>> deflate_data = deflate_compress.compress(text) + deflate_compress.flush()
>>> zlib_data = zlib_compress.compress(text) + zlib_compress.flush()
>>> gzip_data = gzip_compress.compress(text) + gzip_compress.flush()
>>> 

obvious test for zlib:

>>> zlib.decompress(zlib_data)
'test'

test for deflate:

>>> zlib.decompress(deflate_data)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
zlib.error: Error -3 while decompressing data: incorrect header check
>>> zlib.decompress(deflate_data, -zlib.MAX_WBITS)
'test'

test for gzip:

>>> zlib.decompress(gzip_data)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
zlib.error: Error -3 while decompressing data: incorrect header check
>>> zlib.decompress(gzip_data, zlib.MAX_WBITS|16)
'test'

the data is also compatible with gzip module:

>>> import gzip
>>> import StringIO
>>> fio = StringIO.StringIO(gzip_data)
>>> f = gzip.GzipFile(fileobj=fio)
>>> f.read()
'test'
>>> f.close()

automatic header detection (zlib or gzip)

adding 32 to windowBits will trigger header detection

>>> zlib.decompress(gzip_data, zlib.MAX_WBITS|32)
'test'
>>> zlib.decompress(zlib_data, zlib.MAX_WBITS|32)
'test'

using gzip instead

For gzip data with gzip header you can use gzip module directly; but please remember that under the hood, gzip uses zlib.

fh = gzip.open('abc.gz', 'rb')
cdata = fh.read()
fh.close()
🌐
Hackage
hackage.haskell.org β€Ί package β€Ί zlib
zlib: Compression and decompression in the gzip and zlib formats
zlib-0.7.1.1.tar.gz [browse] (Cabal source package) ... This package provides a pure interface for compressing and decompressing streams of data represented as lazy ByteStrings. It uses the zlib C library so it has high performance.