go / expert
Snippet
Constant-Time Cryptographic Comparison and Sensitive Memory Sanitization
Timing side-channel attacks exploit execution duration differences during byte comparisons. crypto/subtle.ConstantTimeCompare executes in constant time regardless of where byte mismatches occur. Explicit memory zeroing prevents secrets from persisting in memory prior to garbage collection.
snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package mainimport ("crypto/subtle")type SecureKey struct {secret []byte}func NewSecureKey(data []byte) *SecureKey {k := &SecureKey{secret: make([]byte, len(data))}copy(k.secret, data)return k}func (k *SecureKey) Verify(expected []byte) bool {if len(k.secret) != len(expected) {return false}return subtle.ConstantTimeCompare(k.secret, expected) == 1}func (k *SecureKey) Destroy() {for i := range k.secret {k.secret[i] = 0}}
Breakdown
1
return subtle.ConstantTimeCompare(k.secret, expected) == 1
Compares byte slices in execution time independent of input content to prevent side-channel timing leaks.
2
for i := range k.secret { k.secret[i] = 0 }
Zeroes out memory buffer contents explicitly to minimize lifetime exposure of key material.