csharp / expert
Snippet
Cryptographic Buffer Sanitization with Stack-Allocated Memory
When handling sensitive data, relying on the Garbage Collector is insufficient. Using 'stackalloc' creates a buffer on the stack, and 'buffer.Clear()' ensures that secrets are wiped from memory immediately after use, reducing the attack surface for memory dumps.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public void ProcessSecureData(ReadOnlySpan<char> sensitive){Span<byte> buffer = stackalloc byte[sensitive.Length * 2];try{// Perform cryptographic operationsSystem.Text.Encoding.UTF8.GetBytes(sensitive, buffer);PerformOperation(buffer);}finally{// Overwrite memory to prevent data leakage after method returnsbuffer.Clear();}}
Breakdown
1
stackalloc byte[...]
Allocates memory on the stack, avoiding heap tracking and GC overhead.
2
buffer.Clear()
Zeroes out the memory range to sanitize sensitive leftovers.