Debian Codegraph @

external/boringssl/ssl/test/runner/poly1305/poly1305_test.go

raw
1 // Copyright 2012 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 poly1305
6
7 import (
8 "bytes"
9 "testing"
10 "unsafe"
11 )
12
13 var testData = []struct {
14 in, k, correct []byte
15 }{
16 {
17 []byte("Hello world!"),
18 []byte("this is 32-byte key for Poly1305"),
19 []byte{0xa6, 0xf7, 0x45, 0x00, 0x8f, 0x81, 0xc9, 0x16, 0xa2, 0x0d, 0xcc, 0x74, 0xee, 0xf2, 0xb2, 0xf0},
20 },
21 {
22 make([]byte, 32),
23 []byte("this is 32-byte key for Poly1305"),
24 []byte{0x49, 0xec, 0x78, 0x09, 0x0e, 0x48, 0x1e, 0xc6, 0xc2, 0x6b, 0x33, 0xb9, 0x1c, 0xcc, 0x03, 0x07},
25 },
26 {
27 make([]byte, 2007),
28 []byte("this is 32-byte key for Poly1305"),
29 []byte{0xda, 0x84, 0xbc, 0xab, 0x02, 0x67, 0x6c, 0x38, 0xcd, 0xb0, 0x15, 0x60, 0x42, 0x74, 0xc2, 0xaa},
30 },
31 {
32 make([]byte, 2007),
33 make([]byte, 32),
34 make([]byte, 16),
35 },
36 }
37
38 func testSum(t *testing.T, unaligned bool) {
39 var out [16]byte
40 var key [32]byte
41
42 for i, v := range testData {
43 in := v.in
44 if unaligned {
45 in = unalignBytes(in)
46 }
47 copy(key[:], v.k)
48 Sum(&out, in, &key)
49 if !bytes.Equal(out[:], v.correct) {
50 t.Errorf("%d: expected %x, got %x", i, v.correct, out[:])
51 }
52 }
53 }
54
55 func TestSum(t *testing.T) { testSum(t, false) }
56 func TestSumUnaligned(t *testing.T) { testSum(t, true) }
57
58 func benchmark(b *testing.B, size int, unaligned bool) {
59 var out [16]byte
60 var key [32]byte
61 in := make([]byte, size)
62 if unaligned {
63 in = unalignBytes(in)
64 }
65 b.SetBytes(int64(len(in)))
66 b.ResetTimer()
67 for i := 0; i < b.N; i++ {
68 Sum(&out, in, &key)
69 }
70 }
71
72 func Benchmark64(b *testing.B) { benchmark(b, 64, false) }
73 func Benchmark1K(b *testing.B) { benchmark(b, 1024, false) }
74 func Benchmark64Unaligned(b *testing.B) { benchmark(b, 64, true) }
75 func Benchmark1KUnaligned(b *testing.B) { benchmark(b, 1024, true) }
76
77 func unalignBytes(in []byte) []byte {
78 out := make([]byte, len(in)+1)
79 if uintptr(unsafe.Pointer(&out[0]))&(unsafe.Alignof(uint32(0))-1) == 0 {
80 out = out[1:]
81 } else {
82 out = out[:len(in)]
83 }
84 copy(out, in)
85 return out
86 }