Zlib-compatible compression streams?

Ben Collins picture Ben Collins · Sep 16, 2008 · Viewed 21k times · Source

Are System.IO.Compression.GZipStream or System.IO.Compression.Deflate compatible with zlib compression?

Answer

Blake Ramsdell picture Blake Ramsdell · Feb 25, 2010

I ran into this issue with Git objects. In that particular case, they store the objects as deflated blobs with a Zlib header, which is documented in RFC 1950. You can make a compatible blob by making a file that contains:

  • Two header bytes (CMF and FLG from RFC 1950) with the values 0x78 0x01
    • CM = 8 = deflate
    • CINFO = 7 = 32Kb window
    • FCHECK = 1 = checksum bits for this header
  • The output of the C# DeflateStream
  • An Adler32 checksum of the input data to the DeflateStream, big-endian format (MSB first)

I made my own Adler implementation

public class Adler32Computer
{
    private int a = 1;
    private int b = 0;

    public int Checksum
    {
        get
        {
            return ((b * 65536) + a);
        }
    }

    private static readonly int Modulus = 65521;

    public void Update(byte[] data, int offset, int length)
    {
        for (int counter = 0; counter < length; ++counter)
        {
            a = (a + (data[offset + counter])) % Modulus;
            b = (b + a) % Modulus;
        }
    }
}

And that was pretty much it.