Skip to content

Instantly share code, notes, and snippets.

@cominging
Last active November 22, 2018 17:57
Show Gist options
  • Save cominging/fbd77d91c3f52170c883fe0cfb925009 to your computer and use it in GitHub Desktop.
Save cominging/fbd77d91c3f52170c883fe0cfb925009 to your computer and use it in GitHub Desktop.
Convert connection string to SAS token for MQTT connection in EasyBuilder Pro. Executable (Win32) can be obtained at: https://www.dropbox.com/s/w0fd7msqcc15cj7/get-mqtt-params.zip
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"fmt"
"log"
"os"
"regexp"
"strconv"
"text/template"
"time"
)
func main() {
if len(os.Args) != 2 {
log.Println("Missing connection string. Example connection string: ostName=saas-iothub-efdc1876-f747-4f6e-95d9-3030c59cc739.azure-devices.net;DeviceId=cMT-8e95;SharedAccessKey=TLhzGZpFZmrAQGWCvBEroxozwSngep82bRikqehfTgg=")
log.Println("Usage: get-mqtt-params.exe <connection string>")
return
}
connString := os.Args[1]
// log.Println("Connection string: " + connString)
re := regexp.MustCompile("HostName=(.*?);DeviceId=(.*?);SharedAccessKey=(.*?)$")
match := re.FindStringSubmatch(connString)
if match == nil {
log.Fatal("Connection string uses a different format?")
}
hostname := match[1]
deviceId := match[2]
sharedAccessKeyEncoded := match[3]
sharedAccessKey, err := base64.StdEncoding.DecodeString(sharedAccessKeyEncoded)
if err != nil {
log.Fatal(err)
}
SaS := createSharedAccessToken(hostname+"/devices/"+deviceId, sharedAccessKey)
fmt.Printf("# Azure Connection Information\n")
fmt.Printf("Cloud service: Normal\n")
fmt.Printf("Protocol: MQTT v3.1.1\n")
fmt.Printf("Domain name: %v\n", hostname)
fmt.Printf("Port: 8883\n")
fmt.Printf("Client ID: %v\n", deviceId)
fmt.Printf("Username: %v\n", hostname+"/"+deviceId)
fmt.Printf("Password: %v\n", SaS)
fmt.Printf("Pub. Topic: %v\n", "devices/"+deviceId+"/messages/events/")
fmt.Printf("Sub. Topic: %v\n", "devices/"+deviceId+"/messages/devicebound/#")
fmt.Printf("[v] Customize length for client ID/username/password\n")
fmt.Printf("[v] TLS/SSL\n")
fmt.Printf("[ ] System Topic(s)\n")
}
func createSharedAccessToken(uri string, saKey []byte) string {
if len(uri) == 0 || len(saKey) == 0 {
return "Missing required parameter"
}
encoded := template.URLQueryEscaper(uri)
now := time.Now().Unix()
tenYear := 60 * 60 * 24 * 365 * 10
ts := now + int64(tenYear)
// week := 60 * 60 * 24 * 7
// ts := now + int64(week)
signature := encoded + "\n" + strconv.Itoa(int(ts))
hmac := hmac.New(sha256.New, saKey)
hmac.Write([]byte(signature))
hmacString := template.URLQueryEscaper(base64.StdEncoding.EncodeToString(hmac.Sum(nil)))
result := "SharedAccessSignature sr=" + encoded + "&sig=" +
hmacString + "&se=" + strconv.Itoa(int(ts))
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment