2020-12-03 10:12:43 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/rsa"
|
|
|
|
"encoding/gob"
|
|
|
|
"github.com/rs/zerolog"
|
|
|
|
"github.com/rs/zerolog/log"
|
|
|
|
"net"
|
|
|
|
"os"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Exchange keys with sender
|
|
|
|
func ReceiverKeyExchange(key *rsa.PublicKey) string {
|
|
|
|
// Use ConsoleWriter logger
|
2020-12-03 17:32:03 +00:00
|
|
|
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}).Hook(FatalHook{})
|
2020-12-03 10:12:43 +00:00
|
|
|
// Create TCP listener on port 9797
|
|
|
|
listener, err := net.Listen("tcp", ":9797")
|
|
|
|
if err != nil { log.Fatal().Err(err).Msg("Error starting listener") }
|
|
|
|
// Create string for sender address
|
|
|
|
var senderAddr string
|
|
|
|
for {
|
|
|
|
// Accept connection on listener
|
|
|
|
connection, err := listener.Accept()
|
2020-12-04 20:55:55 +00:00
|
|
|
if err != nil { log.Fatal().Err(err).Msg("Error accepting connections") }
|
2020-12-03 10:12:43 +00:00
|
|
|
// Get sender address and store it in senderAddr
|
|
|
|
senderAddr = connection.RemoteAddr().String()
|
2020-12-04 20:55:55 +00:00
|
|
|
// Create gob encoder with connection as io.Writer
|
|
|
|
encoder := gob.NewEncoder(connection)
|
|
|
|
// Encode key into connection
|
|
|
|
err = encoder.Encode(key)
|
|
|
|
if err != nil { log.Fatal().Err(err).Msg("Error encoding key") }
|
|
|
|
return senderAddr
|
2020-12-03 10:12:43 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Exchange keys with receiver
|
|
|
|
func SenderKeyExchange(receiverIP string) *rsa.PublicKey {
|
|
|
|
// Use ConsoleWriter logger
|
2020-12-03 17:32:03 +00:00
|
|
|
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}).Hook(FatalHook{})
|
2020-12-03 10:12:43 +00:00
|
|
|
// Connect to TCP socket on receiver IP port 9797
|
|
|
|
connection, err := net.Dial("tcp", receiverIP + ":9797")
|
|
|
|
if err != nil { log.Fatal().Err(err).Msg("Error connecting to sender") }
|
|
|
|
// Create gob decoder
|
|
|
|
decoder := gob.NewDecoder(connection)
|
|
|
|
// Instantiate rsa.PublicKey struct
|
|
|
|
recvPubKey := &rsa.PublicKey{}
|
|
|
|
// Decode key
|
|
|
|
err = decoder.Decode(recvPubKey)
|
|
|
|
if err != nil { log.Fatal().Err(err).Msg("Error decoding key") }
|
|
|
|
// Return received key
|
|
|
|
return recvPubKey
|
|
|
|
}
|