vppn/node/cipher-routing_test.go
2024-12-19 20:53:52 +01:00

115 lines
2.3 KiB
Go

package node
import (
"bytes"
"crypto/rand"
"testing"
"golang.org/x/crypto/nacl/box"
)
func newRoutingCipherForTesting() (c1, c2 routingCipher) {
pubKey1, privKey1, err := box.GenerateKey(rand.Reader)
if err != nil {
panic(err)
}
pubKey2, privKey2, err := box.GenerateKey(rand.Reader)
if err != nil {
panic(err)
}
return newRoutingCipher(privKey1[:], pubKey2[:]),
newRoutingCipher(privKey2[:], pubKey1[:])
}
func TestRoutingCipher(t *testing.T) {
c1, c2 := newRoutingCipherForTesting()
maxSizePlaintext := make([]byte, bufferSize-routingHeaderSize-routingCipherOverhead)
rand.Read(maxSizePlaintext)
testCases := [][]byte{
make([]byte, 0),
{1},
{255},
{1, 2, 3, 4, 5},
[]byte("Hello world"),
maxSizePlaintext,
}
for _, plaintext := range testCases {
h1 := xHeader{
Counter: 235153,
SourceIP: 4,
DestIP: 88,
}
encrypted := make([]byte, bufferSize)
encrypted = c1.Encrypt(h1, plaintext, encrypted)
decrypted, ok := c2.Decrypt(encrypted, make([]byte, bufferSize))
if !ok {
t.Fatal(ok)
}
if !bytes.Equal(decrypted, plaintext) {
t.Fatal("not equal")
}
}
}
func TestRoutingCipher_ShortCiphertext(t *testing.T) {
c1, _ := newRoutingCipherForTesting()
shortText := make([]byte, routingHeaderSize+routingCipherOverhead-1)
rand.Read(shortText)
_, ok := c1.Decrypt(shortText, make([]byte, bufferSize))
if ok {
t.Fatal(ok)
}
}
func BenchmarkRoutingCipher_Encrypt(b *testing.B) {
c1, _ := newRoutingCipherForTesting()
h1 := xHeader{
Counter: 235153,
SourceIP: 4,
DestIP: 88,
}
plaintext := make([]byte, bufferSize-routingHeaderSize-routingCipherOverhead)
rand.Read(plaintext)
encrypted := make([]byte, bufferSize)
b.ResetTimer()
for i := 0; i < b.N; i++ {
encrypted = c1.Encrypt(h1, plaintext, encrypted)
}
}
func BenchmarkRoutingCipher_Decrypt(b *testing.B) {
c1, c2 := newRoutingCipherForTesting()
h1 := xHeader{
Counter: 235153,
SourceIP: 4,
DestIP: 88,
}
plaintext := make([]byte, bufferSize-routingHeaderSize-routingCipherOverhead)
rand.Read(plaintext)
encrypted := make([]byte, bufferSize)
encrypted = c1.Encrypt(h1, plaintext, encrypted)
decrypted := make([]byte, bufferSize)
b.ResetTimer()
for i := 0; i < b.N; i++ {
decrypted, _ = c2.Decrypt(encrypted, decrypted)
}
}