1

How can you decompress a string of text in Python 3, that has been compressed with gzip and converted to base 64?

For example, the text:

EgAAAB+LCAAAAAAABAALycgsVgCi4vzcVAWFktSKEgC9n1/fEgAAAA==

Should convert to:

This is some text

The following C# code successfully does this:

var gzBuffer = Convert.FromBase64String(compressedText);

using (var ms = new MemoryStream()) {
    int msgLength = BitConverter.ToInt32(gzBuffer, 0);
    ms.Write(gzBuffer, 4, gzBuffer.Length - 4);

    var buffer = new byte[msgLength];

    ms.Position = 0;
    using (var zip = new GZipStream(ms, CompressionMode.Decompress)) {
        zip.Read(buffer, 0, buffer.Length);
    }

    return Encoding.UTF8.GetString(buffer);
}
Gilles-Antoine Nys
  • 1,481
  • 16
  • 21
Geoff Smith
  • 585
  • 1
  • 5
  • 14
  • Thanks. Whenever I use base64 and then zlib.decompress I am getting Error -3 while decompressing data: incorrect header check – Geoff Smith Sep 24 '18 at 12:13
  • Rad about [module-base64](https://docs.python.org/3/library/base64.html#module-base64) and [module-gzip](https://docs.python.org/3/library/gzip.html#module-gzip) – stovfl Sep 24 '18 at 12:23

1 Answers1

2

You can use the gzip and base64 modules.

>>> import gzip
>>> import base64

>>> s = 'EgAAAB+LCAAAAAAABAALycgsVgCi4vzcVAWFktSKEgC9n1/fEgAAAA=='
>>> gz = base64.b64decode(s)
>>> gz
b'\x12\x00\x00\x00\x1f\x8b\x08\x00\x00\x00\x00\x00\x04\x00\x0b\xc9\xc8,V\x00\xa2\xe2\xfc\xdcT\x05\x85\x92\xd4\x8a\x12\x00\xbd\x9f_\xdf\x12\x00\x00\x00'

# If you need the length
import struct
# Unpacks binary encoded 4 byte integer (assume native byte order)
# Only select first four bytes with [:4] slice
>>> struct.unpack('i', gz[:4])[0]
18

# Skip length value with [4:] slice
>>> gzip.decompress(gz[4:]).decode('UTF8')
'This is some  text'
AlphaBeta
  • 320
  • 1
  • 4
  • 13