67 lines
1.2 KiB
Go
67 lines
1.2 KiB
Go
package main
|
|
|
|
import (
|
|
"crypto/tls"
|
|
"crypto/x509"
|
|
"gitlab.lrz.de/netintum/teaching/p2psec_projects_2024/DHT-6/pkg"
|
|
"io"
|
|
"log"
|
|
"os"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
func TestBasicTLSConnection(t *testing.T) {
|
|
kademlia.GenerateCert("127.0.0.1", "cert.pem", "key.pem")
|
|
|
|
go StartTLSServer(t)
|
|
|
|
cert, err := os.ReadFile("cert.pem")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
certPool := x509.NewCertPool()
|
|
if ok := certPool.AppendCertsFromPEM(cert); !ok {
|
|
t.Fatal("Unable to parse cert from file")
|
|
}
|
|
config := &tls.Config{RootCAs: certPool}
|
|
time.Sleep(time.Second)
|
|
conn, err := tls.Dial("tcp", "127.0.0.1:8001", config)
|
|
|
|
_, err = io.WriteString(conn, "Hello World")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
time.Sleep(time.Second)
|
|
|
|
}
|
|
|
|
func StartTLSServer(t *testing.T) {
|
|
cert, err := tls.LoadX509KeyPair("cert.pem", "key.pem")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
config := &tls.Config{Certificates: []tls.Certificate{cert}}
|
|
|
|
l, err := tls.Listen("tcp", ":8001", config)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer l.Close()
|
|
|
|
for {
|
|
conn, err := l.Accept()
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
log.Print("Accepted connection")
|
|
|
|
buf := make([]byte, 20)
|
|
|
|
conn.Read(buf)
|
|
t.Logf("%s", buf)
|
|
}
|
|
}
|