Last Updated: February 25, 2016
·
2.683K
· alfeg

Decompressing SWF files in C#

Here is a c# version of SWF decompressing I've used for SWF verification

private byte[] SwfDecompress(byte[] data, out size)
{
    var stream = new MemoryStream(data);

    var first = stream.ReadByte();
    if (first != 0x43) // C
    {
        throw new ArgumentException("Not compressed", "data");
    }

    if (stream.ReadByte() != 0x57) // W
    {
        throw new ArgumentException("Not SWF", "data");
    }

    if (stream.ReadByte() != 0x53) // S
    {
        throw new ArgumentException("Not SWF", "data");
    }

    var version = (byte) stream.ReadByte();
    var integer = new byte[4];
    integer[0] = (byte) stream.ReadByte();
    integer[1] = (byte) stream.ReadByte();
    integer[2] = (byte) stream.ReadByte();
    integer[3] = (byte) stream.ReadByte();

    size = BitConverter.ToInt32(integer, 0);
    var outStream = new MemoryStream();

    outStream.WriteByte(0x46);
    outStream.WriteByte(0x57);
    outStream.WriteByte(0x53);
    outStream.WriteByte(version);
    outStream.Write(integer, 0, 4);

    var uncompressedInput = new Ionic.Zlib.ZlibStream(stream, CompressionMode.Decompress);
    byte[] buffer = new byte[4096];
    int read;
    while ((read = uncompressedInput.Read(buffer, 0, buffer.Length)) > 0)
    {
        outStream.Write(buffer, 0, read);
    }

    outStream.Seek(0, SeekOrigin.Begin);
    return outStream.ToArray();
}

For stream ZLIB decompression DotNetZip.

For implementation details look over here: http://wwwimages.adobe.com/www.adobe.com/content/dam/Adobe/en/devnet/swf/pdf/swf-file-format-spec.pdf

0x43, 0x57, 0x53 (“CWS”).A CWS indicates that the entire file after the first 8 bytes (that is,
after the FileLength field) was compressed by using the ZLIB open standard. The data format
that the ZLIB library uses is described by Request for Comments (RFCs) documents 1950 to
1952. CWS file compression is permitted in SWF 6 or later only