This repository has been archived by the owner on Sep 2, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
encoding.go
67 lines (59 loc) · 1.78 KB
/
encoding.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
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/binary"
"fmt"
"nethernettest/discovery"
)
func decodeDiscoveryPacket(rawData []byte) (discovery.Packet, uint64, error) {
data, err := decryptECB(rawData[32:])
if err != nil {
return nil, 0, fmt.Errorf("error decrypting: %w", err)
}
hm := hmac.New(sha256.New, key[:])
hm.Write(data)
if checksum := hm.Sum(nil); !bytes.Equal(rawData[:32], checksum) {
return nil, 0, fmt.Errorf("checksum mismatch: %v != %v", rawData[:32], checksum)
}
var length, pkID uint16
var senderID uint64
buf := bytes.NewBuffer(data)
_ = binary.Read(buf, binary.LittleEndian, &length)
_ = binary.Read(buf, binary.LittleEndian, &pkID)
_ = binary.Read(buf, binary.LittleEndian, &senderID)
buf.Next(8)
var pk discovery.Packet
switch pkID {
case discovery.IDRequest:
pk = &discovery.RequestPacket{}
case discovery.IDResponse:
pk = &discovery.ResponsePacket{}
case discovery.IDMessage:
pk = &discovery.MessagePacket{}
default:
return nil, 0, fmt.Errorf("unknown packet ID %v", pkID)
}
if err := pk.Read(buf); err != nil {
return nil, 0, fmt.Errorf("error reading packet %d: %w", pkID, err)
}
return pk, senderID, nil
}
func encodeDiscoveryPacket(senderID uint64, pk discovery.Packet) ([]byte, error) {
buf := new(bytes.Buffer)
_ = binary.Write(buf, binary.LittleEndian, pk.ID())
_ = binary.Write(buf, binary.LittleEndian, senderID)
_ = binary.Write(buf, binary.LittleEndian, make([]byte, 8))
pk.Write(buf)
length := len(buf.Bytes())
payload := append([]byte{byte(length), byte(length >> 8)}, buf.Bytes()...)
data, err := encryptECB(payload)
if err != nil {
return nil, fmt.Errorf("error encrypting: %w", err)
}
hm := hmac.New(sha256.New, key[:])
hm.Write(payload)
data = append(hm.Sum(nil), data...)
return data, nil
}