go / expert
Snippet
Mitigating Timing Side-Channel Leakage using subtle.ConstantTimeCompare
Standard byte or string comparisons in Go short-circuit on the first mismatched byte, creating variable execution time vulnerabilities susceptible to timing side-channel attacks. Using crypto/subtle.ConstantTimeCompare evaluates every byte regardless of early mismatches, executing in constant time to safely compare sensitive secrets such as API keys and cryptographic signatures.
snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package mainimport ("crypto/subtle""errors")var ErrInvalidToken = errors.New("authentication token mismatch")func VerifyAuthToken(expected, provided []byte) error {if len(expected) == 0 || len(provided) == 0 {return ErrInvalidToken}if subtle.ConstantTimeCompare(expected, provided) != 1 {return ErrInvalidToken}return nil}
Breakdown
1
if len(expected) == 0 || len(provided) == 0 {
Guards against empty input slices prior to executing constant-time checks.
2
if subtle.ConstantTimeCompare(expected, provided) != 1 {
Compares slice bytes in constant time, returning 1 if equal and 0 otherwise without early return leakage.