53 lines
1011 B
Go
53 lines
1011 B
Go
|
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
|
||
|
}
|