summaryrefslogtreecommitdiffhomepage
path: root/src/cookie.go
blob: a6987a2fc1afccc56cecd5cfeda2091f4bced118 (plain)
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
package main

import (
	"errors"
	"golang.org/x/crypto/blake2s"
)

func CalculateCookie(peer *Peer, msg []byte) {
	size := len(msg)

	if size < blake2s.Size128*2 {
		panic(errors.New("bug: message too short"))
	}

	startMac1 := size - (blake2s.Size128 * 2)
	startMac2 := size - blake2s.Size128

	mac1 := msg[startMac1 : startMac1+blake2s.Size128]
	mac2 := msg[startMac2 : startMac2+blake2s.Size128]

	peer.mutex.RLock()
	defer peer.mutex.RUnlock()

	// set mac1

	func() {
		mac, _ := blake2s.New128(peer.macKey[:])
		mac.Write(msg[:startMac1])
		mac.Sum(mac1[:0])
	}()

	// set mac2

	if peer.cookie != nil {
		mac, _ := blake2s.New128(peer.cookie)
		mac.Write(msg[:startMac2])
		mac.Sum(mac2[:0])
	}
}