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.

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top