Clean up code

This commit is contained in:
Elara 2020-12-04 22:45:38 -08:00
parent 33b88c570d
commit 3e8b84b959
3 changed files with 19 additions and 16 deletions

View File

@ -29,7 +29,8 @@ func EncryptFile(filePath string, newFilePath string, sharedKey string) {
// Encode md5 hash bytes into hexadecimal
hashedKey := hex.EncodeToString(md5Hash.Sum(nil))
// Create new AES cipher
block, _ := aes.NewCipher([]byte(hashedKey))
block, err := aes.NewCipher([]byte(hashedKey))
if err != nil { log.Fatal().Err(err).Msg("Error creating AES cipher") }
// Create GCM for AES cipher
gcm, err := cipher.NewGCM(block)
if err != nil { log.Fatal().Err(err).Msg("Error creating GCM") }
@ -47,6 +48,7 @@ func EncryptFile(filePath string, newFilePath string, sharedKey string) {
defer newFile.Close()
// Write ciphertext to new file
bytesWritten, err := newFile.Write(ciphertext)
if err != nil { log.Fatal().Err(err).Msg("Error writing to file") }
// Log bytes written and to which file
log.Info().Str("file", filepath.Base(newFilePath)).Msg("Wrote " + strconv.Itoa(bytesWritten) + " bytes")
}
@ -81,6 +83,7 @@ func DecryptFile(filePath string, newFilePath string, sharedKey string) {
defer newFile.Close()
// Write ciphertext to new file
bytesWritten, err := newFile.Write(plaintext)
if err != nil { log.Fatal().Err(err).Msg("Error writing to file") }
// Log bytes written and to which file
log.Info().Str("file", filepath.Base(newFilePath)).Msg("Wrote " + strconv.Itoa(bytesWritten) + " bytes")
}

View File

@ -38,7 +38,7 @@ func SendFiles(dir string) {
// Instantiate http.Server struct
srv := &http.Server{}
// Listen on all ipv4 addresses on port 9898
listener, err := net.Listen("tcp4", ":9898")
listener, err := net.Listen("tcp", ":9898")
if err != nil { log.Fatal().Err(err).Msg("Error starting listener") }
// If client connects to /:filePath
@ -73,7 +73,7 @@ func SendFiles(dir string) {
// For each file in listing
for _, file := range dirListing {
// If the file is not the key
if !strings.Contains(file.Name(), "savedKey.aesKey") {
if !strings.Contains(file.Name(), "key.aes") {
// Append the file path to indexSlice
indexSlice = append(indexSlice, dir + "/" + file.Name())
}
@ -90,7 +90,7 @@ func SendFiles(dir string) {
// Inform user a client has requested the key
log.Info().Msg("GET Key")
// Read saved key
key, err := ioutil.ReadFile(dir + "/savedKey.aesKey")
key, err := ioutil.ReadFile(dir + "/key.aes")
if err != nil { log.Fatal().Err(err).Msg("Error reading key") }
// Write saved key to ResponseWriter
_, err = fmt.Fprint(res, string(key))
@ -103,7 +103,7 @@ func SendFiles(dir string) {
log.Info().Msg("GET Stop")
log.Info().Msg("Stop signal received")
// Shutdown server and send to empty context
err := srv.Shutdown(context.TODO())
err := srv.Shutdown(context.Background())
if err != nil { log.Fatal().Err(err).Msg("Error stopping server") }
})
@ -112,7 +112,7 @@ func SendFiles(dir string) {
}
// Get files from sender
func RecvFiles(dir string, senderAddr string) {
func RecvFiles(senderAddr string) {
// Use ConsoleWriter logger
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}).Hook(FatalHook{})
// Get server address by getting the IP without the port, prepending http:// and appending :9898

18
main.go
View File

@ -104,9 +104,7 @@ func main() {
choiceStr, _ := reader.ReadString('\n')
// Convert input to int after trimming spaces
choiceInt, err := strconv.Atoi(strings.TrimSpace(choiceStr))
if err != nil {
log.Fatal().Err(err).Msg("Error converting choice to int")
}
if err != nil { log.Fatal().Err(err).Msg("Error converting choice to int") }
// Set choiceIndex to choiceInt-1 to allow for indexing
choiceIndex := choiceInt - 1
// Get IP of chosen receiver
@ -120,8 +118,8 @@ func main() {
log.Info().Msg("Receiver key received")
// Encrypt shared key using RSA public key
key := EncryptKey(sharedKey, rawKey)
// Save encrypted key in opensend directory as savedKey.aesKey
SaveEncryptedKey(key, opensendDir + "/savedKey.aesKey")
// Save encrypted key in opensend directory as key.aes
SaveEncryptedKey(key, opensendDir + "/key.aes")
// Instantiate Config object
config := NewConfig(*actionType, *actionData)
// Collect any files that may be required for transaction into opensend directory
@ -145,10 +143,12 @@ func main() {
// Shutdown zeroconf server at the end of main()
defer zeroconfShutdown()
}
// Notify user opensend is waiting for key exchange
log.Info().Msg("Waiting for sender key exchange")
// Notify user keypair is being generated
log.Info().Msg("Generating RSA keypair")
// Generate keypair
privateKey, publicKey := GenerateRSAKeypair()
// Notify user opensend is waiting for key exchange
log.Info().Msg("Waiting for sender key exchange")
// Exchange keys with sender
senderIP := ReceiverKeyExchange(publicKey)
// Sleep 300ms to allow sender time to start HTTP server
@ -156,7 +156,7 @@ func main() {
// Notify user files are being received
log.Info().Msg("Receiving files from server (This may take a while)")
// Get files from sender and place them into the opensend directory
RecvFiles(opensendDir, senderIP)
RecvFiles(senderIP)
// Get encrypted shared key from sender
encryptedKey := GetKey(senderIP)
// Send stop signal to sender's HTTP server
@ -180,5 +180,5 @@ func main() {
}
// Remove opensend directory
err = os.RemoveAll(opensendDir)
if err != nil { log.Fatal().Err(err).Msg("Error remove opensend dir") }
if err != nil { log.Fatal().Err(err).Msg("Error removing opensend directory") }
}