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.
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 {
15 for i
:= 0; i
< len(x
); 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 {
36 // ConstantTimeEq returns 1 if x == y and 0 otherwise.
37 func ConstantTimeEq(x
, y
int32) int {
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) {
52 ymask
:= byte(^(v
- 1))
53 for i
:= 0; i
< len(x
); i
++ {
54 x
[i
] = x
[i
]&xmask | y
[i
]&ymask