Guest User

Untitled

a guest
Nov 22nd, 2018
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.31 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "crypto/hmac"
  5. "crypto/sha256"
  6. "encoding/base64"
  7. "fmt"
  8. "log"
  9. "os"
  10. "regexp"
  11. "strconv"
  12. "text/template"
  13. "time"
  14. )
  15.  
  16. func main() {
  17. if len(os.Args) != 2 {
  18. log.Println("Missing connection string. Example connection string: ostName=saas-iothub-efdc1876-f747-4f6e-95d9-3030c59cc739.azure-devices.net;DeviceId=cMT-8e95;SharedAccessKey=TLhzGZpFZmrAQGWCvBEroxozwSngep82bRikqehfTgg=")
  19. log.Println("Usage: get-mqtt-params.exe <connection string>")
  20. return
  21. }
  22. connString := os.Args[1]
  23. // log.Println("Connection string: " + connString)
  24. re := regexp.MustCompile("HostName=(.*?);DeviceId=(.*?);SharedAccessKey=(.*?)$")
  25. match := re.FindStringSubmatch(connString)
  26. if match == nil {
  27. log.Fatal("Connection string uses a different format?")
  28. }
  29. hostname := match[1]
  30. deviceId := match[2]
  31. sharedAccessKeyEncoded := match[3]
  32. sharedAccessKey, err := base64.StdEncoding.DecodeString(sharedAccessKeyEncoded)
  33. if err != nil {
  34. log.Fatal(err)
  35. }
  36.  
  37. SaS := createSharedAccessToken(hostname+"/devices/"+deviceId, sharedAccessKey)
  38.  
  39. fmt.Printf("# Azure Connection Information\n")
  40. fmt.Printf("Cloud service: Normal\n")
  41. fmt.Printf("Protocol: MQTT v3.1.1\n")
  42. fmt.Printf("Domain name: %v\n", hostname)
  43. fmt.Printf("Port: 8883\n")
  44. fmt.Printf("Client ID: %v\n", deviceId)
  45. fmt.Printf("Username: %v\n", hostname+"/"+deviceId)
  46. fmt.Printf("Password: %v\n", SaS)
  47. fmt.Printf("Pub. Topic: %v\n", "devices/"+deviceId+"/messages/events/")
  48. fmt.Printf("Sub. Topic: %v\n", "devices/"+deviceId+"/messages/devicebound/#")
  49.  
  50. fmt.Printf("[v] Customize length for client ID/username/password\n")
  51. fmt.Printf("[v] TLS/SSL\n")
  52. fmt.Printf("[ ] System Topic(s)\n")
  53. }
  54.  
  55. func createSharedAccessToken(uri string, saKey []byte) string {
  56.  
  57. if len(uri) == 0 || len(saKey) == 0 {
  58. return "Missing required parameter"
  59. }
  60.  
  61. encoded := template.URLQueryEscaper(uri)
  62. now := time.Now().Unix()
  63. tenYear := 60 * 60 * 24 * 365 * 10
  64. ts := now + int64(tenYear)
  65. // week := 60 * 60 * 24 * 7
  66. // ts := now + int64(week)
  67. signature := encoded + "\n" + strconv.Itoa(int(ts))
  68. hmac := hmac.New(sha256.New, saKey)
  69. hmac.Write([]byte(signature))
  70. hmacString := template.URLQueryEscaper(base64.StdEncoding.EncodeToString(hmac.Sum(nil)))
  71.  
  72. result := "SharedAccessSignature sr=" + encoded + "&sig=" +
  73. hmacString + "&se=" + strconv.Itoa(int(ts))
  74. return result
  75. }
Add Comment
Please, Sign In to add comment