Recursive AI

Decompress CMS CompressedData from a stream in C#

OneCrypto is a free, open-source cryptography library for .NET from Recursive AI. MIT or Apache-2.0, preview, no native dependencies.

Use DecompressStream, but write to a temporary destination: the decoder may write partial output before it fails.

Terminal
dotnet add package RecursiveAI.OneCrypto

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

C#
using RecursiveAI.OneCrypto;
using RecursiveAI.OneCrypto.Wire.Cms;
using System.Text;
 
var cms = CompressedData.Create("Hello!"u8);
using var input = new MemoryStream(
    cms.Encoded.ToArray());
using var pending = new MemoryStream();
var caps = new CmsLimits
{ MaxDecompressedBytes = 20_000 };
CompressedData.DecompressStream(
    input, pending, caps);
Console.WriteLine(Encoding.UTF8.GetString(
    pending.ToArray()));

The example is the full program below: unzip it and dotnet run. To run only the code above, paste it into Program.cs of a new dotnet new console project and dotnet run.

Text
Hello!

The full program

The first message contains the text Hello!; the second contains 40,000 zero bytes so it exceeds the 20,000-byte cap. Both CMS inputs are generated in memory.

C#
using RecursiveAI.OneCrypto;
using RecursiveAI.OneCrypto.Wire.Cms;
using System.Text;
 
var cms = CompressedData.Create("Hello!"u8);
using var input = new MemoryStream(
    cms.Encoded.ToArray());
using var pending = new MemoryStream();
var caps = new CmsLimits
{ MaxDecompressedBytes = 20_000 };
CompressedData.DecompressStream(
    input, pending, caps);
Console.WriteLine(Encoding.UTF8.GetString(
    pending.ToArray()));
 
// The decoder will write some bytes before reaching the cap.
var larger = CompressedData.Create(new byte[40_000]);
using var largerInput = new MemoryStream(larger.Encoded.ToArray());
using var rejected = new MemoryStream();
try
{
    CompressedData.DecompressStream(largerInput, rejected, caps);
}
catch (CmsParseException error)
{
    Console.WriteLine($"Discarding {rejected.Length} bytes: {error.Error}");
    rejected.SetLength(0);
}

dotnet run prints:

Text
Hello!
Discarding 16384 bytes: LimitExceeded

The decoder can throw CmsParseException after writing to the destination, so discard the staged bytes on failure rather than handing them to a consumer.

Variations

Read a CMS file. Replace the sample cms and input declarations with this line. message.p7z is your encoded CMS CompressedData file.

C#
using var input = File.OpenRead("message.p7z");

Use async streams. Replace the call with the asynchronous form so reads and writes can be awaited. Pass a CancellationToken as the fourth argument if the caller can cancel; discard staged bytes on cancellation too.

C#
await CompressedData.DecompressStreamAsync(
    input, pending, caps);

The short answer

Use CompressedData.DecompressStream(message, destination, limits) from RecursiveAI.OneCrypto. Give it the stream containing the outer CMS ContentInfo, not just the inner zlib bytes. Set a cap suitable for the expected payload, write to an isolated destination, and commit that destination only when the call returns successfully.

What is CMS CompressedData?

RFC 3274 defines a CMS content type for compressed data. The outer ContentInfo identifies the message type, and the compressed-data structure identifies the compression algorithm and carries the compressed bytes. OneCrypto’s streaming reader expects this envelope with zlib content. It can read a forward-only stream and doesn’t need to know the total length in advance.

This isn’t a ZIP archive: the operation returns the encapsulated content bytes, not named files. It also doesn’t authenticate the sender. The CMS docs describe the zlib end check; it’s an integrity check for the compressed stream, not a signature.

How do you limit the output size when decompressing a stream in C#?

CmsLimits.MaxDecompressedBytes is the absolute output cap. The ratio guard uses MaxDecompressionRatio times the compressed bytes read so far, with a 4 KiB floor on that ratio allowance; it still obeys the absolute cap. The defaults are 1 GiB and 1032 respectively. Choose a smaller absolute cap if you expect a small message. Streaming avoids keeping the whole decoded message in the library, but a MemoryStream destination still holds the bytes your application writes into it.

For a large destination, use a temporary file rather than writing to the final path. Close it and move it into place only after success; delete it on failure or cancellation. A socket or HTTP response is harder to stage: once a byte is sent, it can’t be taken back. The zlib end check runs after inflation, so even a stream that produced plausible bytes can fail at the end. Don’t send these bytes directly to a reader that assumes the operation has already succeeded.

All onecrypto recipes