dissertation-2-code/proxy/packet.go

53 lines
1011 B
Go
Raw Normal View History

2020-10-22 21:19:26 +01:00
package proxy
import (
"encoding/binary"
"time"
)
type Packet struct {
Data []byte
timestamp time.Time
}
func NewPacket(data []byte) Packet {
return Packet{
Data: data,
timestamp: time.Now(),
}
}
func UnmarshalPacket(raw []byte, verifier MacVerifier) *Packet {
// the MAC is the last N bytes
data := raw[:len(raw)-verifier.CodeLength()]
sum := raw[len(raw)-verifier.CodeLength():]
if !verifier.Verify(data, sum) {
return nil
}
p := Packet{
Data: data[:8],
}
unixTime := int64(binary.LittleEndian.Uint64(data[len(data)-8:]))
p.timestamp = time.Unix(unixTime, 0)
return &p
}
func (p Packet) Marshal(generator MacGenerator) []byte {
// length of data + length of timestamp (8 byte) + length of checksum
slice := make([]byte, len(p.Data)+8+generator.CodeLength())
copy(slice, p.Data)
unixTime := uint64(p.timestamp.Unix())
binary.LittleEndian.PutUint64(slice[len(p.Data):], unixTime)
mac := generator.Generate(slice)
copy(slice[len(p.Data)+8:], mac)
return slice
}