Home | History | Annotate | Download | only in subtle
      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 if and only if the two 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 		return 0
     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 (a slice of equal length)
     53 // if v == 1. If v == 0, x is left unchanged. Its behavior is undefined if v
     54 // takes any other value.
     55 func ConstantTimeCopy(v int, x, y []byte) {
     56 	if len(x) != len(y) {
     57 		panic("subtle: slices have different lengths")
     58 	}
     59 
     60 	xmask := byte(v - 1)
     61 	ymask := byte(^(v - 1))
     62 	for i := 0; i < len(x); i++ {
     63 		x[i] = x[i]&xmask | y[i]&ymask
     64 	}
     65 }
     66 
     67 // ConstantTimeLessOrEq returns 1 if x <= y and 0 otherwise.
     68 // Its behavior is undefined if x or y are negative or > 2**31 - 1.
     69 func ConstantTimeLessOrEq(x, y int) int {
     70 	x32 := int32(x)
     71 	y32 := int32(y)
     72 	return int(((x32 - y32 - 1) >> 31) & 1)
     73 }
     74