Golang crypto/subtle.ConstantTimeCompare() function example

package crypto/subtle

ConstantTimeCompare returns 1 iff the two equal length slices, x(1st param) and y(2nd param), have equal contents. The time taken is a function of the length of the slices and is independent of the contents.

Golang crypto/subtle.ConstantTimeCompare() function usage example

 package main

 import (
 "crypto/subtle"
 "fmt"
 )

 func main() {
  X := []byte("Hello")
  Y := []byte("World")
  Z := []byte("Hello")

  n := subtle.ConstantTimeCompare(X,Y) // X != Y, n = 0
  fmt.Printf("n : %d\n", n)


  nn := subtle.ConstantTimeCompare(X,Z) // X == Z, nn = 1

  fmt.Printf("nn : %d\n", nn)
 }

Output :

n : 0

nn : 1

Reference :

http://golang.org/pkg/crypto/subtle/#ConstantTimeCompare

Advertisement