-
Notifications
You must be signed in to change notification settings - Fork 49
/
crypto.go
59 lines (50 loc) · 1.15 KB
/
crypto.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
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package srtp
import (
"crypto/cipher"
"sync"
"github.com/pion/transport/v3/utils/xor"
)
// incrementCTR increments a big-endian integer of arbitrary size.
func incrementCTR(ctr []byte) {
for i := len(ctr) - 1; i >= 0; i-- {
ctr[i]++
if ctr[i] != 0 {
break
}
}
}
var xorBufferPool = sync.Pool{ // nolint:gochecknoglobals
New: func() interface{} {
return make([]byte, 1500)
},
}
// xorBytesCTR performs CTR encryption and decryption.
// It is equivalent to cipher.NewCTR followed by XORKeyStream.
func xorBytesCTR(block cipher.Block, iv []byte, dst, src []byte) error {
if len(iv) != block.BlockSize() {
return errBadIVLength
}
xorBuf := xorBufferPool.Get()
defer xorBufferPool.Put(xorBuf)
buffer, ok := xorBuf.([]byte)
if !ok {
return errFailedTypeAssertion
}
ctr := buffer[:len(iv)]
copy(ctr, iv)
bs := block.BlockSize()
stream := buffer[len(iv) : len(iv)+bs]
i := 0
for i < len(src) {
block.Encrypt(stream, ctr)
incrementCTR(ctr)
n := xor.XorBytes(dst[i:], src[i:], stream)
if n == 0 {
break
}
i += n
}
return nil
}