util.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package mq
  2. import (
  3. "github.com/gravitl/netmaker/logger"
  4. "github.com/gravitl/netmaker/logic"
  5. "github.com/gravitl/netmaker/netclient/ncutils"
  6. )
  7. func decryptMsg(nodeid string, msg []byte) ([]byte, error) {
  8. logger.Log(0, "found message for decryption: %s \n", string(msg))
  9. trafficKey, trafficErr := logic.RetrieveTrafficKey()
  10. if trafficErr != nil {
  11. return nil, trafficErr
  12. }
  13. return ncutils.DecryptWithPrivateKey(msg, &trafficKey), nil
  14. }
  15. func encrypt(nodeid string, dest string, msg []byte) ([]byte, error) {
  16. var node, err = logic.GetNodeByID(nodeid)
  17. if err != nil {
  18. return nil, err
  19. }
  20. encrypted, encryptErr := ncutils.EncryptWithPublicKey(msg, &node.TrafficKeys.Mine)
  21. if encryptErr != nil {
  22. return nil, encryptErr
  23. }
  24. return encrypted, nil
  25. }
  26. func publish(nodeid string, dest string, msg []byte) error {
  27. client := SetupMQTT()
  28. defer client.Disconnect(250)
  29. encrypted, encryptErr := encrypt(nodeid, dest, msg)
  30. if encryptErr != nil {
  31. return encryptErr
  32. }
  33. if token := client.Publish(dest, 0, false, encrypted); token.Wait() && token.Error() != nil {
  34. return token.Error()
  35. }
  36. return nil
  37. }