Skip to content
The quick start's key, on the stack, as the end of its using block overwrites it with zeros. A drawing of the mechanism, not a trace of a real process.

A secret should not outlive its use.

Put a key in an ordinary array and the runtime treats it like any other data. The garbage collector can copy it to a new address and leave the old bytes behind, and nothing clears it when your method returns. NCode.Buffers gives you buffers the collector does not move, overwritten with zeros when you dispose them.

It does not lock memory into RAM, and it cannot hide memory from a debugger or a crash dump.

Terminal window
dotnet add package NCode.Buffers

NuGet version CI Coverage Target framework OpenSSF Scorecard OpenSSF Best Practices License

You have a task

Each guide is one situation: the usual code, what it leaves behind, the fix and a checklist.

Find your situation

The same 32-byte key, held in an ordinary array and in a buffer from Rent with isSensitive: true, at three moments of its life. How secrets leak steps through all six.

The life of a key

The same 32-byte key, drawn as eight cells, held in an ordinary array and in a buffer from Rent with isSensitive: true, step by step.

  • The key
  • An old copy
  • Zeros
  • Not written yet
  • Other data
  1. 3A collection compacts the heap

    An ordinary arraybyte[] key = new byte[32]

    Places this key can be read2

    The collector copies the array to a new address. The old cells keep the key until something is written over them.L1: The collector moves arrays

    A buffer from RentRent(32, isSensitive: true, out Span<byte> key)

    Places this key can be read1

    Other objects move. The pinned buffer does not, so the key is still in one place.R3: Not moved by the collector

  2. 4Your code copies it

    An ordinary arraybyte[] key = new byte[32]

    Places this key can be read3

    ToArray(), or a string of the key, makes one more place that holds it.L9: Copies are on their own

    A buffer from RentRent(32, isSensitive: true, out Span<byte> key)

    Places this key can be read1

    The same copy here would be ordinary memory again: the library cannot reach it. This code makes none.L9: Copies are on their own

  3. 5You are done with it

    An ordinary arraybyte[] key = new byte[32]

    Places this key can be read3

    The method returns. Nothing clears the array, its old cells or the copy.L2: Freed is not erased

    A buffer from RentRent(32, isSensitive: true, out Span<byte> key)

    Places this key can be read0

    Dispose overwrites the whole buffer with zeros, the part after the key included, on every way out of the using block.R1: Zeroed on disposeL6: An exception skips your cleanup

IllustrationA drawing of the mechanism, not a trace of a real process.

Verify a signature with a key derived from a password. First the usual way, then with NCode.Buffers.

The usual code

Signatures.cs
public static bool VerifySignature(
byte[] password,
byte[] salt,
byte[] payload,
byte[] signature
)
{
byte[] key = Rfc2898DeriveBytes.Pbkdf2(
password,
salt,
600_000,
HashAlgorithmName.SHA256,
32
);
byte[] expected = HMACSHA256.HashData(key, payload);
return expected.AsSpan().SequenceEqual(signature);
}

Leaves behind

  1. The key, in an ordinary array. The collector can move it, and nothing clears it.
    L1The collector moves arraysPrevents

    A collection can compact the heap: it copies the objects still in use to new addresses, an array that holds a key among them. Microsoft's page on SecureString says that, because a string's memory is not pinned, the collector "will make additional copies" of it when it moves and compacts memory. Which objects move, and when, is the collector's decision.

    NCode.Buffers. For the buffers it allocates: they are pinned, and the collector does not move them. Stack memory does not move either. It does not help with heap memory you already had.

    All nine ways a secret leaks
    L2Freed is not erasedReduces

    When nothing references an array any more, the collector takes its memory back without overwriting it, and nothing clears an array when your method returns. A crash dump or a page file can hold those bytes until the memory is used again, and an allocation that skips zeroing, as GC.AllocateUninitializedArray does, can be handed them as they are.

    NCode.Buffers. Dispose overwrites the buffer with zeros before the memory is let go. It does nothing for a buffer you never dispose, and a new buffer is not cleared for you: write before you read.

    All nine ways a secret leaks
  2. The expected MAC, the same way. Whoever reads it can forge this message.
    L2Freed is not erasedReduces

    When nothing references an array any more, the collector takes its memory back without overwriting it, and nothing clears an array when your method returns. A crash dump or a page file can hold those bytes until the memory is used again, and an allocation that skips zeroing, as GC.AllocateUninitializedArray does, can be handed them as they are.

    NCode.Buffers. Dispose overwrites the buffer with zeros before the memory is let go. It does nothing for a buffer you never dispose, and a new buffer is not cleared for you: write before you read.

    All nine ways a secret leaks
  3. A comparison that stops at the first wrong byte.
    L7An early exit tells timePrevents

    A comparison that stops at the first difference, such as ==, SequenceEqual or a loop of your own, returns sooner the earlier two values differ. Someone who can send many guesses and time the answers can learn an expected MAC one byte at a time.

    NCode.Buffers. For values of the same length: FixedTimeEquals calls .NET's fixed-time comparison. The length still shows.

    All nine ways a secret leaks

With NCode.Buffers

Signatures.cs
using System.Security.Cryptography;
using NCode.Buffers;
public static class Signatures
{
public static bool VerifySignature(
ReadOnlySpan<byte> password,
ReadOnlySpan<byte> salt,
ReadOnlySpan<byte> payload,
ReadOnlySpan<byte> signature
)
{
// A pinned, pooled 32-byte key, zeroed when keyOwner is disposed.
using var keyOwner = BufferFactory.Rent(32, isSensitive: true, out Span<byte> key);
Rfc2898DeriveBytes.Pbkdf2(
password,
salt,
key,
iterations: 600_000,
HashAlgorithmName.SHA256
);
// The expected MAC lives on the stack and is zeroed when expectedLifetime is disposed.
Span<byte> expected = stackalloc byte[HMACSHA256.HashSizeInBytes];
using var expectedLifetime = expected.GetSecureLifetime();
HMACSHA256.HashData(key, payload, expected);
// Constant time, so the comparison doesn't reveal where the MACs differ.
return CryptographicOperations.FixedTimeEquals(expected, signature);
}
}

What changed

  1. The key is written into a pinned buffer and zeroed when keyOwner is disposed, on every exit. AssertedR3 AssertedR1
  2. The expected MAC is on the stack and zeroed when expectedLifetime is disposed. AssertedR1
  3. The comparison takes the same time wherever the MACs differ, for MACs of the same length. By constructionR4

Both versions are tests in the repository. They compile and pass on every pull request, and this page copies them from there. AssertedSiteHowSecretsLeakUsual AssertedQuickStart_ValidSignature_ReturnsTrue The Quick start reads the second one line by line; Derive a key from a password and Verify a MAC without leaking timing take each half further.

It does

  • Allocate buffers for secrets on the pinned object heap. The collector does not move them, so no copy is left at an old address. AssertedR3
  • Overwrite the whole buffer with zeros in Dispose, including the part beyond the length you asked for. AssertedR1
  • Zero a pooled buffer before another caller can rent it. AssertedR2
  • Make you say whether a pooled buffer holds a secret: isSensitive has no default value. By constructionPublicAPI.Shipped.txt:96–103
  • Compare spans of any unmanaged type in time that does not depend on their contents, for equal lengths. By constructionR4
  • Reject malformed UTF-8 and ASCII with an exception instead of substituting characters. AssertedR5
  • Refuse, at compile time, element types that hold references the zeroing would miss. By constructionR8

It does not

If an attacker can read your process’s memory while a secret is in use, no managed library changes that. This one reduces how many copies of a secret exist and how long they last. What it protects, and what it does not draws the line in full, and Guarantees and their tests lists each claim with the tests behind it and what they do not show.

Each guide is one situation.

Not sure which type you need? Which buffer? asks at most four questions.

  • Tests. Each claim under “It does” names the test, or the line of code, that makes it true. Guarantees and their tests
  • Samples. Every C# sample on this site that compiles is a test in the repository, the usual code included. A sample that stops compiling or passing fails the build. Code shown as not compiling is marked so, with the compiler’s error. A processADR-1010
  • Coverage. The build fails under 98% line or branch coverage. A processTest-Coverage.ps1:31–32
  • Analysis. Warnings are errors. The library’s own code cannot call a lenient text encoding or rent from a pool without saying whether the buffer holds a secret: an analyzer rejects both. A processProjectTemplate.props:8–9 A processBannedSymbols.Encoding.txt A processBannedSymbols.Buffers.txt
  • Releases. A package is built in CI from a tagged commit and pushed to nuget.org through trusted publishing after a maintainer approves. SECURITY.md lists the checks you can run on a package you downloaded. A processR7
  • Decisions. The reasons behind the design are on record, one short file each, in docs/decisions.