Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell if a byte array is gzipped

How can I see if a byte array contains a gzip stream? My application gets files from other applications through http post with Base64 encoding. Depending on the implementation of the application that delivers the files, the byte array that comes out of the Base64 string can be gzipped. How can I recognize the gzipped arrays? I have found some method, but I think that it will go wrong when someone uploads a zip file or prepared "bad" zip file

This is what I found and works, but can it be exploited in some way?

C#

public static bool IsGZip(byte[] arr)
{
    return arr.Length >= 2 && arr[0] == 31 && arr[1] == 139;
}

VB.NET

Public Shared Function IsGZip(arr As Byte()) As Boolean
    Return arr.Length >= 2 AndAlso arr(0) = 31 AndAlso arr(1) = 139
End Function

If the IsGzip returns true my application will decompress the byte array.

like image 830
Kees de Wit Avatar asked Oct 14 '13 16:10

Kees de Wit


1 Answers

Do what you're doing, check that the third byte is 8, and then try to gunzip it. That final step is the only way to really know. If the gunzip fails, then use the stream as is.

like image 69
Mark Adler Avatar answered Oct 25 '22 07:10

Mark Adler