using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace HBLConsole.Communication { public class MqttSign { private string username = ""; private string password = ""; private string clientid = ""; public string getUsername() { return this.username; } public string getPassword() { return this.password; } public string getClientid() { return this.clientid; } public bool calculate(string productKey, string deviceName, string deviceSecret) { if (productKey == null || deviceName == null || deviceSecret == null) { return false; } //MQTT用户名 this.username = deviceName + "&" + productKey; //MQTT密码 String timestamp = Convert.ToInt64((DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds).ToString(); String plainPasswd = "clientId" + productKey + "." + deviceName + "deviceName" + deviceName + "productKey" + productKey + "timestamp" + timestamp; this.password = hmacSha256(plainPasswd, deviceSecret); //MQTT ClientId this.clientid = productKey + "." + deviceName + "|" + "timestamp=" + timestamp + ",_v=paho-c#-1.0.0,securemode=2,signmethod=hmacsha256|"; return true; } public string hmacSha256(string plainText, string key) { var encoding = new System.Text.UTF8Encoding(); byte[] plainTextBytes = encoding.GetBytes(plainText); byte[] keyBytes = encoding.GetBytes(key); HMACSHA256 hmac = new HMACSHA256(keyBytes); byte[] sign = hmac.ComputeHash(plainTextBytes); return BitConverter.ToString(sign).Replace("-", string.Empty); } } }