Debian Codegraph @

chacha20/chacha/chacha_test.go

raw symbols SCIP
1 // Use of this source code is governed by a license
2 // that can be found in the LICENSE file.
3
4 package chacha
5
6 import (
7 "bytes"
8 "encoding/hex"
9 "testing"
10 )
11
12 var recFail = func(t *testing.T, msg string) {
13 if err := recover(); err == nil {
14 t.Fatalf("Expected error: %s", msg)
15 }
16 }
17
18 func TestNewCipher(t *testing.T) {
19 mustFail := func(t *testing.T, msg string, nonce *[12]byte, key *[32]byte, rounds int) {
20 defer recFail(t, msg)
21 NewCipher(nonce, key, rounds)
22 }
23
24 key := new([32]byte)
25 nonce := new([12]byte)
26
27 mustFail(t, "rounds is 0", nonce, key, 0)
28
29 mustFail(t, "rounds is not even", nonce, key, 21)
30 }
31
32 func TestSetCounter(t *testing.T) {
33 var key [32]byte
34 var nonce [12]byte
35 for i := range key {
36 key[i] = byte(i)
37 }
38 buf0, buf1 := make([]byte, 128), make([]byte, 128)
39
40 c := NewCipher(&nonce, &key, 20)
41 c.XORKeyStream(buf0[:1], buf0[:1])
42 c.SetCounter(20)
43 c.XORKeyStream(buf0[1:], buf0[1:])
44
45 XORKeyStream(buf1[:1], buf1[:1], &nonce, &key, 0, 20)
46 XORKeyStream(buf1[1:], buf1[1:], &nonce, &key, 20, 20)
47
48 if !bytes.Equal(buf0, buf1) {
49 t.Fatalf("XORKeyStream differ from chacha.XORKeyStream\n XORKeyStream: %s \n chacha.XORKeyStream: %s", hex.EncodeToString(buf1), hex.EncodeToString(buf0))
50 }
51 }
52
53 func TestXORKeyStream(t *testing.T) {
54 var key [32]byte
55 var nonce [12]byte
56 for i := range key {
57 key[i] = byte(i)
58 }
59 buf0, buf1 := make([]byte, 256), make([]byte, 256)
60
61 c := NewCipher(&nonce, &key, 20)
62 c.XORKeyStream(buf0[:1], buf0[:1])
63 c.XORKeyStream(buf0[1:65], buf0[1:65])
64 c.XORKeyStream(buf0[65:193], buf0[65:193])
65 c.XORKeyStream(buf0[193:200], buf0[193:200])
66 c.XORKeyStream(buf0[200:], buf0[200:])
67
68 XORKeyStream(buf1, buf1, &nonce, &key, 0, 20)
69
70 if !bytes.Equal(buf0, buf1) {
71 t.Fatalf("XORKeyStream differ from chacha.XORKeyStream\n XORKeyStream: %s \n chacha.XORKeyStream: %s", hex.EncodeToString(buf1), hex.EncodeToString(buf0))
72 }
73 }
74
75 func TestXORKeyStreamPanic(t *testing.T) {
76 mustFail := func(t *testing.T, msg string, dst, src []byte, nonce *[12]byte, key *[32]byte, counter uint32, rounds int) {
77 defer recFail(t, msg)
78 XORKeyStream(dst, src, nonce, key, counter, rounds)
79 }
80
81 key := new([32]byte)
82 nonce := new([12]byte)
83 src, dst := make([]byte, 65), make([]byte, 65)
84
85 mustFail(t, "rounds is 0", dst, src, nonce, key, 0, 0)
86
87 mustFail(t, "rounds is not even", dst, src, nonce, key, 0, 21)
88
89 mustFail(t, "len(dst) < len(src)", dst[:len(src)-1], src, nonce, key, 0, 20)
90
91 c := NewCipher(nonce, key, 20)
92
93 mustFail2 := func(t *testing.T, msg string, dst, src []byte) {
94 defer recFail(t, msg)
95 c.XORKeyStream(dst, src)
96 }
97
98 mustFail2(t, "len(dst) < len(src)", dst[:len(src)-1], src)
99
100 }