-
Notifications
You must be signed in to change notification settings - Fork 52
/
crypto_test.go
67 lines (53 loc) · 1.61 KB
/
crypto_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package srtp
import (
"crypto/aes"
"crypto/cipher"
"math/rand"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func xorBytesCTRReference(block cipher.Block, iv []byte, dst, src []byte) {
stream := cipher.NewCTR(block, iv)
stream.XORKeyStream(dst, src)
}
func TestXorBytesCTR(t *testing.T) {
for keysize := 16; keysize < 64; keysize *= 2 {
key := make([]byte, keysize)
_, err := rand.Read(key) //nolint: gosec
require.NoError(t, err)
block, err := aes.NewCipher(key)
require.NoError(t, err)
iv := make([]byte, block.BlockSize())
for i := 0; i < 1500; i++ {
src := make([]byte, i)
dst := make([]byte, i)
reference := make([]byte, i)
_, err = rand.Read(iv) //nolint: gosec
require.NoError(t, err)
_, err = rand.Read(src) //nolint: gosec
require.NoError(t, err)
assert.NoError(t, xorBytesCTR(block, iv, dst, src))
xorBytesCTRReference(block, iv, reference, src)
require.Equal(t, dst, reference)
// test overlap
assert.NoError(t, xorBytesCTR(block, iv, dst, dst))
xorBytesCTRReference(block, iv, reference, reference)
require.Equal(t, dst, reference)
}
}
}
func TestXorBytesCTRInvalidIvLength(t *testing.T) {
key := make([]byte, 16)
block, err := aes.NewCipher(key)
require.NoError(t, err)
src := make([]byte, 1024)
dst := make([]byte, 1024)
test := func(iv []byte) {
assert.Error(t, errBadIVLength, xorBytesCTR(block, iv, dst, src))
}
test(make([]byte, block.BlockSize()-1))
test(make([]byte, block.BlockSize()+1))
}