Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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
- }
Add Comment
Please, Sign In to add comment