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 // Encode md5 hash bytes into hexadecimal
hashedKey := hex.EncodeToString(md5Hash.Sum(nil)) hashedKey := hex.EncodeToString(md5Hash.Sum(nil))
// Create new AES cipher // 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 // Create GCM for AES cipher
gcm, err := cipher.NewGCM(block) gcm, err := cipher.NewGCM(block)
if err != nil { log.Fatal().Err(err).Msg("Error creating GCM") } 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() defer newFile.Close()
// Write ciphertext to new file // Write ciphertext to new file
bytesWritten, err := newFile.Write(ciphertext) 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 bytes written and to which file
log.Info().Str("file", filepath.Base(newFilePath)).Msg("Wrote " + strconv.Itoa(bytesWritten) + " bytes") 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() defer newFile.Close()
// Write ciphertext to new file // Write ciphertext to new file
bytesWritten, err := newFile.Write(plaintext) 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 bytes written and to which file
log.Info().Str("file", filepath.Base(newFilePath)).Msg("Wrote " + strconv.Itoa(bytesWritten) + " bytes") log.Info().Str("file", filepath.Base(newFilePath)).Msg("Wrote " + strconv.Itoa(bytesWritten) + " bytes")
} }
@ -99,7 +102,7 @@ func EncryptFiles(dir string, sharedKey string) {
EncryptFile(path, path + ".enc", sharedKey) EncryptFile(path, path + ".enc", sharedKey)
// Remove unencrypted file // Remove unencrypted file
err := os.Remove(path) err := os.Remove(path)
if err != nil {return err} if err != nil { return err }
} }
// Return nil if no error occurs // Return nil if no error occurs
return nil return nil

View File

@ -38,7 +38,7 @@ func SendFiles(dir string) {
// Instantiate http.Server struct // Instantiate http.Server struct
srv := &http.Server{} srv := &http.Server{}
// Listen on all ipv4 addresses on port 9898 // 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 err != nil { log.Fatal().Err(err).Msg("Error starting listener") }
// If client connects to /:filePath // If client connects to /:filePath
@ -73,7 +73,7 @@ func SendFiles(dir string) {
// For each file in listing // For each file in listing
for _, file := range dirListing { for _, file := range dirListing {
// If the file is not the key // 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 // Append the file path to indexSlice
indexSlice = append(indexSlice, dir + "/" + file.Name()) indexSlice = append(indexSlice, dir + "/" + file.Name())
} }
@ -90,7 +90,7 @@ func SendFiles(dir string) {
// Inform user a client has requested the key // Inform user a client has requested the key
log.Info().Msg("GET Key") log.Info().Msg("GET Key")
// Read saved 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") } if err != nil { log.Fatal().Err(err).Msg("Error reading key") }
// Write saved key to ResponseWriter // Write saved key to ResponseWriter
_, err = fmt.Fprint(res, string(key)) _, err = fmt.Fprint(res, string(key))
@ -103,7 +103,7 @@ func SendFiles(dir string) {
log.Info().Msg("GET Stop") log.Info().Msg("GET Stop")
log.Info().Msg("Stop signal received") log.Info().Msg("Stop signal received")
// Shutdown server and send to empty context // 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") } if err != nil { log.Fatal().Err(err).Msg("Error stopping server") }
}) })
@ -112,7 +112,7 @@ func SendFiles(dir string) {
} }
// Get files from sender // Get files from sender
func RecvFiles(dir string, senderAddr string) { func RecvFiles(senderAddr string) {
// Use ConsoleWriter logger // Use ConsoleWriter logger
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}).Hook(FatalHook{}) 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 // 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') choiceStr, _ := reader.ReadString('\n')
// Convert input to int after trimming spaces // Convert input to int after trimming spaces
choiceInt, err := strconv.Atoi(strings.TrimSpace(choiceStr)) choiceInt, err := strconv.Atoi(strings.TrimSpace(choiceStr))
if err != nil { if err != nil { log.Fatal().Err(err).Msg("Error converting choice to int") }
log.Fatal().Err(err).Msg("Error converting choice to int")
}
// Set choiceIndex to choiceInt-1 to allow for indexing // Set choiceIndex to choiceInt-1 to allow for indexing
choiceIndex := choiceInt - 1 choiceIndex := choiceInt - 1
// Get IP of chosen receiver // Get IP of chosen receiver
@ -120,8 +118,8 @@ func main() {
log.Info().Msg("Receiver key received") log.Info().Msg("Receiver key received")
// Encrypt shared key using RSA public key // Encrypt shared key using RSA public key
key := EncryptKey(sharedKey, rawKey) key := EncryptKey(sharedKey, rawKey)
// Save encrypted key in opensend directory as savedKey.aesKey // Save encrypted key in opensend directory as key.aes
SaveEncryptedKey(key, opensendDir + "/savedKey.aesKey") SaveEncryptedKey(key, opensendDir + "/key.aes")
// Instantiate Config object // Instantiate Config object
config := NewConfig(*actionType, *actionData) config := NewConfig(*actionType, *actionData)
// Collect any files that may be required for transaction into opensend directory // 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() // Shutdown zeroconf server at the end of main()
defer zeroconfShutdown() defer zeroconfShutdown()
} }
// Notify user opensend is waiting for key exchange // Notify user keypair is being generated
log.Info().Msg("Waiting for sender key exchange") log.Info().Msg("Generating RSA keypair")
// Generate keypair // Generate keypair
privateKey, publicKey := GenerateRSAKeypair() privateKey, publicKey := GenerateRSAKeypair()
// Notify user opensend is waiting for key exchange
log.Info().Msg("Waiting for sender key exchange")
// Exchange keys with sender // Exchange keys with sender
senderIP := ReceiverKeyExchange(publicKey) senderIP := ReceiverKeyExchange(publicKey)
// Sleep 300ms to allow sender time to start HTTP server // Sleep 300ms to allow sender time to start HTTP server
@ -156,7 +156,7 @@ func main() {
// Notify user files are being received // Notify user files are being received
log.Info().Msg("Receiving files from server (This may take a while)") log.Info().Msg("Receiving files from server (This may take a while)")
// Get files from sender and place them into the opensend directory // Get files from sender and place them into the opensend directory
RecvFiles(opensendDir, senderIP) RecvFiles(senderIP)
// Get encrypted shared key from sender // Get encrypted shared key from sender
encryptedKey := GetKey(senderIP) encryptedKey := GetKey(senderIP)
// Send stop signal to sender's HTTP server // Send stop signal to sender's HTTP server
@ -180,5 +180,5 @@ func main() {
} }
// Remove opensend directory // Remove opensend directory
err = os.RemoveAll(opensendDir) 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") }
} }