// RemoteConnHandler continuously reads an encrypted message from a remote user // (sent from his/her LanChat client), decrypts it, then prints it to the // terminal. Called by RemoteTCPServer, which is used when *ActAsServer == true, // and TCPBridge, which is used when *ActAsServer == false. func RemoteConnHandler(conn net.Conn) { // New user connected; add their connection to routing table connList.AddRemote <- conn // Close conn and remove it from the routing table when we're done // here defer func() { connList.DeleteRemote <- conn conn.Close() }() // Create new cipher.Block decBlock, err := aes.NewCipher([]byte(SharedSecret)) if err != nil { log.Fatalf("Error creating AES cipher for decryption: %v\n", err) } ciphertext := make([]byte, MAX_MESSAGE_SIZE) for { n, err := conn.Read(ciphertext) if err != nil { if err == io.EOF { break // TODO: os.Exit(1) when disconnecting from _the_ server } log.Printf("Error reading message from remote conn %s: %v\n", conn.RemoteAddr(), err) continue } if DEBUG { log.Printf("ciphertext[:n] == %v\n", ciphertext[:n]) } // Send message to other remote users go func() { connList.WriteToRemotes <- &types.Cipherstore{conn, ciphertext[:n]} }() // Decrypt plaintext, err := crypt.AESDecryptBytes(decBlock, ciphertext[:n]) if err != nil { log.Printf("Error decrypting '%v' ('%s'): %v\n", ciphertext[:n], ciphertext[:n], err) continue } // Print to screen of the form `[timestamp] remoteIP: Message` now := time.Now().Format(time.Kitchen) fmt.Printf("[%s] %s: %s\n", now, conn.RemoteAddr(), plaintext) } }
func main() { msg := []byte("This is 18+ chars!") fmt.Printf("msg == %s\n", msg) // Encrypt encBlock, err := aes.NewCipher(PASSPHRASE) fun.MaybeFatalAt("aes.NewCipher", err) // See https://github.com/thecloakproject/utils/blob/master/crypt/aes.go cipher, err := crypt.AESEncryptBytes(encBlock, msg) fun.MaybeFatalAt("AESEncryptBytes", err) fmt.Printf("cipher == %v\n", cipher) // Decrypt decBlock, err := aes.NewCipher(PASSPHRASE) fun.MaybeFatalAt("aes.NewCipher", err) // See https://github.com/thecloakproject/utils/blob/master/crypt/aes.go plain, err := crypt.AESDecryptBytes(decBlock, cipher) fun.MaybeFatalAt("AESDecryptBytes", err) fmt.Printf("plain == %s\n", plain) msgPadded := utils.PadBytes(msg, decBlock.BlockSize()) // Check for equality fmt.Printf("\nThey match? %v!\n", bytes.Equal(msgPadded, plain)) // Check for equality in other ways msgUnpadded := strings.TrimSpace(string(msgPadded)) match := (msgUnpadded == string(plain)) fmt.Printf("\nDo their trimmed versions match? %v!\n", match) if match { fmt.Printf("They both equal '%s'\n", msgUnpadded) } // Here's how to remove those ugly trailing nulls fmt.Printf("Cleanest-looking version: '%s'\n", strings.TrimRight(string(plain), "\x00")) }