csharp / expert
Snippet
Zeroing Sensitive Memory via Spans
For high-security applications, leaving sensitive data like passwords in memory is risky. Using 'stackalloc' with 'Span<T>.Clear()' ensures that the memory is overwritten with zeros immediately after use, reducing the window for memory scraping attacks.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
public unsafe void HandleSecret(){Span<byte> secretBuffer = stackalloc byte[32];try{// Perform cryptographic operations here}finally{secretBuffer.Clear(); // Explicitly overwrites memory with zeros}}
Breakdown
1
stackalloc byte[32]
Allocates memory on the stack, which is faster and doesn't trigger GC overhead.
2
secretBuffer.Clear()
A performance-optimized way to fill the entire span with the default value (zero).