This repository has been archived on 2021-07-08. You can view files and clone it, but cannot push or open issues or pull requests.
opensend/keyExchange.go

76 lines
2.1 KiB
Go
Raw Normal View History

/*
Copyright © 2021 Arsen Musayelyan
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
2020-12-03 10:12:43 +00:00
package main
import (
"crypto/rsa"
"encoding/gob"
"net"
2021-06-19 07:36:48 +00:00
"github.com/rs/zerolog/log"
2020-12-03 10:12:43 +00:00
)
// Exchange keys with sender
func ReceiverKeyExchange(key *rsa.PublicKey) string {
// Use ConsoleWriter logger
// Create TCP listener on port 9797
listener, err := net.Listen("tcp", ":9797")
2020-12-21 07:18:42 +00:00
if err != nil {
log.Fatal().Err(err).Msg("Error starting listener")
}
2020-12-03 10:12:43 +00:00
// Create string for sender address
var senderAddr string
for {
// Accept connection on listener
connection, err := listener.Accept()
2020-12-21 07:18:42 +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)
2020-12-21 07:18:42 +00:00
if err != nil {
log.Fatal().Err(err).Msg("Error encoding key")
}
2020-12-04 20:55:55 +00:00
return senderAddr
2020-12-03 10:12:43 +00:00
}
}
// Exchange keys with receiver
func SenderKeyExchange(receiverIP string) *rsa.PublicKey {
// Use ConsoleWriter logger
// Connect to TCP socket on receiver IP port 9797
2020-12-21 07:18:42 +00:00
connection, err := net.Dial("tcp", receiverIP+":9797")
if err != nil {
log.Fatal().Err(err).Msg("Error connecting to sender")
}
2020-12-03 10:12:43 +00:00
// Create gob decoder
decoder := gob.NewDecoder(connection)
// Instantiate rsa.PublicKey struct
recvPubKey := &rsa.PublicKey{}
// Decode key
err = decoder.Decode(recvPubKey)
2020-12-21 07:18:42 +00:00
if err != nil {
log.Fatal().Err(err).Msg("Error decoding key")
}
2020-12-03 10:12:43 +00:00
// Return received key
return recvPubKey
}