This commit is contained in:
jdl
2024-12-08 09:45:29 +01:00
parent 55a9bf9dc3
commit 03ff1aac80
60 changed files with 3165 additions and 2 deletions

32
peer/crypto.go Normal file
View File

@@ -0,0 +1,32 @@
package peer
import (
"golang.org/x/crypto/nacl/box"
"golang.org/x/crypto/nacl/sign"
)
func encryptPacket(sharedKey, nonce, packet, out []byte) []byte {
out = box.SealAfterPrecomputation(out[:0], packet, (*[24]byte)(nonce), (*[32]byte)(sharedKey))
return append(out, nonce...)
}
func decryptPacket(sharedKey, packet, out []byte) (decrypted []byte, ok bool) {
cut := len(packet) - NONCE_SIZE
decrypted, ok = box.OpenAfterPrecomputation(out[:0], packet[:cut], (*[24]byte)(packet[cut:]), (*[32]byte)(sharedKey))
return decrypted, ok
}
// Signed packet should be encrypted with the encryptPacket function first.
func signPacket(privKey, packet, out []byte) []byte {
return sign.Sign(out[:0], packet, (*[64]byte)(privKey))
}
func openPacket(pubKey, packet, out []byte) (encPacket []byte, ok bool) {
return sign.Open(out[:0], packet, (*[32]byte)(pubKey))
}
func computeSharedKey(peerPubKey, privKey []byte) []byte {
shared := [32]byte{}
box.Precompute(&shared, (*[32]byte)(peerPubKey), (*[32]byte)(privKey))
return shared[:]
}