server.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package main
  2. import (
  3. "crypto/aes"
  4. "crypto/cipher"
  5. "encoding/binary"
  6. "encoding/hex"
  7. "fmt"
  8. "net"
  9. )
  10. var aes_key = "03020100070605040b0a09080f0e0d0c"
  11. func serveConnection(conn net.Conn) {
  12. defer logPanic()
  13. defer conn.Close()
  14. fmt.Printf("Connection from %s\n", conn.RemoteAddr().String())
  15. decoded, _ := hex.DecodeString(aes_key)
  16. buf := make([]byte, 4)
  17. for {
  18. _, err := conn.Read(buf)
  19. errCheckPanic(err, "Connection failed with %s", conn.RemoteAddr().String())
  20. id := binary.LittleEndian.Uint16(buf[:2])
  21. msglen := binary.LittleEndian.Uint16(buf[2:])
  22. fmt.Printf("Connection from ID %d message length %d\n %x\n", id, msglen, buf)
  23. payload := make([]byte, msglen)
  24. _, err = conn.Read(payload)
  25. errCheckPanic(err, "Connection failed %s device #%d", conn.RemoteAddr().String(), id)
  26. fmt.Printf("Payload: %x\n", payload)
  27. message := make([]byte, msglen-16)
  28. c, err := aes.NewCipher(decoded)
  29. errCheckPanic(err, "Decryption failed %s device #%d", conn.RemoteAddr().String(), id)
  30. cbc := cipher.NewCBCEncrypter(c, payload[:16])
  31. cbc.CryptBlocks(payload[16:], message)
  32. fmt.Printf("Message: %x\n", message)
  33. }
  34. }
  35. func serve(address string) {
  36. ln, err := net.Listen("tcp", address)
  37. errCheckExit(err,"Failed accept connection")
  38. defer ln.Close()
  39. fmt.Printf("Service socket ready at %s\n", address)
  40. for {
  41. conn, err := ln.Accept()
  42. errCheckExit(err,"Failed accept connection %s", conn.RemoteAddr().String())
  43. go serveConnection(conn)
  44. }
  45. }