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.
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 {
14 panic("subtle: slices have different lengths")
19 for i
:= 0; i
< len(x
); 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 {
40 // ConstantTimeEq returns 1 if x == y and 0 otherwise.
41 func ConstantTimeEq(x
, y
int32) int {
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) {
56 ymask
:= byte(^(v
- 1))
57 for i
:= 0; i
< len(x
); i
++ {
58 x
[i
] = x
[i
]&xmask | y
[i
]&ymask
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 {
68 return int(((x32
- y32
- 1) >> 31) & 1)