Quick start
This page derives a key from a password, verifies an HMAC-SHA256 signature with it, and zeroes the derived key and the expected MAC when the method returns.
Install
dotnet add package NCode.Buffers
Verify a signature
BufferFactory.Rent hands back a pinned, pooled buffer and an owner. Disposing the owner zeroes the whole buffer, so the key never outlives the method.
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);
}
The brace spans the lifetime of key: from the line that rents it to the brace that ends the method, where it is zeroed.
What happens: the key and the expected MAC are zeroed when the method exits, by return or by a thrown exception.
Choosing a buffer
| API | Use it when | Pooled |
|---|---|---|
Rent |
You need a temporary buffer for a key, password or other secret | PooledYes |
CreatePooledBufferWriter |
You write a secret whose length you don't know up front | PooledYes |
CreatePinnedArray |
An API needs a T[], within one synchronous scope |
PooledNo |
GetSecureLifetime |
You already have the memory, usually stackalloc |
PooledNo |