go / intermediate
Snippet
Constant-Time Comparison to Prevent Timing Attacks in Security Checks
Standard byte comparisons return false as soon as they find a mismatch, creating variations in response times that attackers can measure to guess secrets. The `crypto/subtle` package provides `ConstantTimeCompare`, which always takes the same amount of time to run regardless of content, mitigating timing attacks.
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
package mainimport ("crypto/subtle""fmt")func verifySecret(inputToken, expectedToken []byte) bool {if len(inputToken) != len(expectedToken) {return false}return subtle.ConstantTimeCompare(inputToken, expectedToken) == 1}func main() {tokenA := []byte("secureToken123")tokenB := []byte("secureToken123")tokenC := []byte("wrongTokenXYZ")fmt.Println("Match A/B:", verifySecret(tokenA, tokenB))fmt.Println("Match A/C:", verifySecret(tokenA, tokenC))}
Breakdown
1
if len(inputToken) != len(expectedToken) {
Performs a quick length check first, ensuring we operate on identical sizes for the safe comparison.
2
return subtle.ConstantTimeCompare(inputToken, expectedToken) == 1
Compares slices in constant time. It returns 1 if they are identical, and 0 otherwise.