You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

56 lines
1.9 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Security.Cryptography;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace HBLConsole.Communication
  8. {
  9. public class MqttSign
  10. {
  11. private string username = "";
  12. private string password = "";
  13. private string clientid = "";
  14. public string getUsername() { return this.username; }
  15. public string getPassword() { return this.password; }
  16. public string getClientid() { return this.clientid; }
  17. public bool calculate(string productKey, string deviceName, string deviceSecret)
  18. {
  19. if (productKey == null || deviceName == null || deviceSecret == null)
  20. {
  21. return false;
  22. }
  23. //MQTT用户名
  24. this.username = deviceName + "&" + productKey;
  25. //MQTT密码
  26. String timestamp = Convert.ToInt64((DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds).ToString();
  27. String plainPasswd = "clientId" + productKey + "." + deviceName + "deviceName" + deviceName + "productKey" + productKey + "timestamp" + timestamp;
  28. this.password = hmacSha256(plainPasswd, deviceSecret);
  29. //MQTT ClientId
  30. this.clientid = productKey + "." + deviceName + "|" + "timestamp=" + timestamp + ",_v=paho-c#-1.0.0,securemode=2,signmethod=hmacsha256|";
  31. return true;
  32. }
  33. public string hmacSha256(string plainText, string key)
  34. {
  35. var encoding = new System.Text.UTF8Encoding();
  36. byte[] plainTextBytes = encoding.GetBytes(plainText);
  37. byte[] keyBytes = encoding.GetBytes(key);
  38. HMACSHA256 hmac = new HMACSHA256(keyBytes);
  39. byte[] sign = hmac.ComputeHash(plainTextBytes);
  40. return BitConverter.ToString(sign).Replace("-", string.Empty);
  41. }
  42. }
  43. }