Fix bootstrap/PR63632
[official-gcc.git] / libgo / go / crypto / subtle / constant_time.go
blobde1a4e8c54da1a4c59d6f88b9b3e78a9fe68f44e
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 // Package subtle 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 if len(x) != len(y) {
14 panic("subtle: slices have different lengths")
17 var v byte
19 for i := 0; i < len(x); i++ {
20 v |= x[i] ^ y[i]
23 return ConstantTimeByteEq(v, 0)
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 }
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
37 return int(z)
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
49 return int(z & 1)
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
60 return
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)