go / intermediate
Snippet
Mitigating Timing Attacks with Constant-Time Comparisons
A timing attack allows an attacker to guess secrets (like API keys or password hashes) by measuring how long a comparison takes. Standard string comparisons (==) exit early on the first mismatched character, meaning strings that match at the beginning take longer to compare. Go's crypto/subtle package provides ConstantTimeCompare, which runs in constant time relative to the slice length, ensuring no timing side-channel leaks information.
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
package mainimport ("crypto/subtle""fmt")func verifySecret(inputToken, actualToken string) bool {inputBytes := []byte(inputToken)actualBytes := []byte(actualToken)if subtle.ConstantTimeCompare(inputBytes, actualBytes) == 1 {return true}return false}func main() {secret := "super-secure-token-123"input := "super-secure-token-123"isValid := verifySecret(input, secret)fmt.Println("Verification successful:", isValid)}
Breakdown
1
inputBytes := []byte(inputToken)
Converts the input string to a byte slice, as the subtle comparison function requires byte slices.
2
subtle.ConstantTimeCompare(inputBytes, actualBytes)
Compares the two byte slices. It iterates through all elements and returns 1 if they are identical, or 0 otherwise, without short-circuiting on mismatch.
3
if ... == 1
Checks if the return value is 1, indicating a successful match of the credentials.