forked from pion/srtp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsrtcp.go
83 lines (63 loc) · 2.16 KB
/
srtcp.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package srtp
import (
"crypto/cipher"
"encoding/binary"
"github.com/pions/webrtc/pkg/rtcp"
)
func (c *Context) decryptRTCP(dst, encrypted []byte) ([]byte, error) {
out := allocateIfMismatch(dst, encrypted)
tailOffset := len(encrypted) - (authTagSize + srtcpIndexSize)
out = out[0:tailOffset]
isEncrypted := encrypted[tailOffset] >> 7
if isEncrypted == 0 {
return out, nil
}
srtcpIndexBuffer := out[tailOffset : tailOffset+srtcpIndexSize]
srtcpIndexBuffer[0] &= 0x7f // unset Encryption bit
index := binary.BigEndian.Uint32(srtcpIndexBuffer)
ssrc := binary.BigEndian.Uint32(encrypted[4:])
stream := cipher.NewCTR(c.srtcpBlock, c.generateCounter(uint16(index&0xffff), index>>16, ssrc, c.srtcpSessionSalt))
stream.XORKeyStream(out[8:], out[8:])
return out, nil
}
// DecryptRTCP decrypts a buffer that contains a RTCP packet
func (c *Context) DecryptRTCP(dst, encrypted []byte, header *rtcp.Header) ([]byte, error) {
if header == nil {
header = &rtcp.Header{}
}
if err := header.Unmarshal(encrypted); err != nil {
return nil, err
}
return c.decryptRTCP(dst, encrypted)
}
func (c *Context) encryptRTCP(dst, decrypted []byte) ([]byte, error) {
out := allocateIfMismatch(dst, decrypted)
ssrc := binary.BigEndian.Uint32(out[4:])
// We roll over early because MSB is used for marking as encrypted
c.srtcpIndex++
if c.srtcpIndex >= 2147483647 {
c.srtcpIndex = 0
}
// Encrypt everything after header
stream := cipher.NewCTR(c.srtcpBlock, c.generateCounter(uint16(c.srtcpIndex&0xffff), c.srtcpIndex>>16, ssrc, c.srtcpSessionSalt))
stream.XORKeyStream(out[8:], out[8:])
// Add SRTCP Index and set Encryption bit
out = append(out, make([]byte, 4)...)
binary.BigEndian.PutUint32(out[len(out)-4:], c.srtcpIndex)
out[len(out)-4] |= 0x80
authTag, err := c.generateAuthTag(out, c.srtcpSessionAuthTag)
if err != nil {
return nil, err
}
return append(out, authTag...), nil
}
// EncryptRTCP Encrypts a RTCP packet
func (c *Context) EncryptRTCP(dst, decrypted []byte, header *rtcp.Header) ([]byte, error) {
if header == nil {
header = &rtcp.Header{}
}
if err := header.Unmarshal(decrypted); err != nil {
return nil, err
}
return c.encryptRTCP(dst, decrypted)
}