You have a task
Each guide is one situation: the usual code, what it leaves behind, the fix and a checklist.
using block overwrites it with zeros. A drawing of the mechanism, not a trace of a real process.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.
dotnet add package NCode.BuffersYou have a task
Each guide is one situation: the usual code, what it leaves behind, the fix and a checklist.
You are evaluating it
What it protects and what it does not, and the test behind each claim.
You have not thought about this before
What the garbage collector, array pools and strings do to a secret, in pictures.
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.
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
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
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
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
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.
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.
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.
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.
With NCode.Buffers
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
Both versions are tests in the repository. They compile and pass on every pull request, and this page copies them from there. SiteHowSecretsLeakUsual QuickStart_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
Dispose, including the part beyond the length you asked for.
R1
isSensitive has no default value.
PublicAPI.Shipped.txt:96–103
It does not
string, a ToArray() result, a buffer rented with isSensitive: false.
SiteCopiesAreNotCleared
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.
SECURITY.md lists the checks you can run on a package you downloaded. R7Sequence<T> the pooled buffer writers return.
NCode.Buffers.csproj
ZeroMemory and FixedTimeEquals for spans of any unmanaged type.