| 1 |
// Copyright 2025 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 constanttime |
| 6 |
|
| 7 |
// The functions in this package are compiler intrinsics for constant-time |
| 8 |
// operations. They are exposed by crypto/subtle and used directly by the |
| 9 |
// FIPS 140-3 module. |
| 10 |
|
| 11 |
// Select returns x if v == 1 and y if v == 0. |
| 12 |
// Its behavior is undefined if v takes any other value. |
| 13 |
func Select(v, x, y int) int { |
| 14 |
// This is intrinsicified on arches with CMOV. |
| 15 |
// It implements the following superset behavior: |
| 16 |
// ConstantTimeSelect returns x if v != 0 and y if v == 0. |
| 17 |
// Do the same here to avoid non portable UB. |
| 18 |
v = int(boolToUint8(v != 0)) |
| 19 |
return ^(v-1)&x | (v-1)&y |
| 20 |
} |
| 21 |
|
| 22 |
// ByteEq returns 1 if x == y and 0 otherwise. |
| 23 |
func ByteEq(x, y uint8) int { |
| 24 |
return int(boolToUint8(x == y)) |
| 25 |
} |
| 26 |
|
| 27 |
// Eq returns 1 if x == y and 0 otherwise. |
| 28 |
func Eq(x, y int32) int { |
| 29 |
return int(boolToUint8(x == y)) |
| 30 |
} |
| 31 |
|
| 32 |
// LessOrEq returns 1 if x <= y and 0 otherwise. |
| 33 |
// Its behavior is undefined if x or y are negative or > 2**31 - 1. |
| 34 |
func LessOrEq(x, y int) int { |
| 35 |
return int(boolToUint8(x <= y)) |
| 36 |
} |
| 37 |
|
| 38 |
// boolToUint8 is a compiler intrinsic. |
| 39 |
// It returns 1 for true and 0 for false. |
| 40 |
func boolToUint8(b bool) uint8 { |
| 41 |
panic("unreachable; must be intrinsicified") |
| 42 |
} |