-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathcrypto_test.go
More file actions
101 lines (84 loc) · 2.47 KB
/
crypto_test.go
File metadata and controls
101 lines (84 loc) · 2.47 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// SPDX-FileCopyrightText: 2026 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 benchmarkAESCTR(block cipher.Block, iv []byte, dst, src []byte) {
_ = xorBytesCTR(block, iv, dst, src)
}
func BenchmarkAES128CTRAlloc(b *testing.B) {
b.ReportAllocs()
const keysize = 16
key := make([]byte, keysize)
_, _ = rand.Read(key) //nolint: gosec,staticcheck
block, _ := aes.NewCipher(key)
iv := make([]byte, block.BlockSize())
src := make([]byte, 0)
dst := make([]byte, 0)
b.ResetTimer()
for i := 0; i < b.N; i++ {
benchmarkAESCTR(block, iv, dst, src)
}
}
func BenchmarkAES256CTRAlloc(b *testing.B) {
b.ReportAllocs()
const keysize = 32
key := make([]byte, keysize)
_, _ = rand.Read(key) //nolint: gosec,staticcheck
block, _ := aes.NewCipher(key)
iv := make([]byte, block.BlockSize())
src := make([]byte, 0)
dst := make([]byte, 0)
b.ResetTimer()
for i := 0; i < b.N; i++ {
benchmarkAESCTR(block, iv, dst, src)
}
}
func TestXorBytesCTR(t *testing.T) {
for keysize := 16; keysize < 64; keysize *= 2 {
key := make([]byte, keysize)
_, err := rand.Read(key) //nolint: gosec,staticcheck
require.NoError(t, err)
block, err := aes.NewCipher(key)
require.NoError(t, err)
iv := make([]byte, block.BlockSize())
for i := range 1500 {
src := make([]byte, i)
dst := make([]byte, i)
reference := make([]byte, i)
_, err = rand.Read(iv) //nolint: gosec,staticcheck
require.NoError(t, err)
_, err = rand.Read(src) //nolint: gosec,staticcheck
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))
}