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.
14 func TestSealOpen(t *testing.T) {
18 rand.Reader.Read(key[:])
19 rand.Reader.Read(nonce[:])
21 var box, opened []byte
23 for msgLen := 0; msgLen < 128; msgLen += 17 {
24 message := make([]byte, msgLen)
25 rand.Reader.Read(message)
27 box = Seal(box[:0], message, &nonce, &key)
29 opened, ok = Open(opened[:0], box, &nonce, &key)
31 t.Errorf("%d: failed to open box", msgLen)
35 if !bytes.Equal(opened, message) {
36 t.Errorf("%d: got %x, expected %x", msgLen, opened, message)
43 _, ok := Open(opened[:0], box, &nonce, &key)
45 t.Errorf("box was opened after corrupting byte %d", i)
51 func TestSecretBox(t *testing.T) {
56 for i := range key[:] {
59 for i := range nonce[:] {
62 for i := range message[:] {
66 box := Seal(nil, message[:], &nonce, &key)
67 // expected was generated using the C implementation of NaCl.
68 expected, _ := hex.DecodeString("8442bc313f4626f1359e3b50122b6ce6fe66ddfe7d39d14e637eb4fd5b45beadab55198df6ab5368439792a23c87db70acb6156dc5ef957ac04f6276cf6093b84be77ff0849cc33e34b7254d5a8f65ad")
70 if !bytes.Equal(box, expected) {
71 t.Fatalf("box didn't match, got\n%x\n, expected\n%x", box, expected)
75 func TestAppend(t *testing.T) {
80 out := make([]byte, 4)
81 box := Seal(out, message[:], &nonce, &key)
82 if !bytes.Equal(box[:4], out[:4]) {
83 t.Fatalf("Seal didn't correctly append")
86 out = make([]byte, 4, 100)
87 box = Seal(out, message[:], &nonce, &key)
88 if !bytes.Equal(box[:4], out[:4]) {
89 t.Fatalf("Seal didn't correctly append with sufficient capacity.")
93 func benchmarkSealSize(b *testing.B, size int) {
94 message := make([]byte, size)
95 out := make([]byte, size+Overhead)
99 b.SetBytes(int64(size))
102 for i := 0; i < b.N; i++ {
103 out = Seal(out[:0], message, &nonce, &key)
107 func BenchmarkSeal8Bytes(b *testing.B) {
108 benchmarkSealSize(b, 8)
111 func BenchmarkSeal100Bytes(b *testing.B) {
112 benchmarkSealSize(b, 100)
115 func BenchmarkSeal1K(b *testing.B) {
116 benchmarkSealSize(b, 1024)
119 func BenchmarkSeal8K(b *testing.B) {
120 benchmarkSealSize(b, 8192)
123 func benchmarkOpenSize(b *testing.B, size int) {
124 msg := make([]byte, size)
125 result := make([]byte, size)
128 box := Seal(nil, msg, &nonce, &key)
130 b.SetBytes(int64(size))
133 for i := 0; i < b.N; i++ {
134 if _, ok := Open(result[:0], box, &nonce, &key); !ok {
140 func BenchmarkOpen8Bytes(b *testing.B) {
141 benchmarkOpenSize(b, 8)
144 func BenchmarkOpen100Bytes(b *testing.B) {
145 benchmarkOpenSize(b, 100)
148 func BenchmarkOpen1K(b *testing.B) {
149 benchmarkOpenSize(b, 1024)
152 func BenchmarkOpen8K(b *testing.B) {
153 benchmarkOpenSize(b, 8192)