github.com/ader1990/go@v0.0.0-20140630135419-8c24447fa791/src/pkg/crypto/subtle/constant_time.go (about)

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package subtle implements functions that are often useful in cryptographic
     6  // code but require careful thought to use correctly.
     7  package subtle
     8  
     9  // ConstantTimeCompare returns 1 iff the two equal length slices, x
    10  // and y, have equal contents. The time taken is a function of the length of
    11  // the slices and is independent of the contents.
    12  func ConstantTimeCompare(x, y []byte) int {
    13  	if len(x) != len(y) {
    14  		panic("subtle: slices have different lengths")
    15  	}
    16  
    17  	var v byte
    18  
    19  	for i := 0; i < len(x); i++ {
    20  		v |= x[i] ^ y[i]
    21  	}
    22  
    23  	return ConstantTimeByteEq(v, 0)
    24  }
    25  
    26  // ConstantTimeSelect returns x if v is 1 and y if v is 0.
    27  // Its behavior is undefined if v takes any other value.
    28  func ConstantTimeSelect(v, x, y int) int { return ^(v-1)&x | (v-1)&y }
    29  
    30  // ConstantTimeByteEq returns 1 if x == y and 0 otherwise.
    31  func ConstantTimeByteEq(x, y uint8) int {
    32  	z := ^(x ^ y)
    33  	z &= z >> 4
    34  	z &= z >> 2
    35  	z &= z >> 1
    36  
    37  	return int(z)
    38  }
    39  
    40  // ConstantTimeEq returns 1 if x == y and 0 otherwise.
    41  func ConstantTimeEq(x, y int32) int {
    42  	z := ^(x ^ y)
    43  	z &= z >> 16
    44  	z &= z >> 8
    45  	z &= z >> 4
    46  	z &= z >> 2
    47  	z &= z >> 1
    48  
    49  	return int(z & 1)
    50  }
    51  
    52  // ConstantTimeCopy copies the contents of y into x iff v == 1. If v == 0, x is left unchanged.
    53  // Its behavior is undefined if v takes any other value.
    54  func ConstantTimeCopy(v int, x, y []byte) {
    55  	xmask := byte(v - 1)
    56  	ymask := byte(^(v - 1))
    57  	for i := 0; i < len(x); i++ {
    58  		x[i] = x[i]&xmask | y[i]&ymask
    59  	}
    60  	return
    61  }
    62  
    63  // ConstantTimeLessOrEq returns 1 if x <= y and 0 otherwise.
    64  // Its behavior is undefined if x or y are negative or > 2**31 - 1.
    65  func ConstantTimeLessOrEq(x, y int) int {
    66  	x32 := int32(x)
    67  	y32 := int32(y)
    68  	return int(((x32 - y32 - 1) >> 31) & 1)
    69  }