Constant-Time Secret Comparison

Compare API tokens without leaking length or prefix through timing by hashing both sides to fixed size and using subtle.

GoSecurity Boundaries

Code

gosnippet
21 lines
package main

import (
	"crypto/sha256"
	"crypto/subtle"
	"fmt"
)

func ConstantTimeEqual(a, b string) bool {
	left := sha256.Sum256([]byte(a))
	right := sha256.Sum256([]byte(b))
	return subtle.ConstantTimeCompare(left[:], right[:]) == 1
}

func main() {
	secret := "s3cr3t-token"
	fmt.Println(ConstantTimeEqual(secret, "s3cr3t-token"))
	fmt.Println(ConstantTimeEqual(secret, "s3cr3t-tokeX"))
	fmt.Println(ConstantTimeEqual(secret, "short"))
}

What the code does

Count the functions ConstantTimeEqual and main as the entire surface area of Constant-Time Secret Comparison.

Caveats

  • There is no dependency tree here — the platform is the whole dependency.

Applying it

Entry signature: func ConstantTimeEqual(a, b string) bool

Launch the file; main takes over and steps through ConstantTimeEqual.

Statements that matter most here

func ConstantTimeEqual(a, b string) bool {
left := sha256.Sum256([]byte(a))
right := sha256.Sum256([]byte(b))
return subtle.ConstantTimeCompare(left[:], right[:]) == 1
}
func main() {
secret := "s3cr3t-token"
fmt.Println(ConstantTimeEqual(secret, "s3cr3t-token"))
fmt.Println(ConstantTimeEqual(secret, "s3cr3t-tokeX"))
fmt.Println(ConstantTimeEqual(secret, "short"))
}

Interactive Tools for This Topic

FAQ

How do you run Constant-Time Secret Comparison?
This is a complete program, not a library excerpt — execution starts at the top.