51 lines
1.1 KiB
Go
51 lines
1.1 KiB
Go
package node
|
|
|
|
import (
|
|
"sync"
|
|
"vppn/fasttime"
|
|
|
|
"golang.org/x/crypto/nacl/box"
|
|
)
|
|
|
|
// Encrypting the packet will also set the header's DataSize field.
|
|
func encryptPacket(h *header, sharedKey, data, out []byte) []byte {
|
|
out = out[:headerSize]
|
|
h.Marshal(out)
|
|
b := box.SealAfterPrecomputation(out[headerSize:headerSize], data, (*[24]byte)(out[:headerSize]), (*[32]byte)(sharedKey))
|
|
return out[:len(b)+headerSize]
|
|
}
|
|
|
|
func decryptPacket(sharedKey, packetAndHeader, out []byte) (decrypted []byte, ok bool) {
|
|
return box.OpenAfterPrecomputation(
|
|
out[:0],
|
|
packetAndHeader[headerSize:],
|
|
(*[24]byte)(packetAndHeader[:headerSize]),
|
|
(*[32]byte)(sharedKey))
|
|
}
|
|
|
|
func computeSharedKey(peerPubKey, privKey []byte) []byte {
|
|
shared := [32]byte{}
|
|
box.Precompute(&shared, (*[32]byte)(peerPubKey), (*[32]byte)(privKey))
|
|
return shared[:]
|
|
}
|
|
|
|
var (
|
|
traceIDLock sync.Mutex
|
|
traceIDTime uint64
|
|
traceIDCounter uint64
|
|
)
|
|
|
|
func newTraceID() (id uint64) {
|
|
traceIDLock.Lock()
|
|
defer traceIDLock.Unlock()
|
|
|
|
now := uint64(fasttime.Now())
|
|
if traceIDTime < now {
|
|
traceIDTime = now
|
|
traceIDCounter = 0
|
|
}
|
|
traceIDCounter++
|
|
|
|
return traceIDTime<<30 + traceIDCounter
|
|
}
|