MQTT AiotMqttOption.java

复制代码
package mqtt;

import java.math.BigInteger;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

/**
 * https://linkkit-export.oss-cn-shanghai.aliyuncs.com/paho/android_sameple_code.zip?spm=a2c63.p38356.0.0.488769ccON8nor&file=android_sameple_code.zip
 * MQTT建连选项类,输入设备三元组productKey, deviceName和deviceSecret, 生成Mqtt建连参数clientId,username和password.
 *
 * @author ZengWenFeng
 * @email 117791303@qq.com
 * @mobile 13805029595
 */
public class AiotMqttOption
{
	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;
	}

	/**
	    * 获取Mqtt建连选项对象
	    * @param productKey 产品秘钥
	    * @param deviceName 设备名称
	    * @param deviceSecret 设备机密
	    * @return AiotMqttOption对象或者NULL
	    */
	public AiotMqttOption getMqttOption(String productKey, String deviceName, String deviceSecret)
	{
		if (productKey == null || deviceName == null || deviceSecret == null)
		{
			return null;
		}

		try
		{
			String timestamp = Long.toString(System.currentTimeMillis());

			// clientId
			this.clientId = productKey + "." + deviceName + "|timestamp=" + timestamp + ",_v=paho-android-1.0.0,securemode=2,signmethod=hmacsha256|";

			// userName
			this.username = deviceName + "&" + productKey;

			// password
			String macSrc = "clientId" + productKey + "." + deviceName + "deviceName" + deviceName + "productKey" + productKey + "timestamp" + timestamp;
			String algorithm = "HmacSHA256";
			Mac mac = Mac.getInstance(algorithm);
			SecretKeySpec secretKeySpec = new SecretKeySpec(deviceSecret.getBytes(), algorithm);
			mac.init(secretKeySpec);
			byte[] macRes = mac.doFinal(macSrc.getBytes());
			password = String.format("%064x", new BigInteger(1, macRes));
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return null;
		}

		return this;
	}
}

MQTT常用语物联网上硬件设备和软件之间的通讯通道

Pet Detection System (PDS)_spencer_tseng的博客-CSDN博客

相关推荐
阿拉斯攀登5 分钟前
深入微服务配置中心:Nacos注册中心的实操细节
java·微服务·云原生·springcloud
f***24116 分钟前
springboot系列--自动配置原理
java·spring boot·后端
一 乐25 分钟前
水果销售|基于springboot + vue水果商城系统(源码+数据库+文档)
java·前端·数据库·vue.js·spring boot·后端
JIngJaneIL26 分钟前
校园任务平台|校园社区系统|基于java+vue的校园悬赏任务平台系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·校园任务平台
三省同学29 分钟前
SpringBoot 项目LOG_PATH_IS_UNDEFINED问题完整解决方案
java·spring boot·后端
阿蔹30 分钟前
抓包工具Charles——介绍、篡改数据、弱网环境测试
java·自动化·抓包·charles
i***683236 分钟前
【MyBatis】spring整合mybatis教程(详细易懂)
java·spring·mybatis
小马爱打代码1 小时前
Spring AI:ChatMemory 实现聊天记忆功能
java·人工智能·spring
小许学java1 小时前
数据结构-模拟实现顺序表和链表
java·数据结构·链表·arraylist·linkedlist·顺序表模拟实现·链表的模拟实现
+VX:Fegn08951 小时前
计算机毕业设计|基于springboot + vue零食商城管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·课程设计