[PD1] crypto changes and TLS almost done

This commit is contained in:
Afonso Franco 2024-04-18 17:15:47 +01:00
parent 2c4f1fd2fc
commit 5ae7358a0d
Signed by: afonso
SSH key fingerprint: SHA256:aiLbdlPwXKJS5wMnghdtod0SPy8imZjlVvCyUX9DJNk
13 changed files with 138 additions and 87 deletions

View file

@ -1,18 +1,18 @@
package networking
import (
"crypto/tls"
"crypto/x509"
"encoding/json"
"net"
)
type Connection[T any] struct {
Conn net.Conn
Conn *tls.Conn
encoder *json.Encoder
decoder *json.Decoder
}
func NewConnection[T any](netConn net.Conn) Connection[T] {
func NewConnection[T any](netConn *tls.Conn) Connection[T] {
return Connection[T]{
Conn: netConn,
encoder: json.NewEncoder(netConn),
@ -20,16 +20,21 @@ func NewConnection[T any](netConn net.Conn) Connection[T] {
}
}
func (jc Connection[T]) Send(obj T) {
if err := jc.encoder.Encode(&obj); err != nil {
func (c Connection[T]) Send(obj T) {
if err := c.encoder.Encode(&obj); err != nil {
panic("Failed encoding data or sending it to connection")
}
}
func (jc Connection[T]) Receive() T {
func (c Connection[T]) Receive() T {
var obj T
if err := jc.decoder.Decode(&obj); err != nil {
if err := c.decoder.Decode(&obj); err != nil {
panic("Failed decoding data or reading it from connection")
}
return obj
}
func (c Connection[T]) GetPeerCertificate() *x509.Certificate {
state := c.Conn.ConnectionState()
return state.PeerCertificates[0]
}