Merge from mainline (167278:168000).
[official-gcc/graphite-test-results.git] / libgo / go / crypto / subtle / constant_time.go
bloba3d70b9c96e3e4d2237ea7738a72558e51741e4c
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.
5 // This package implements functions that are often useful in cryptographic
6 // code but require careful thought to use correctly.
7 package subtle
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 var v byte
15 for i := 0; i < len(x); i++ {
16 v |= x[i] ^ y[i]
19 return ConstantTimeByteEq(v, 0)
22 // ConstantTimeSelect returns x if v is 1 and y if v is 0.
23 // Its behavior is undefined if v takes any other value.
24 func ConstantTimeSelect(v, x, y int) int { return ^(v-1)&x | (v-1)&y }
26 // ConstantTimeByteEq returns 1 if x == y and 0 otherwise.
27 func ConstantTimeByteEq(x, y uint8) int {
28 z := ^(x ^ y)
29 z &= z >> 4
30 z &= z >> 2
31 z &= z >> 1
33 return int(z)
36 // ConstantTimeEq returns 1 if x == y and 0 otherwise.
37 func ConstantTimeEq(x, y int32) int {
38 z := ^(x ^ y)
39 z &= z >> 16
40 z &= z >> 8
41 z &= z >> 4
42 z &= z >> 2
43 z &= z >> 1
45 return int(z & 1)
48 // ConstantTimeCopy copies the contents of y into x iff v == 1. If v == 0, x is left unchanged.
49 // Its behavior is undefined if v takes any other value.
50 func ConstantTimeCopy(v int, x, y []byte) {
51 xmask := byte(v - 1)
52 ymask := byte(^(v - 1))
53 for i := 0; i < len(x); i++ {
54 x[i] = x[i]&xmask | y[i]&ymask
56 return