Fix bootstrap/PR63632
[official-gcc.git] / libgo / go / crypto / subtle / constant_time_test.go
blobd8e321ec04a7f8294efd62fb26086424b66814cd
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
7 import (
8 "testing"
9 "testing/quick"
12 type TestConstantTimeCompareStruct struct {
13 a, b []byte
14 out int
17 var testConstantTimeCompareData = []TestConstantTimeCompareStruct{
18 {[]byte{}, []byte{}, 1},
19 {[]byte{0x11}, []byte{0x11}, 1},
20 {[]byte{0x12}, []byte{0x11}, 0},
23 func TestConstantTimeCompare(t *testing.T) {
24 for i, test := range testConstantTimeCompareData {
25 if r := ConstantTimeCompare(test.a, test.b); r != test.out {
26 t.Errorf("#%d bad result (got %x, want %x)", i, r, test.out)
31 type TestConstantTimeByteEqStruct struct {
32 a, b uint8
33 out int
36 var testConstandTimeByteEqData = []TestConstantTimeByteEqStruct{
37 {0, 0, 1},
38 {0, 1, 0},
39 {1, 0, 0},
40 {0xff, 0xff, 1},
41 {0xff, 0xfe, 0},
44 func byteEq(a, b uint8) int {
45 if a == b {
46 return 1
48 return 0
51 func TestConstantTimeByteEq(t *testing.T) {
52 for i, test := range testConstandTimeByteEqData {
53 if r := ConstantTimeByteEq(test.a, test.b); r != test.out {
54 t.Errorf("#%d bad result (got %x, want %x)", i, r, test.out)
57 err := quick.CheckEqual(ConstantTimeByteEq, byteEq, nil)
58 if err != nil {
59 t.Error(err)
63 func eq(a, b int32) int {
64 if a == b {
65 return 1
67 return 0
70 func TestConstantTimeEq(t *testing.T) {
71 err := quick.CheckEqual(ConstantTimeEq, eq, nil)
72 if err != nil {
73 t.Error(err)
77 func makeCopy(v int, x, y []byte) []byte {
78 if len(x) > len(y) {
79 x = x[0:len(y)]
80 } else {
81 y = y[0:len(x)]
83 if v == 1 {
84 copy(x, y)
86 return x
89 func constantTimeCopyWrapper(v int, x, y []byte) []byte {
90 if len(x) > len(y) {
91 x = x[0:len(y)]
92 } else {
93 y = y[0:len(x)]
95 v &= 1
96 ConstantTimeCopy(v, x, y)
97 return x
100 func TestConstantTimeCopy(t *testing.T) {
101 err := quick.CheckEqual(constantTimeCopyWrapper, makeCopy, nil)
102 if err != nil {
103 t.Error(err)
107 var lessOrEqTests = []struct {
108 x, y, result int
110 {0, 0, 1},
111 {1, 0, 0},
112 {0, 1, 1},
113 {10, 20, 1},
114 {20, 10, 0},
115 {10, 10, 1},
118 func TestConstantTimeLessOrEq(t *testing.T) {
119 for i, test := range lessOrEqTests {
120 result := ConstantTimeLessOrEq(test.x, test.y)
121 if result != test.result {
122 t.Errorf("#%d: %d <= %d gave %d, expected %d", i, test.x, test.y, result, test.result)